node.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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 core
  5. import (
  6. "github.com/g3n/engine/gls"
  7. "github.com/g3n/engine/math32"
  8. "strings"
  9. )
  10. // INode is the interface for all node types.
  11. type INode interface {
  12. IDispatcher
  13. GetNode() *Node
  14. UpdateMatrixWorld()
  15. Raycast(*Raycaster, *[]Intersect)
  16. BoundingBox() math32.Box3
  17. Render(gs *gls.GLS)
  18. Dispose()
  19. }
  20. // Node represents an object in 3D space existing within a hierarchy.
  21. type Node struct {
  22. Dispatcher // Embedded event dispatcher
  23. parent INode // Parent node
  24. children []INode // Children nodes
  25. name string // Optional node name
  26. loaderID string // ID used by loader
  27. visible bool // Whether the node is visible
  28. matNeedsUpdate bool // Whether the the local matrix needs to be updated because position or scale has changed
  29. rotNeedsUpdate bool // Whether the euler rotation and local matrix need to be updated because the quaternion has changed
  30. userData interface{} // Generic user data
  31. // Spatial properties
  32. position math32.Vector3 // Node position in 3D space (relative to parent)
  33. scale math32.Vector3 // Node scale (relative to parent)
  34. direction math32.Vector3 // Initial direction (relative to parent)
  35. rotation math32.Vector3 // Node rotation specified in Euler angles (relative to parent)
  36. quaternion math32.Quaternion // Node rotation specified as a Quaternion (relative to parent)
  37. matrix math32.Matrix4 // Local transform matrix. Contains all position/rotation/scale information (relative to parent)
  38. matrixWorld math32.Matrix4 // World transform matrix. Contains all absolute position/rotation/scale information (i.e. relative to very top parent, generally the scene)
  39. }
  40. // NewNode returns a pointer to a new Node.
  41. func NewNode() *Node {
  42. n := new(Node)
  43. n.Init()
  44. return n
  45. }
  46. // Init initializes the node.
  47. // Normally called by other types which embed a Node.
  48. func (n *Node) Init() {
  49. n.Dispatcher.Initialize()
  50. n.children = make([]INode, 0)
  51. n.visible = true
  52. // Initialize spatial properties
  53. n.position.Set(0, 0, 0)
  54. n.scale.Set(1, 1, 1)
  55. n.direction.Set(0, 0, 1)
  56. n.rotation.Set(0, 0, 0)
  57. n.quaternion.Set(0, 0, 0, 1)
  58. n.matrix.Identity()
  59. n.matrixWorld.Identity()
  60. }
  61. // GetNode satisfies the INode interface
  62. // and returns a pointer to the embedded Node.
  63. func (n *Node) GetNode() *Node {
  64. return n
  65. }
  66. // Raycast satisfies the INode interface.
  67. func (n *Node) Raycast(rc *Raycaster, intersects *[]Intersect) {
  68. }
  69. // BoundingBox satisfies the INode interface.
  70. func (n *Node) BoundingBox() math32.Box3 {
  71. bbox := math32.Box3{n.position, n.position}
  72. for _, inode := range n.Children() {
  73. childBbox := inode.BoundingBox()
  74. bbox.Union(&childBbox)
  75. }
  76. return bbox
  77. }
  78. // Render satisfies the INode interface.
  79. func (n *Node) Render(gs *gls.GLS) {
  80. }
  81. // Dispose satisfies the INode interface.
  82. func (n *Node) Dispose() {
  83. }
  84. // SetParent sets the parent.
  85. func (n *Node) SetParent(iparent INode) {
  86. n.parent = iparent
  87. }
  88. // Parent returns the parent.
  89. func (n *Node) Parent() INode {
  90. return n.parent
  91. }
  92. // SetName sets the (optional) name.
  93. // The name can be used for debugging or other purposes.
  94. func (n *Node) SetName(name string) {
  95. n.name = name
  96. }
  97. // Name returns the (optional) name.
  98. func (n *Node) Name() string {
  99. return n.name
  100. }
  101. // SetLoaderID is normally used by external loaders, such as Collada,
  102. // to assign an ID to the node with the ID value in the node description.
  103. // Can be used to find other loaded nodes.
  104. func (n *Node) SetLoaderID(id string) {
  105. n.loaderID = id
  106. }
  107. // LoaderID returns an optional ID set when this node was
  108. // created by an external loader such as Collada.
  109. func (n *Node) LoaderID() string {
  110. return n.loaderID
  111. }
  112. // SetVisible sets the visibility of the node.
  113. func (n *Node) SetVisible(state bool) {
  114. n.visible = state
  115. n.matNeedsUpdate = true
  116. }
  117. // Visible returns the visibility of the node.
  118. func (n *Node) Visible() bool {
  119. return n.visible
  120. }
  121. // SetChanged sets the matNeedsUpdate flag of the node.
  122. func (n *Node) SetChanged(changed bool) {
  123. n.matNeedsUpdate = changed
  124. }
  125. // Changed returns the matNeedsUpdate flag of the node.
  126. func (n *Node) Changed() bool {
  127. return n.matNeedsUpdate
  128. }
  129. // SetUserData sets the generic user data associated to the node.
  130. func (n *Node) SetUserData(data interface{}) {
  131. n.userData = data
  132. }
  133. // UserData returns the generic user data associated to the node.
  134. func (n *Node) UserData() interface{} {
  135. return n.userData
  136. }
  137. // FindPath finds a node with the specified path starting with this node and
  138. // searching in all its children recursively.
  139. // A path is the sequence of the names from the first node to the desired node
  140. // separated by the forward slash.
  141. func (n *Node) FindPath(path string) INode {
  142. // Internal recursive function to find node
  143. var finder func(inode INode, path string) INode
  144. finder = func(inode INode, path string) INode {
  145. // Get first component of the path
  146. parts := strings.Split(path, "/")
  147. if len(parts) == 0 {
  148. return nil
  149. }
  150. first := parts[0]
  151. // Checks current node
  152. node := inode.GetNode()
  153. if node.name != first {
  154. return nil
  155. }
  156. // If the path has finished this is the desired node
  157. rest := strings.Join(parts[1:], "/")
  158. if rest == "" {
  159. return inode
  160. }
  161. // Otherwise search in this node children
  162. for _, ichild := range node.children {
  163. found := finder(ichild, rest)
  164. if found != nil {
  165. return found
  166. }
  167. }
  168. return nil
  169. }
  170. return finder(n, path)
  171. }
  172. // FindLoaderID looks in the specified node and in all its children
  173. // for a node with the specified loaderID and if found returns it.
  174. // Returns nil if not found.
  175. func (n *Node) FindLoaderID(id string) INode {
  176. var finder func(parent INode, id string) INode
  177. finder = func(parent INode, id string) INode {
  178. pnode := parent.GetNode()
  179. if pnode.loaderID == id {
  180. return parent
  181. }
  182. for _, child := range pnode.children {
  183. found := finder(child, id)
  184. if found != nil {
  185. return found
  186. }
  187. }
  188. return nil
  189. }
  190. return finder(n, id)
  191. }
  192. // Children returns the list of children.
  193. func (n *Node) Children() []INode {
  194. return n.children
  195. }
  196. // Add adds the specified node to the list of children and sets its parent pointer.
  197. // If the specified node had a parent, the specified node is removed from the original parent's list of children.
  198. func (n *Node) Add(ichild INode) *Node {
  199. n.setParentOf(ichild)
  200. n.children = append(n.children, ichild)
  201. return n
  202. }
  203. // AddAt adds the specified node to the list of children at the specified index and sets its parent pointer.
  204. // If the specified node had a parent, the specified node is removed from the original parent's list of children.
  205. func (n *Node) AddAt(idx int, ichild INode) {
  206. // Validate position
  207. if idx < 0 || idx > len(n.children) {
  208. panic("Node.AddAt: invalid position")
  209. }
  210. n.setParentOf(ichild)
  211. // Insert child in the specified position
  212. n.children = append(n.children, nil)
  213. copy(n.children[idx+1:], n.children[idx:])
  214. n.children[idx] = ichild
  215. }
  216. // setParentOf is used by Add and AddAt.
  217. // It verifies that the node is not being added to itself and sets the parent pointer of the specified node.
  218. // If the specified node had a parent, the specified node is removed from the original parent's list of children.
  219. // It does not add the specified node to the list of children.
  220. func (n *Node) setParentOf(ichild INode) {
  221. child := ichild.GetNode()
  222. if n == child {
  223. panic("Node.{Add,AddAt}: object can't be added as a child of itself")
  224. }
  225. // If the specified node already has a parent,
  226. // remove it from the original parent's list of children
  227. if child.parent != nil {
  228. child.parent.GetNode().Remove(ichild)
  229. }
  230. child.parent = n
  231. }
  232. // ChildAt returns the child at the specified index.
  233. func (n *Node) ChildAt(idx int) INode {
  234. if idx < 0 || idx >= len(n.children) {
  235. return nil
  236. }
  237. return n.children[idx]
  238. }
  239. // ChildIndex returns the index of the specified child (-1 if not found).
  240. func (n *Node) ChildIndex(ichild INode) int {
  241. for idx := 0; idx < len(n.children); idx++ {
  242. if n.children[idx] == ichild {
  243. return idx
  244. }
  245. }
  246. return -1
  247. }
  248. // Remove removes the specified INode from the list of children.
  249. // Returns true if found or false otherwise.
  250. func (n *Node) Remove(ichild INode) bool {
  251. for pos, current := range n.children {
  252. if current == ichild {
  253. copy(n.children[pos:], n.children[pos+1:])
  254. n.children[len(n.children)-1] = nil
  255. n.children = n.children[:len(n.children)-1]
  256. ichild.GetNode().parent = nil
  257. return true
  258. }
  259. }
  260. return false
  261. }
  262. // RemoveAt removes the child at the specified index.
  263. func (n *Node) RemoveAt(idx int) INode {
  264. // Validate position
  265. if idx < 0 || idx >= len(n.children) {
  266. panic("Node.RemoveAt: invalid position")
  267. }
  268. child := n.children[idx]
  269. // Remove child from children list
  270. copy(n.children[idx:], n.children[idx+1:])
  271. n.children[len(n.children)-1] = nil
  272. n.children = n.children[:len(n.children)-1]
  273. return child
  274. }
  275. // RemoveAll removes all children.
  276. func (n *Node) RemoveAll(recurs bool) {
  277. for pos, ichild := range n.children {
  278. n.children[pos] = nil
  279. ichild.GetNode().parent = nil
  280. if recurs {
  281. ichild.GetNode().RemoveAll(recurs)
  282. }
  283. }
  284. n.children = n.children[0:0]
  285. }
  286. // DisposeChildren removes and disposes of all children.
  287. // If 'recurs' is true, call DisposeChildren on each child recursively.
  288. func (n *Node) DisposeChildren(recurs bool) {
  289. for pos, ichild := range n.children {
  290. n.children[pos] = nil
  291. ichild.GetNode().parent = nil
  292. if recurs {
  293. ichild.GetNode().DisposeChildren(true)
  294. }
  295. ichild.Dispose()
  296. }
  297. n.children = n.children[0:0]
  298. }
  299. // SetPosition sets the position.
  300. func (n *Node) SetPosition(x, y, z float32) {
  301. n.position.Set(x, y, z)
  302. n.matNeedsUpdate = true
  303. }
  304. // SetPositionVec sets the position based on the specified vector pointer.
  305. func (n *Node) SetPositionVec(vpos *math32.Vector3) {
  306. n.position = *vpos
  307. n.matNeedsUpdate = true
  308. }
  309. // SetPositionX sets the X coordinate of the position.
  310. func (n *Node) SetPositionX(x float32) {
  311. n.position.X = x
  312. n.matNeedsUpdate = true
  313. }
  314. // SetPositionY sets the Y coordinate of the position.
  315. func (n *Node) SetPositionY(y float32) {
  316. n.position.Y = y
  317. n.matNeedsUpdate = true
  318. }
  319. // SetPositionZ sets the Z coordinate of the position.
  320. func (n *Node) SetPositionZ(z float32) {
  321. n.position.Z = z
  322. n.matNeedsUpdate = true
  323. }
  324. // Position returns the position as a vector.
  325. func (n *Node) Position() math32.Vector3 {
  326. return n.position
  327. }
  328. // TranslateOnAxis translates the specified distance on the specified local axis.
  329. func (n *Node) TranslateOnAxis(axis *math32.Vector3, dist float32) {
  330. v := math32.NewVec3().Copy(axis)
  331. v.ApplyQuaternion(&n.quaternion)
  332. v.MultiplyScalar(dist)
  333. n.position.Add(v)
  334. n.matNeedsUpdate = true
  335. }
  336. // TranslateX translates the specified distance on the local X axis.
  337. func (n *Node) TranslateX(dist float32) {
  338. n.TranslateOnAxis(&math32.Vector3{1,0,0}, dist)
  339. }
  340. // TranslateY translates the specified distance on the local Y axis.
  341. func (n *Node) TranslateY(dist float32) {
  342. n.TranslateOnAxis(&math32.Vector3{0,1,0}, dist)
  343. }
  344. // TranslateZ translates the specified distance on the local Z axis.
  345. func (n *Node) TranslateZ(dist float32) {
  346. n.TranslateOnAxis(&math32.Vector3{0,0,1}, dist)
  347. }
  348. // SetRotation sets the global rotation in Euler angles (radians).
  349. func (n *Node) SetRotation(x, y, z float32) {
  350. n.rotation.Set(x, y, z)
  351. n.quaternion.SetFromEuler(&n.rotation)
  352. n.matNeedsUpdate = true
  353. }
  354. // SetRotationVec sets the global rotation in Euler angles (radians) based on the specified vector pointer.
  355. func (n *Node) SetRotationVec(vrot *math32.Vector3) {
  356. n.rotation = *vrot
  357. n.quaternion.SetFromEuler(&n.rotation)
  358. n.matNeedsUpdate = true
  359. }
  360. // SetRotationQuat sets the global rotation based on the specified quaternion pointer.
  361. func (n *Node) SetRotationQuat(quat *math32.Quaternion) {
  362. n.quaternion = *quat
  363. n.rotNeedsUpdate = true
  364. }
  365. // SetRotationX sets the global X rotation to the specified angle in radians.
  366. func (n *Node) SetRotationX(x float32) {
  367. if n.rotNeedsUpdate {
  368. n.rotation.SetFromQuaternion(&n.quaternion)
  369. n.rotNeedsUpdate = false
  370. }
  371. n.rotation.X = x
  372. n.quaternion.SetFromEuler(&n.rotation)
  373. n.matNeedsUpdate = true
  374. }
  375. // SetRotationY sets the global Y rotation to the specified angle in radians.
  376. func (n *Node) SetRotationY(y float32) {
  377. if n.rotNeedsUpdate {
  378. n.rotation.SetFromQuaternion(&n.quaternion)
  379. n.rotNeedsUpdate = false
  380. }
  381. n.rotation.Y = y
  382. n.quaternion.SetFromEuler(&n.rotation)
  383. n.matNeedsUpdate = true
  384. }
  385. // SetRotationZ sets the global Z rotation to the specified angle in radians.
  386. func (n *Node) SetRotationZ(z float32) {
  387. if n.rotNeedsUpdate {
  388. n.rotation.SetFromQuaternion(&n.quaternion)
  389. n.rotNeedsUpdate = false
  390. }
  391. n.rotation.Z = z
  392. n.quaternion.SetFromEuler(&n.rotation)
  393. n.matNeedsUpdate = true
  394. }
  395. // Rotation returns the current global rotation in Euler angles (radians).
  396. func (n *Node) Rotation() math32.Vector3 {
  397. if n.rotNeedsUpdate {
  398. n.rotation.SetFromQuaternion(&n.quaternion)
  399. n.rotNeedsUpdate = false
  400. }
  401. return n.rotation
  402. }
  403. // RotateOnAxis rotates around the specified local axis the specified angle in radians.
  404. func (n *Node) RotateOnAxis(axis *math32.Vector3, angle float32) {
  405. var rotQuat math32.Quaternion
  406. rotQuat.SetFromAxisAngle(axis, angle)
  407. n.QuaternionMult(&rotQuat)
  408. }
  409. // RotateX rotates around the local X axis the specified angle in radians.
  410. func (n *Node) RotateX(x float32) {
  411. n.RotateOnAxis(&math32.Vector3{1,0,0}, x)
  412. }
  413. // RotateY rotates around the local Y axis the specified angle in radians.
  414. func (n *Node) RotateY(y float32) {
  415. n.RotateOnAxis(&math32.Vector3{0,1,0}, y)
  416. }
  417. // RotateZ rotates around the local Z axis the specified angle in radians.
  418. func (n *Node) RotateZ(z float32) {
  419. n.RotateOnAxis(&math32.Vector3{0,0,1}, z)
  420. }
  421. // SetQuaternion sets the quaternion based on the specified quaternion unit multiples.
  422. func (n *Node) SetQuaternion(x, y, z, w float32) {
  423. n.quaternion.Set(x, y, z, w)
  424. n.rotNeedsUpdate = true
  425. }
  426. // SetQuaternionVec sets the quaternion based on the specified quaternion unit multiples vector.
  427. func (n *Node) SetQuaternionVec(q *math32.Vector4) {
  428. n.quaternion.Set(q.X, q.Y, q.Z, q.W)
  429. n.rotNeedsUpdate = true
  430. }
  431. // SetQuaternionQuat sets the quaternion based on the specified quaternion pointer.
  432. func (n *Node) SetQuaternionQuat(q *math32.Quaternion) {
  433. n.quaternion = *q
  434. n.rotNeedsUpdate = true
  435. }
  436. // QuaternionMult multiplies the current quaternion by the specified quaternion.
  437. func (n *Node) QuaternionMult(q *math32.Quaternion) {
  438. n.quaternion.Multiply(q)
  439. n.rotNeedsUpdate = true
  440. }
  441. // Quaternion returns the current quaternion.
  442. func (n *Node) Quaternion() math32.Quaternion {
  443. return n.quaternion
  444. }
  445. // SetScale sets the scale.
  446. func (n *Node) SetScale(x, y, z float32) {
  447. n.scale.Set(x, y, z)
  448. n.matNeedsUpdate = true
  449. }
  450. // SetScaleVec sets the scale based on the specified vector pointer.
  451. func (n *Node) SetScaleVec(scale *math32.Vector3) {
  452. n.scale = *scale
  453. n.matNeedsUpdate = true
  454. }
  455. // SetScaleX sets the X scale.
  456. func (n *Node) SetScaleX(sx float32) {
  457. n.scale.X = sx
  458. n.matNeedsUpdate = true
  459. }
  460. // SetScaleY sets the Y scale.
  461. func (n *Node) SetScaleY(sy float32) {
  462. n.scale.Y = sy
  463. n.matNeedsUpdate = true
  464. }
  465. // SetScaleZ sets the Z scale.
  466. func (n *Node) SetScaleZ(sz float32) {
  467. n.scale.Z = sz
  468. n.matNeedsUpdate = true
  469. }
  470. // Scale returns the current scale.
  471. func (n *Node) Scale() math32.Vector3 {
  472. return n.scale
  473. }
  474. // SetDirection sets the direction.
  475. func (n *Node) SetDirection(x, y, z float32) {
  476. n.direction.Set(x, y, z)
  477. n.matNeedsUpdate = true
  478. }
  479. // SetDirectionVec sets the direction based on a vector pointer.
  480. func (n *Node) SetDirectionVec(vdir *math32.Vector3) {
  481. n.direction = *vdir
  482. n.matNeedsUpdate = true
  483. }
  484. // Direction returns the direction.
  485. func (n *Node) Direction() math32.Vector3 {
  486. return n.direction
  487. }
  488. // SetMatrix sets the local transformation matrix.
  489. func (n *Node) SetMatrix(m *math32.Matrix4) {
  490. n.matrix = *m
  491. n.matrix.Decompose(&n.position, &n.quaternion, &n.scale)
  492. n.rotNeedsUpdate = true
  493. }
  494. // Matrix returns a copy of the local transformation matrix.
  495. func (n *Node) Matrix() math32.Matrix4 {
  496. return n.matrix
  497. }
  498. // WorldPosition updates the world matrix and sets
  499. // the specified vector to the current world position of this node.
  500. func (n *Node) WorldPosition(result *math32.Vector3) {
  501. n.UpdateMatrixWorld()
  502. result.SetFromMatrixPosition(&n.matrixWorld)
  503. }
  504. // WorldQuaternion updates the world matrix and sets
  505. // the specified quaternion to the current world quaternion of this node.
  506. func (n *Node) WorldQuaternion(result *math32.Quaternion) {
  507. var position math32.Vector3
  508. var scale math32.Vector3
  509. n.UpdateMatrixWorld()
  510. n.matrixWorld.Decompose(&position, result, &scale)
  511. }
  512. // WorldRotation updates the world matrix and sets
  513. // the specified vector to the current world rotation of this node in Euler angles.
  514. func (n *Node) WorldRotation(result *math32.Vector3) {
  515. var quaternion math32.Quaternion
  516. n.WorldQuaternion(&quaternion)
  517. result.SetFromQuaternion(&quaternion)
  518. }
  519. // WorldScale updates the world matrix and sets
  520. // the specified vector to the current world scale of this node.
  521. func (n *Node) WorldScale(result *math32.Vector3) {
  522. var position math32.Vector3
  523. var quaternion math32.Quaternion
  524. n.UpdateMatrixWorld()
  525. n.matrixWorld.Decompose(&position, &quaternion, result)
  526. }
  527. // WorldDirection updates the world matrix and sets
  528. // the specified vector to the current world direction of this node.
  529. func (n *Node) WorldDirection(result *math32.Vector3) {
  530. var quaternion math32.Quaternion
  531. n.WorldQuaternion(&quaternion)
  532. *result = n.direction
  533. result.ApplyQuaternion(&quaternion)
  534. }
  535. // MatrixWorld returns a copy of the matrix world of this node.
  536. func (n *Node) MatrixWorld() math32.Matrix4 {
  537. return n.matrixWorld
  538. }
  539. // UpdateMatrix updates (if necessary) the local transform matrix
  540. // of this node based on its position, quaternion, and scale.
  541. func (n *Node) UpdateMatrix() bool {
  542. if !n.matNeedsUpdate && !n.rotNeedsUpdate {
  543. return false
  544. }
  545. n.matrix.Compose(&n.position, &n.quaternion, &n.scale)
  546. n.matNeedsUpdate = false
  547. return true
  548. }
  549. // UpdateMatrixWorld updates this node world transform matrix and of all its children
  550. func (n *Node) UpdateMatrixWorld() {
  551. n.UpdateMatrix()
  552. if n.parent == nil {
  553. n.matrixWorld = n.matrix
  554. } else {
  555. parent := n.parent.GetNode()
  556. n.matrixWorld.MultiplyMatrices(&parent.matrixWorld, &n.matrix)
  557. }
  558. // Update this Node children matrices
  559. for _, ichild := range n.children {
  560. ichild.UpdateMatrixWorld()
  561. }
  562. }