geometry.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. // Geometry encapsulates a three-dimensional geometric shape.
  16. type Geometry struct {
  17. refcount int // Current number of references
  18. vbos []*gls.VBO // Array of VBOs
  19. groups []Group // Array geometry groups
  20. indices math32.ArrayU32 // Buffer with indices
  21. gs *gls.GLS // Pointer to gl context. Valid after first render setup
  22. handleVAO uint32 // Handle to OpenGL VAO
  23. handleIndices uint32 // Handle to OpenGL buffer for indices
  24. updateIndices bool // Flag to indicate that indices must be transferred
  25. // Geometric properties
  26. boundingBox math32.Box3 // Last calculated bounding box
  27. boundingSphere math32.Sphere // Last calculated bounding sphere
  28. area float32 // Last calculated area
  29. volume float32 // Last calculated volume
  30. rotInertia math32.Matrix3 // Last calculated rotational inertia matrix
  31. // Flags indicating whether geometric properties are valid
  32. boundingBoxValid bool // Indicates if last calculated bounding box is valid
  33. boundingSphereValid bool // Indicates if last calculated bounding sphere is valid
  34. areaValid bool // Indicates if last calculated area is valid
  35. volumeValid bool // Indicates if last calculated volume is valid
  36. rotInertiaValid bool // Indicates if last calculated rotational inertia matrix is valid
  37. }
  38. // Geometry group object
  39. type Group struct {
  40. Start int // Index of first element of the group
  41. Count int // Number of elements in the group
  42. Matindex int // Material index for this group
  43. Matid string // Material id used when loading external models
  44. }
  45. func NewGeometry() *Geometry {
  46. g := new(Geometry)
  47. g.Init()
  48. return g
  49. }
  50. // Init initializes the geometry
  51. func (g *Geometry) Init() {
  52. g.refcount = 1
  53. g.vbos = make([]*gls.VBO, 0)
  54. g.groups = make([]Group, 0)
  55. g.gs = nil
  56. g.handleVAO = 0
  57. g.handleIndices = 0
  58. g.updateIndices = true
  59. }
  60. // Incref increments the reference count for this geometry
  61. // and returns a pointer to the geometry.
  62. // It should be used when this geometry is shared by another
  63. // Graphic object.
  64. func (g *Geometry) Incref() *Geometry {
  65. g.refcount++
  66. return g
  67. }
  68. // Dispose decrements this geometry reference count and
  69. // if necessary releases OpenGL resources, C memory
  70. // and VBOs associated with this geometry.
  71. func (g *Geometry) Dispose() {
  72. if g.refcount > 1 {
  73. g.refcount--
  74. return
  75. }
  76. // Delete VAO and indices buffer
  77. if g.gs != nil {
  78. g.gs.DeleteVertexArrays(g.handleVAO)
  79. g.gs.DeleteBuffers(g.handleIndices)
  80. }
  81. // Delete this geometry VBO buffers
  82. for i := 0; i < len(g.vbos); i++ {
  83. g.vbos[i].Dispose()
  84. }
  85. g.Init()
  86. }
  87. func (g *Geometry) GetGeometry() *Geometry {
  88. return g
  89. }
  90. // AddGroup adds a geometry group (for multimaterial)
  91. func (g *Geometry) AddGroup(start, count, matIndex int) *Group {
  92. g.groups = append(g.groups, Group{start, count, matIndex, ""})
  93. return &g.groups[len(g.groups)-1]
  94. }
  95. // AddGroupList adds the specified list of groups to this geometry
  96. func (g *Geometry) AddGroupList(groups []Group) {
  97. for _, group := range groups {
  98. g.groups = append(g.groups, group)
  99. }
  100. }
  101. // GroupCount returns the number of geometry groups (for multimaterial)
  102. func (g *Geometry) GroupCount() int {
  103. return len(g.groups)
  104. }
  105. // GroupAt returns pointer to geometry group at the specified index
  106. func (g *Geometry) GroupAt(idx int) *Group {
  107. return &g.groups[idx]
  108. }
  109. // SetIndices sets the indices array for this geometry
  110. func (g *Geometry) SetIndices(indices math32.ArrayU32) {
  111. g.indices = indices
  112. g.updateIndices = true
  113. g.boundingBoxValid = false
  114. g.boundingSphereValid = false
  115. }
  116. // Indices returns this geometry indices array
  117. func (g *Geometry) Indices() math32.ArrayU32 {
  118. return g.indices
  119. }
  120. // AddVBO adds a Vertex Buffer Object for this geometry
  121. func (g *Geometry) AddVBO(vbo *gls.VBO) {
  122. // Check that the provided VBO doesn't have conflicting attributes with existing VBOs
  123. for _, existingVbo := range g.vbos {
  124. for _, attrib := range vbo.Attributes() {
  125. if existingVbo.Attrib(attrib.Name) != nil {
  126. panic("Geometry.AddVBO: geometry already has a VBO with attribute " + attrib.Name)
  127. }
  128. }
  129. }
  130. g.vbos = append(g.vbos, vbo)
  131. }
  132. // VBO returns a pointer to this geometry's VBO which contain the specified attribute.
  133. // Returns nil if the VBO is not found.
  134. func (g *Geometry) VBO(attrib string) *gls.VBO {
  135. for _, vbo := range g.vbos {
  136. if vbo.Attrib(attrib) != nil {
  137. return vbo
  138. }
  139. }
  140. return nil
  141. }
  142. // Returns the number of items in the first VBO
  143. // (The number of items should be same for all VBOs)
  144. // An item is a complete group of attributes in the VBO buffer
  145. func (g *Geometry) Items() int {
  146. if len(g.vbos) == 0 {
  147. return 0
  148. }
  149. vbo := g.vbos[0]
  150. if vbo.AttribCount() == 0 {
  151. return 0
  152. }
  153. return vbo.Buffer().Bytes() / vbo.StrideSize()
  154. }
  155. // OperateOnVertices iterates over all the vertices and calls
  156. // the specified callback function with a pointer to each vertex.
  157. // The vertex pointers can be modified inside the callback and
  158. // the modifications will be applied to the buffer at each iteration.
  159. // The callback function returns false to continue or true to break.
  160. func (g *Geometry) OperateOnVertices(cb func(vertex *math32.Vector3) bool) {
  161. // Get buffer with position vertices
  162. vbo := g.VBO("VertexPosition")
  163. if vbo == nil {
  164. return
  165. }
  166. vbo.OperateOnVectors3("VertexPosition", cb)
  167. }
  168. // ReadVertices iterates over all the vertices and calls
  169. // the specified callback function with the value of each vertex.
  170. // The callback function returns false to continue or true to break.
  171. func (g *Geometry) ReadVertices(cb func(vertex math32.Vector3) bool) {
  172. // Get buffer with position vertices
  173. vbo := g.VBO("VertexPosition")
  174. if vbo == nil {
  175. return
  176. }
  177. vbo.ReadVectors3("VertexPosition", cb)
  178. }
  179. // OperateOnVertexNormals iterates over all the vertex normals
  180. // and calls the specified callback function with a pointer to each normal.
  181. // The vertex pointers can be modified inside the callback and
  182. // the modifications will be applied to the buffer at each iteration.
  183. // The callback function returns false to continue or true to break.
  184. func (g *Geometry) OperateOnVertexNormals(cb func(normal *math32.Vector3) bool) {
  185. // Get buffer with position vertices
  186. vbo := g.VBO("VertexNormal")
  187. if vbo == nil {
  188. return
  189. }
  190. vbo.OperateOnVectors3("VertexNormal", cb)
  191. }
  192. // ReadVertexNormals iterates over all the vertex normals and calls
  193. // the specified callback function with the value of each normal.
  194. // The callback function returns false to continue or true to break.
  195. func (g *Geometry) ReadVertexNormals(cb func(vertex math32.Vector3) bool) {
  196. // Get buffer with position vertices
  197. vbo := g.VBO("VertexNormal")
  198. if vbo == nil {
  199. return
  200. }
  201. vbo.ReadVectors3("VertexNormal", cb)
  202. }
  203. // ReadFaces iterates over all the vertices and calls
  204. // the specified callback function with face-forming vertex triples.
  205. // The callback function returns false to continue or true to break.
  206. func (g *Geometry) ReadFaces(cb func(vA, vB, vC math32.Vector3) bool) {
  207. // Get buffer with position vertices
  208. vbo := g.VBO("VertexPosition")
  209. if vbo == nil {
  210. return
  211. }
  212. // If geometry has indexed vertices need to loop over indexes
  213. if g.Indexed() {
  214. var vA, vB, vC math32.Vector3
  215. positions := vbo.Buffer()
  216. for i := 0; i < g.indices.Size(); i += 3 {
  217. // Get face vertices
  218. positions.GetVector3(int(3*g.indices[i]), &vA)
  219. positions.GetVector3(int(3*g.indices[i+1]), &vB)
  220. positions.GetVector3(int(3*g.indices[i+2]), &vC)
  221. // Call callback with face vertices
  222. brk := cb(vA, vB, vC)
  223. if brk {
  224. break
  225. }
  226. }
  227. } else {
  228. // Geometry does NOT have indexed vertices - can read vertices in sequence
  229. vbo.ReadTripleVectors3("VertexPosition", cb)
  230. }
  231. }
  232. // TODO Read and Operate on Texcoords, Faces, Edges, FaceNormals, etc...
  233. // Indexed returns whether the geometry is indexed or not.
  234. func (g *Geometry) Indexed() bool {
  235. return g.indices.Size() > 0
  236. }
  237. // BoundingBox computes the bounding box of the geometry if necessary
  238. // and returns is value
  239. func (g *Geometry) BoundingBox() math32.Box3 {
  240. // If valid, return its value
  241. if g.boundingBoxValid {
  242. return g.boundingBox
  243. }
  244. // Reset bounding box
  245. g.boundingBox.Min.Set(0, 0, 0)
  246. g.boundingBox.Max.Set(0, 0, 0)
  247. // Expand bounding box by each vertex
  248. g.ReadVertices(func(vertex math32.Vector3) bool {
  249. g.boundingBox.ExpandByPoint(&vertex)
  250. return false
  251. })
  252. g.boundingBoxValid = true
  253. return g.boundingBox
  254. }
  255. // BoundingSphere computes the bounding sphere of this geometry
  256. // if necessary and returns its value.
  257. func (g *Geometry) BoundingSphere() math32.Sphere {
  258. // If valid, return its value
  259. if g.boundingSphereValid {
  260. return g.boundingSphere
  261. }
  262. // Reset radius, calculate bounding box and copy center
  263. g.boundingSphere.Radius = float32(0)
  264. box := g.BoundingBox()
  265. box.Center(&g.boundingSphere.Center)
  266. // Find the radius of the bounding sphere
  267. maxRadiusSq := float32(0)
  268. g.ReadVertices(func(vertex math32.Vector3) bool {
  269. maxRadiusSq = math32.Max(maxRadiusSq, g.boundingSphere.Center.DistanceToSquared(&vertex))
  270. return false
  271. })
  272. g.boundingSphere.Radius = float32(math32.Sqrt(maxRadiusSq))
  273. g.boundingSphereValid = true
  274. return g.boundingSphere
  275. }
  276. // Area returns the surface area.
  277. // NOTE: This only works for triangle-based meshes.
  278. func (g *Geometry) Area() float32 {
  279. // If valid, return its value
  280. if g.areaValid {
  281. return g.area
  282. }
  283. // Reset area
  284. g.area = 0
  285. // Sum area of all triangles
  286. g.ReadFaces(func(vA, vB, vC math32.Vector3) bool {
  287. vA.Sub(&vC)
  288. vB.Sub(&vC)
  289. vC.CrossVectors(&vA, &vB)
  290. g.area += vC.Length() / 2.0
  291. return false
  292. })
  293. g.areaValid = true
  294. return g.area
  295. }
  296. // Volume returns the volume.
  297. // NOTE: This only works for closed triangle-based meshes.
  298. func (g *Geometry) Volume() float32 {
  299. // If valid, return its value
  300. if g.volumeValid {
  301. return g.volume
  302. }
  303. // Reset volume
  304. g.volume = 0
  305. // Calculate volume of all tetrahedrons
  306. g.ReadFaces(func(vA, vB, vC math32.Vector3) bool {
  307. vA.Sub(&vC)
  308. vB.Sub(&vC)
  309. g.volume += vC.Dot(vA.Cross(&vB)) / 6.0
  310. return false
  311. })
  312. g.volumeValid = true
  313. return g.volume
  314. }
  315. // RotationalInertia returns the rotational inertia tensor, also known as the moment of inertia.
  316. // This assumes constant density of 1 (kg/m^2).
  317. // To adjust for a different constant density simply scale the returning matrix by the density.
  318. func (g *Geometry) RotationalInertia() math32.Matrix3 {
  319. // If valid, return its value
  320. if g.rotInertiaValid {
  321. return g.rotInertia
  322. }
  323. // Reset rotational inertia
  324. g.rotInertia.Zero()
  325. // For now approximate result based on bounding box
  326. b := math32.NewVec3()
  327. box := g.BoundingBox()
  328. box.Size(b)
  329. multiplier := g.Volume() / 12.0
  330. x := (b.Y*b.Y + b.Z*b.Z) * multiplier
  331. y := (b.X*b.X + b.Z*b.Z) * multiplier
  332. z := (b.Y*b.Y + b.X*b.X) * multiplier
  333. g.rotInertia.Set(
  334. x, 0, 0,
  335. 0, y, 0,
  336. 0, 0, z,
  337. )
  338. return g.rotInertia
  339. }
  340. // ProjectOntoAxis projects the geometry onto the specified axis,
  341. // effectively squashing it into a line passing through the local origin.
  342. // Returns the maximum and the minimum values on that line (i.e. signed distances from the local origin).
  343. func (g *Geometry) ProjectOntoAxis(localAxis *math32.Vector3) (float32, float32) {
  344. var max, min float32
  345. g.ReadVertices(func(vertex math32.Vector3) bool {
  346. val := vertex.Dot(localAxis)
  347. if val > max {
  348. max = val
  349. }
  350. if val < min {
  351. min = val
  352. }
  353. return false
  354. })
  355. return max, min
  356. }
  357. // TODO:
  358. // https://stackoverflow.com/questions/21640545/how-to-check-for-convexity-of-a-3d-mesh
  359. // func (g *Geometry) IsConvex() bool {
  360. //
  361. // {
  362. // ApplyMatrix multiplies each of the geometry position vertices
  363. // by the specified matrix and apply the correspondent normal
  364. // transform matrix to the geometry normal vectors.
  365. // The geometry's bounding box and sphere are recomputed if needed.
  366. func (g *Geometry) ApplyMatrix(m *math32.Matrix4) {
  367. // Apply matrix to all vertices
  368. g.OperateOnVertices(func(vertex *math32.Vector3) bool {
  369. vertex.ApplyMatrix4(m)
  370. return false
  371. })
  372. // Apply normal matrix to all normal vectors
  373. var normalMatrix math32.Matrix3
  374. normalMatrix.GetNormalMatrix(m)
  375. g.OperateOnVertexNormals(func(normal *math32.Vector3) bool {
  376. normal.ApplyMatrix3(&normalMatrix).Normalize()
  377. return false
  378. })
  379. }
  380. // RenderSetup is called by the renderer before drawing the geometry
  381. func (g *Geometry) RenderSetup(gs *gls.GLS) {
  382. // First time initialization
  383. if g.gs == nil {
  384. // Generates VAO and binds it
  385. g.handleVAO = gs.GenVertexArray()
  386. gs.BindVertexArray(g.handleVAO)
  387. // Generates VBO for indices
  388. g.handleIndices = gs.GenBuffer()
  389. // Saves pointer to gl indicating initialization was done.
  390. g.gs = gs
  391. }
  392. // Update VBOs
  393. gs.BindVertexArray(g.handleVAO)
  394. for _, vbo := range g.vbos {
  395. vbo.Transfer(gs)
  396. }
  397. // Updates Indices buffer if necessary
  398. if g.indices.Size() > 0 && g.updateIndices {
  399. gs.BindBuffer(gls.ELEMENT_ARRAY_BUFFER, g.handleIndices)
  400. gs.BufferData(gls.ELEMENT_ARRAY_BUFFER, g.indices.Bytes(), g.indices, gls.STATIC_DRAW)
  401. g.updateIndices = false
  402. }
  403. }