geometry.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package geometry
  5. import (
  6. "github.com/g3n/engine/gls"
  7. "github.com/g3n/engine/math32"
  8. )
  9. // Interface for all geometries
  10. type IGeometry interface {
  11. GetGeometry() *Geometry
  12. RenderSetup(gs *gls.GLS)
  13. Dispose()
  14. }
  15. type Geometry struct {
  16. refcount int // Current number of references
  17. vbos []*gls.VBO // Array of VBOs
  18. groups []Group // Array geometry groups
  19. indices math32.ArrayU32 // Buffer with indices
  20. gs *gls.GLS // Pointer to gl context. Valid after first render setup
  21. handleVAO uint32 // Handle to OpenGL VAO
  22. handleIndices uint32 // Handle to OpenGL buffer for indices
  23. updateIndices bool // Flag to indicate that indices must be transferred
  24. boundingBox math32.Box3 // Last calculated bounding box
  25. boundingBoxValid bool // Indicates if last calculated bounding box is valid
  26. boundingSphere math32.Sphere // Last calculated bounding sphere
  27. boundingSphereValid bool // Indicates if last calculated bounding sphere is valid
  28. }
  29. // Geometry group object
  30. type Group struct {
  31. Start int // Index of first element of the group
  32. Count int // Number of elements in the group
  33. Matindex int // Material index for this group
  34. Matid string // Material id used when loading external models
  35. }
  36. func NewGeometry() *Geometry {
  37. g := new(Geometry)
  38. g.Init()
  39. return g
  40. }
  41. // Init initializes the geometry
  42. func (g *Geometry) Init() {
  43. g.refcount = 1
  44. g.vbos = make([]*gls.VBO, 0)
  45. g.groups = make([]Group, 0)
  46. g.gs = nil
  47. g.handleVAO = 0
  48. g.handleIndices = 0
  49. g.updateIndices = true
  50. }
  51. // Incref increments the reference count for this geometry
  52. // and returns a pointer to the geometry.
  53. // It should be used when this geometry is shared by another
  54. // Graphic object.
  55. func (g *Geometry) Incref() *Geometry {
  56. g.refcount++
  57. return g
  58. }
  59. // Dispose decrements this geometry reference count and
  60. // if necessary releases OpenGL resources, C memory
  61. // and VBOs associated with this geometry.
  62. func (g *Geometry) Dispose() {
  63. if g.refcount > 1 {
  64. g.refcount--
  65. return
  66. }
  67. if g.gs != nil {
  68. g.gs.DeleteVertexArrays(g.handleVAO)
  69. g.gs.DeleteBuffers(g.handleIndices)
  70. }
  71. g.Init()
  72. }
  73. func (g *Geometry) GetGeometry() *Geometry {
  74. return g
  75. }
  76. // AddGroup adds a geometry group (for multimaterial)
  77. func (g *Geometry) AddGroup(start, count, matIndex int) *Group {
  78. g.groups = append(g.groups, Group{start, count, matIndex, ""})
  79. return &g.groups[len(g.groups)-1]
  80. }
  81. // AddGroupList adds the specified list of groups to this geometry
  82. func (g *Geometry) AddGroupList(groups []Group) {
  83. for _, group := range groups {
  84. g.groups = append(g.groups, group)
  85. }
  86. }
  87. // GroupCount returns the number of geometry groups (for multimaterial)
  88. func (g *Geometry) GroupCount() int {
  89. return len(g.groups)
  90. }
  91. // GroupAt returns pointer to geometry group at the specified index
  92. func (g *Geometry) GroupAt(idx int) *Group {
  93. return &g.groups[idx]
  94. }
  95. // SetIndices sets the indices array for this geometry
  96. func (g *Geometry) SetIndices(indices math32.ArrayU32) {
  97. g.indices = indices
  98. g.boundingBoxValid = false
  99. g.boundingSphereValid = false
  100. }
  101. // Indices returns this geometry indices array
  102. func (g *Geometry) Indices() math32.ArrayU32 {
  103. return g.indices
  104. }
  105. // AddVBO adds a Vertex Buffer Object for this geometry
  106. func (g *Geometry) AddVBO(vbo *gls.VBO) {
  107. g.vbos = append(g.vbos, vbo)
  108. }
  109. // VBO returns a pointer to this geometry VBO for the specified attribute.
  110. // Returns nil if the VBO is not found.
  111. func (g *Geometry) VBO(attrib string) *gls.VBO {
  112. for _, vbo := range g.vbos {
  113. if vbo.Attrib(attrib) != nil {
  114. return vbo
  115. }
  116. }
  117. return nil
  118. }
  119. // Returns the number of items in the first VBO
  120. // (The number of items should be same for all VBOs)
  121. // An item is a complete group of attributes in the VBO buffer
  122. func (g *Geometry) Items() int {
  123. if len(g.vbos) == 0 {
  124. return 0
  125. }
  126. vbo := g.vbos[0]
  127. if vbo.AttribCount() == 0 {
  128. return 0
  129. }
  130. return vbo.Buffer().Bytes() / vbo.Stride()
  131. }
  132. // BoundingBox computes the bounding box of the geometry if necessary
  133. // and returns is value
  134. func (g *Geometry) BoundingBox() math32.Box3 {
  135. // If valid, returns its value
  136. if g.boundingBoxValid {
  137. return g.boundingBox
  138. }
  139. // Get buffer with position vertices
  140. vbPos := g.VBO("VertexPosition")
  141. if vbPos == nil {
  142. return g.boundingBox
  143. }
  144. positions := vbPos.Buffer()
  145. // Calculates bounding box
  146. var vertex math32.Vector3
  147. g.boundingBox.Min.Set(0, 0, 0)
  148. g.boundingBox.Max.Set(0, 0, 0)
  149. for i := 0; i < positions.Size(); i += 3 {
  150. positions.GetVector3(i, &vertex)
  151. g.boundingBox.ExpandByPoint(&vertex)
  152. }
  153. g.boundingBoxValid = true
  154. return g.boundingBox
  155. }
  156. // BoundingSphere computes the bounding sphere of this geometry
  157. // if necessary and returns its value.
  158. func (g *Geometry) BoundingSphere() math32.Sphere {
  159. // if valid, returns its value
  160. if g.boundingSphereValid {
  161. return g.boundingSphere
  162. }
  163. // Get buffer with position vertices
  164. vbPos := g.VBO("VertexPosition")
  165. if vbPos == nil {
  166. return g.boundingSphere
  167. }
  168. positions := vbPos.Buffer()
  169. // Get/calculates the bounding box
  170. box := g.BoundingBox()
  171. // Sets the center of the bounding sphere the same as the center of the bounding box.
  172. box.Center(&g.boundingSphere.Center)
  173. center := g.boundingSphere.Center
  174. // Find the radius of the bounding sphere
  175. maxRadiusSq := float32(0.0)
  176. for i := 0; i < positions.Size(); i += 3 {
  177. var vertex math32.Vector3
  178. positions.GetVector3(i, &vertex)
  179. maxRadiusSq = math32.Max(maxRadiusSq, center.DistanceToSquared(&vertex))
  180. }
  181. radius := math32.Sqrt(maxRadiusSq)
  182. if math32.IsNaN(radius) {
  183. panic("geometry.BoundingSphere: computed radius is NaN")
  184. }
  185. g.boundingSphere.Radius = float32(radius)
  186. g.boundingSphereValid = true
  187. return g.boundingSphere
  188. }
  189. // ApplyMatrix multiplies each of the geometry position vertices
  190. // by the specified matrix and apply the correspondent normal
  191. // transform matrix to the geometry normal vectors.
  192. // The geometry's bounding box and sphere are recomputed if needed.
  193. func (g *Geometry) ApplyMatrix(m *math32.Matrix4) {
  194. // Get positions buffer
  195. vboPos := g.VBO("VertexPosition")
  196. if vboPos == nil {
  197. return
  198. }
  199. positions := vboPos.Buffer()
  200. // Apply matrix to all position vertices
  201. for i := 0; i < positions.Size(); i += 3 {
  202. var vertex math32.Vector3
  203. positions.GetVector3(i, &vertex)
  204. vertex.ApplyMatrix4(m)
  205. positions.SetVector3(i, &vertex)
  206. }
  207. vboPos.Update()
  208. // Get normals buffer
  209. vboNormals := g.VBO("VertexNormal")
  210. if vboNormals == nil {
  211. return
  212. }
  213. normals := vboNormals.Buffer()
  214. // Apply normal matrix to all normal vectors
  215. var normalMatrix math32.Matrix3
  216. normalMatrix.GetNormalMatrix(m)
  217. for i := 0; i < normals.Size(); i += 3 {
  218. var vertex math32.Vector3
  219. normals.GetVector3(i, &vertex)
  220. vertex.ApplyMatrix3(&normalMatrix).Normalize()
  221. normals.SetVector3(i, &vertex)
  222. }
  223. vboNormals.Update()
  224. }
  225. // RenderSetup is called by the renderer before drawing the geometry
  226. func (g *Geometry) RenderSetup(gs *gls.GLS) {
  227. // First time initialization
  228. if g.gs == nil {
  229. // Generates VAO and binds it
  230. g.handleVAO = gs.GenVertexArray()
  231. gs.BindVertexArray(g.handleVAO)
  232. // Generates VBO for indices
  233. g.handleIndices = gs.GenBuffer()
  234. // Saves pointer to gl indicating initialization was done.
  235. g.gs = gs
  236. }
  237. // Update VBOs
  238. gs.BindVertexArray(g.handleVAO)
  239. for _, vbo := range g.vbos {
  240. vbo.Transfer(gs)
  241. }
  242. // Updates Indices buffer if necessary
  243. if g.indices.Size() > 0 && g.updateIndices {
  244. gs.BindBuffer(gls.ELEMENT_ARRAY_BUFFER, g.handleIndices)
  245. gs.BufferData(gls.ELEMENT_ARRAY_BUFFER, g.indices.Bytes(), g.indices, gls.STATIC_DRAW)
  246. g.updateIndices = false
  247. }
  248. }