geometry.go 8.5 KB

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