geometry.go 14 KB

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