geometry.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. // Delete VAO and indices buffer
  68. if g.gs != nil {
  69. g.gs.DeleteVertexArrays(g.handleVAO)
  70. g.gs.DeleteBuffers(g.handleIndices)
  71. }
  72. // Delete this geometry VBO buffers
  73. for i := 0; i < len(g.vbos); i++ {
  74. g.vbos[i].Dispose()
  75. }
  76. g.Init()
  77. }
  78. func (g *Geometry) GetGeometry() *Geometry {
  79. return g
  80. }
  81. // AddGroup adds a geometry group (for multimaterial)
  82. func (g *Geometry) AddGroup(start, count, matIndex int) *Group {
  83. g.groups = append(g.groups, Group{start, count, matIndex, ""})
  84. return &g.groups[len(g.groups)-1]
  85. }
  86. // AddGroupList adds the specified list of groups to this geometry
  87. func (g *Geometry) AddGroupList(groups []Group) {
  88. for _, group := range groups {
  89. g.groups = append(g.groups, group)
  90. }
  91. }
  92. // GroupCount returns the number of geometry groups (for multimaterial)
  93. func (g *Geometry) GroupCount() int {
  94. return len(g.groups)
  95. }
  96. // GroupAt returns pointer to geometry group at the specified index
  97. func (g *Geometry) GroupAt(idx int) *Group {
  98. return &g.groups[idx]
  99. }
  100. // SetIndices sets the indices array for this geometry
  101. func (g *Geometry) SetIndices(indices math32.ArrayU32) {
  102. g.indices = indices
  103. g.boundingBoxValid = false
  104. g.boundingSphereValid = false
  105. }
  106. // Indices returns this geometry indices array
  107. func (g *Geometry) Indices() math32.ArrayU32 {
  108. return g.indices
  109. }
  110. // AddVBO adds a Vertex Buffer Object for this geometry
  111. func (g *Geometry) AddVBO(vbo *gls.VBO) {
  112. // Check that the provided VBO doesn't have conflicting attributes with existing VBOs
  113. for _, existingVbo := range g.vbos {
  114. for _, attrib := range vbo.Attributes() {
  115. if existingVbo.Attrib(attrib.Name) != nil {
  116. panic("Geometry.AddVBO: geometry already has a VBO with attribute " + attrib.Name)
  117. }
  118. }
  119. }
  120. g.vbos = append(g.vbos, vbo)
  121. }
  122. // VBO returns a pointer to this geometry's VBO which contain the specified attribute.
  123. // Returns nil if the VBO is not found.
  124. func (g *Geometry) VBO(attrib string) *gls.VBO {
  125. for _, vbo := range g.vbos {
  126. if vbo.Attrib(attrib) != nil {
  127. return vbo
  128. }
  129. }
  130. return nil
  131. }
  132. // Returns the number of items in the first VBO
  133. // (The number of items should be same for all VBOs)
  134. // An item is a complete group of attributes in the VBO buffer
  135. func (g *Geometry) Items() int {
  136. if len(g.vbos) == 0 {
  137. return 0
  138. }
  139. vbo := g.vbos[0]
  140. if vbo.AttribCount() == 0 {
  141. return 0
  142. }
  143. return vbo.Buffer().Bytes() / vbo.StrideSize()
  144. }
  145. // BoundingBox computes the bounding box of the geometry if necessary
  146. // and returns is value
  147. func (g *Geometry) BoundingBox() math32.Box3 {
  148. // If valid, returns its value
  149. if g.boundingBoxValid {
  150. return g.boundingBox
  151. }
  152. // Get buffer with position vertices
  153. vboPos := g.VBO("VertexPosition")
  154. if vboPos == nil {
  155. return g.boundingBox
  156. }
  157. stride := vboPos.Stride()
  158. offset := vboPos.AttribOffset("VertexPosition")
  159. positions := vboPos.Buffer()
  160. // Calculates bounding box
  161. var vertex math32.Vector3
  162. g.boundingBox.Min.Set(0, 0, 0)
  163. g.boundingBox.Max.Set(0, 0, 0)
  164. for i := offset; i < positions.Size(); i += stride {
  165. positions.GetVector3(i, &vertex)
  166. g.boundingBox.ExpandByPoint(&vertex)
  167. }
  168. g.boundingBoxValid = true
  169. return g.boundingBox
  170. }
  171. // BoundingSphere computes the bounding sphere of this geometry
  172. // if necessary and returns its value.
  173. func (g *Geometry) BoundingSphere() math32.Sphere {
  174. // if valid, returns its value
  175. if g.boundingSphereValid {
  176. return g.boundingSphere
  177. }
  178. // Get buffer with position vertices
  179. vboPos := g.VBO("VertexPosition")
  180. if vboPos == nil {
  181. return g.boundingSphere
  182. }
  183. stride := vboPos.Stride()
  184. offset := vboPos.AttribOffset("VertexPosition")
  185. positions := vboPos.Buffer()
  186. // Get/calculates the bounding box
  187. box := g.BoundingBox()
  188. // Sets the center of the bounding sphere the same as the center of the bounding box.
  189. box.Center(&g.boundingSphere.Center)
  190. center := g.boundingSphere.Center
  191. // Find the radius of the bounding sphere
  192. maxRadiusSq := float32(0.0)
  193. for i := offset; i < positions.Size(); i += stride {
  194. var vertex math32.Vector3
  195. positions.GetVector3(i, &vertex)
  196. maxRadiusSq = math32.Max(maxRadiusSq, center.DistanceToSquared(&vertex))
  197. }
  198. radius := math32.Sqrt(maxRadiusSq)
  199. if math32.IsNaN(radius) {
  200. panic("geometry.BoundingSphere: computed radius is NaN")
  201. }
  202. g.boundingSphere.Radius = float32(radius)
  203. g.boundingSphereValid = true
  204. return g.boundingSphere
  205. }
  206. // ApplyMatrix multiplies each of the geometry position vertices
  207. // by the specified matrix and apply the correspondent normal
  208. // transform matrix to the geometry normal vectors.
  209. // The geometry's bounding box and sphere are recomputed if needed.
  210. func (g *Geometry) ApplyMatrix(m *math32.Matrix4) {
  211. // Get positions buffer
  212. vboPos := g.VBO("VertexPosition")
  213. if vboPos == nil {
  214. return
  215. }
  216. stride := vboPos.Stride()
  217. offset := vboPos.AttribOffset("VertexPosition")
  218. positions := vboPos.Buffer()
  219. // Apply matrix to all position vertices
  220. for i := offset; i < positions.Size(); i += stride {
  221. var vertex math32.Vector3
  222. positions.GetVector3(i, &vertex)
  223. vertex.ApplyMatrix4(m)
  224. positions.SetVector3(i, &vertex)
  225. }
  226. vboPos.Update()
  227. // Get normals buffer
  228. vboNormals := g.VBO("VertexNormal")
  229. if vboNormals == nil {
  230. return
  231. }
  232. stride = vboNormals.Stride()
  233. offset = vboNormals.AttribOffset("VertexNormal")
  234. normals := vboNormals.Buffer()
  235. // Apply normal matrix to all normal vectors
  236. var normalMatrix math32.Matrix3
  237. normalMatrix.GetNormalMatrix(m)
  238. for i := offset; i < normals.Size(); i += stride {
  239. var vertex math32.Vector3
  240. normals.GetVector3(i, &vertex)
  241. vertex.ApplyMatrix3(&normalMatrix).Normalize()
  242. normals.SetVector3(i, &vertex)
  243. }
  244. vboNormals.Update()
  245. }
  246. // RenderSetup is called by the renderer before drawing the geometry
  247. func (g *Geometry) RenderSetup(gs *gls.GLS) {
  248. // First time initialization
  249. if g.gs == nil {
  250. // Generates VAO and binds it
  251. g.handleVAO = gs.GenVertexArray()
  252. gs.BindVertexArray(g.handleVAO)
  253. // Generates VBO for indices
  254. g.handleIndices = gs.GenBuffer()
  255. // Saves pointer to gl indicating initialization was done.
  256. g.gs = gs
  257. }
  258. // Update VBOs
  259. gs.BindVertexArray(g.handleVAO)
  260. for _, vbo := range g.vbos {
  261. vbo.Transfer(gs)
  262. }
  263. // Updates Indices buffer if necessary
  264. if g.indices.Size() > 0 && g.updateIndices {
  265. gs.BindBuffer(gls.ELEMENT_ARRAY_BUFFER, g.handleIndices)
  266. gs.BufferData(gls.ELEMENT_ARRAY_BUFFER, g.indices.Bytes(), g.indices, gls.STATIC_DRAW)
  267. g.updateIndices = false
  268. }
  269. }