geometry.go 15 KB

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