narrowphase.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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 physics
  5. import (
  6. "github.com/g3n/engine/physics/object"
  7. "github.com/g3n/engine/physics/collision"
  8. "github.com/g3n/engine/physics/equation"
  9. "github.com/g3n/engine/math32"
  10. "github.com/g3n/engine/physics/material"
  11. )
  12. // Narrowphase
  13. type Narrowphase struct {
  14. simulation *Simulation
  15. currentContactMaterial *material.ContactMaterial
  16. enableFrictionReduction bool // If true friction is computed as average
  17. debugging bool
  18. }
  19. type Pair struct {
  20. bodyA *object.Body
  21. bodyB *object.Body
  22. }
  23. // NewNarrowphase creates and returns a pointer to a new Narrowphase.
  24. func NewNarrowphase(simulation *Simulation) *Narrowphase {
  25. n := new(Narrowphase)
  26. n.simulation = simulation
  27. //n.enableFrictionReduction = true
  28. // FOR DEBUGGING
  29. n.debugging = true
  30. return n
  31. }
  32. func (n *Narrowphase) GetContacts(pairs []collision.Pair) ([]*equation.Contact, []*equation.Friction) {
  33. allContactEqs := make([]*equation.Contact, 0)
  34. allFrictionEqs := make([]*equation.Friction, 0)
  35. for k := 0; k < len(pairs); k++ {
  36. // Get current collision bodies
  37. bodyA := pairs[k].BodyA
  38. bodyB := pairs[k].BodyB
  39. bodyTypeA := bodyA.BodyType()
  40. bodyTypeB := bodyB.BodyType()
  41. // For now these collisions are ignored
  42. // TODO future: just want to check for collision (in order to dispatch events) and not create equations
  43. justTest := (bodyTypeA == object.Kinematic) && (bodyTypeB == object.Static) ||
  44. (bodyTypeA == object.Static) && (bodyTypeB == object.Kinematic) ||
  45. (bodyTypeA == object.Kinematic) && (bodyTypeB == object.Kinematic)
  46. // Get contacts
  47. if !justTest {
  48. _, contactEqs, frictionEqs := n.Resolve(bodyA, bodyB)
  49. allContactEqs = append(allContactEqs, contactEqs...)
  50. allFrictionEqs = append(allFrictionEqs, frictionEqs...)
  51. }
  52. }
  53. return allContactEqs, allFrictionEqs
  54. }
  55. // Convex - Convex collision detection
  56. //func (n *Narrowphase) Resolve(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest) {
  57. func (n *Narrowphase) Resolve(bodyA, bodyB *object.Body) (bool, []*equation.Contact, []*equation.Friction) {
  58. contactEqs := make([]*equation.Contact, 0)
  59. frictionEqs := make([]*equation.Friction, 0)
  60. // Check if colliding and find penetration axis
  61. penetrating, penAxis := n.FindPenetrationAxis(bodyA, bodyB)
  62. if penetrating {
  63. // Colliding! Find contacts.
  64. ShowPenAxis(n.simulation.Scene(), &penAxis) //, -1000, 1000)
  65. log.Error("Colliding (%v|%v) penAxis: %v", bodyA.Name(), bodyB.Name(), penAxis)
  66. contacts := n.ClipAgainstHull(bodyA, bodyB, &penAxis, -100, 100)
  67. log.Error(" .... contacts: %v", contacts)
  68. posA := bodyA.Position()
  69. posB := bodyB.Position()
  70. for j := 0; j < len(contacts); j++ {
  71. contact := contacts[j]
  72. ShowContact(n.simulation.Scene(), &contact) // TODO DEBUGGING
  73. // Note - contact Normals point from B to A (contacts live in B)
  74. // Create contact equation and append it
  75. contactEq := equation.NewContact(bodyA, bodyB, 0, 1e6)
  76. contactEq.SetSpookParams(1e6, 3, n.simulation.dt)
  77. contactEq.SetEnabled(bodyA.CollisionResponse() && bodyB.CollisionResponse())
  78. contactEq.SetNormal(penAxis.Clone())
  79. log.Error("contact.Depth: %v", contact.Depth)
  80. //contactEq.SetRA(contact.Point.Clone().Sub(&posA).MultiplyScalar(1-contact.Depth))//.MultiplyScalar(2))
  81. contactEq.SetRA(contact.Normal.Clone().MultiplyScalar(contact.Depth - 0).Add(&contact.Point).Sub(&posA))
  82. //contactEq.SetRA(contact.Normal.MultiplyScalar(-contact.Depth*10).Add(&contact.Point).Sub(&posA))
  83. contactEq.SetRB(contact.Point.Clone().Sub(&posB))
  84. contactEqs = append(contactEqs, contactEq)
  85. // If enableFrictionReduction is true then skip creating friction equations for individual contacts
  86. // We will create average friction equations later based on all contacts
  87. // TODO
  88. if !n.enableFrictionReduction {
  89. //fEq1, fEq2 := n.createFrictionEquationsFromContact(contactEq)
  90. //frictionEqs = append(frictionEqs, fEq1, fEq2)
  91. }
  92. }
  93. // If enableFrictionReduction is true then we skipped creating friction equations for individual contacts
  94. // We now want to create average friction equations based on all contact points.
  95. // If we only have one contact however, then friction is small and we don't need to create the friction equations at all.
  96. // TODO
  97. if n.enableFrictionReduction && len(contactEqs) > 1 {
  98. //fEq1, fEq2 := n.createFrictionFromAverage(contactEqs)
  99. //frictionEqs = append(frictionEqs, fEq1, fEq2)
  100. }
  101. }
  102. return false, contactEqs, frictionEqs
  103. }
  104. func (n *Narrowphase) createFrictionEquationsFromContact(contactEquation *equation.Contact) (*equation.Friction, *equation.Friction) { //}, outArray) bool {
  105. bodyA := n.simulation.bodies[contactEquation.BodyA().Index()]
  106. bodyB := n.simulation.bodies[contactEquation.BodyB().Index()]
  107. // TODO
  108. // friction = n.currentContactMaterial.friction
  109. // if materials are defined then override: friction = matA.friction * matB.friction
  110. //var mug = friction * world.gravity.length()
  111. //var reducedMass = bodyA.InvMass() + bodyB.InvMass()
  112. //if reducedMass > 0 {
  113. // reducedMass = 1/reducedMass
  114. //}
  115. slipForce := float32(0.5) //mug*reducedMass
  116. fricEq1 := equation.NewFriction(bodyA, bodyB, slipForce)
  117. fricEq2 := equation.NewFriction(bodyA, bodyB, slipForce)
  118. fricEq1.SetSpookParams(1e7, 3, n.simulation.dt)
  119. fricEq2.SetSpookParams(1e7, 3, n.simulation.dt)
  120. // Copy over the relative vectors
  121. cRA := contactEquation.RA()
  122. cRB := contactEquation.RB()
  123. fricEq1.SetRA(&cRA)
  124. fricEq1.SetRB(&cRB)
  125. fricEq2.SetRA(&cRA)
  126. fricEq2.SetRB(&cRB)
  127. // Construct tangents
  128. cNormal := contactEquation.Normal()
  129. t1, t2 := cNormal.RandomTangents()
  130. fricEq1.SetTangent(t1)
  131. fricEq2.SetTangent(t2)
  132. // Copy enabled state
  133. cEnabled := contactEquation.Enabled()
  134. fricEq1.SetEnabled(cEnabled)
  135. fricEq2.SetEnabled(cEnabled)
  136. return fricEq1, fricEq2
  137. }
  138. func (n *Narrowphase) createFrictionFromAverage(contactEqs []*equation.Contact) (*equation.Friction, *equation.Friction) {
  139. // The last contactEquation
  140. lastContactEq := contactEqs[len(contactEqs)-1]
  141. // Create a friction equation based on the last contact (we will modify it to take into account all contacts)
  142. fEq1, fEq2 := n.createFrictionEquationsFromContact(lastContactEq)
  143. if (fEq1 == nil && fEq2 == nil) || len(contactEqs) == 1 {
  144. return fEq1, fEq2
  145. }
  146. averageNormal := math32.NewVec3()
  147. averageContactPointA := math32.NewVec3()
  148. averageContactPointB := math32.NewVec3()
  149. bodyA := lastContactEq.BodyA()
  150. //bodyB := lastContactEq.BodyB()
  151. normal := lastContactEq.Normal()
  152. rA := lastContactEq.RA()
  153. rB := lastContactEq.RB()
  154. for _, cEq := range contactEqs {
  155. if cEq.BodyA() != bodyA {
  156. averageNormal.Add(&normal)
  157. averageContactPointA.Add(&rA)
  158. averageContactPointB.Add(&rB)
  159. } else {
  160. averageNormal.Sub(&normal)
  161. averageContactPointA.Add(&rB)
  162. averageContactPointB.Add(&rA)
  163. }
  164. }
  165. invNumContacts := float32(1) / float32(len(contactEqs))
  166. averageContactPointA.MultiplyScalar(invNumContacts)
  167. averageContactPointB.MultiplyScalar(invNumContacts)
  168. // Should be the same for both friction equations
  169. fEq1.SetRA(averageContactPointA)
  170. fEq1.SetRB(averageContactPointB)
  171. fEq2.SetRA(averageContactPointA)
  172. fEq2.SetRB(averageContactPointB)
  173. // Set tangents
  174. averageNormal.Normalize()
  175. t1, t2 := averageNormal.RandomTangents()
  176. fEq1.SetTangent(t1)
  177. fEq2.SetTangent(t2)
  178. return fEq1, fEq2
  179. }
  180. //
  181. // Penetration Axis =============================================
  182. //
  183. // FindPenetrationAxis finds the penetration axis between two convex bodies.
  184. // The normal points from bodyA to bodyB.
  185. // Returns false if there is no penetration. If there is a penetration - returns true and the penetration axis.
  186. func (n *Narrowphase) FindPenetrationAxis(bodyA, bodyB *object.Body) (bool, math32.Vector3) {
  187. // Keep track of the smaller depth found so far
  188. // Note that the penetration axis is the one that causes
  189. // the smallest penetration depth when the two hulls are squished onto that axis!
  190. // (may seem a bit counter-intuitive)
  191. depthMin := math32.Inf(1)
  192. var penetrationAxis math32.Vector3
  193. var depth float32
  194. // Assume the geometries are penetrating.
  195. // As soon as (and if) we figure out that they are not, then return false.
  196. penetrating := true
  197. worldFaceNormalsA := bodyA.WorldFaceNormals()
  198. worldFaceNormalsB := bodyB.WorldFaceNormals()
  199. // Check world normals of body A
  200. for _, worldFaceNormal := range worldFaceNormalsA {
  201. // Check whether the face is colliding with geomB
  202. penetrating, depth = n.TestPenetrationAxis(&worldFaceNormal, bodyA, bodyB)
  203. if !penetrating {
  204. return false, penetrationAxis // penetrationAxis doesn't matter since not penetrating
  205. }
  206. if depth < depthMin {
  207. depthMin = depth
  208. penetrationAxis.Copy(&worldFaceNormal)
  209. }
  210. }
  211. // Check world normals of body B
  212. for _, worldFaceNormal := range worldFaceNormalsB {
  213. // Check whether the face is colliding with geomB
  214. penetrating, depth = n.TestPenetrationAxis(&worldFaceNormal, bodyA, bodyB)
  215. if !penetrating {
  216. return false, penetrationAxis // penetrationAxis doesn't matter since not penetrating
  217. }
  218. if depth < depthMin {
  219. depthMin = depth
  220. penetrationAxis.Copy(&worldFaceNormal)
  221. }
  222. }
  223. worldUniqueEdgesA := bodyA.WorldUniqueEdges()
  224. worldUniqueEdgesB := bodyB.WorldUniqueEdges()
  225. // Check all combinations of unique world edges
  226. for _, worldUniqueEdgeA := range worldUniqueEdgesA {
  227. for _, worldUniqueEdgeB := range worldUniqueEdgesB {
  228. // Cross edges
  229. edgeCross := math32.NewVec3().CrossVectors(&worldUniqueEdgeA, &worldUniqueEdgeB)
  230. // If the edges are not aligned
  231. tol := float32(1e-6)
  232. if edgeCross.Length() > tol { // Cross product is not close to zero
  233. edgeCross.Normalize()
  234. penetrating, depth = n.TestPenetrationAxis(edgeCross, bodyA, bodyB)
  235. if !penetrating {
  236. return false, penetrationAxis
  237. }
  238. if depth < depthMin {
  239. depthMin = depth
  240. penetrationAxis.Copy(edgeCross)
  241. }
  242. }
  243. }
  244. }
  245. posA := bodyA.Position()
  246. posB := bodyB.Position()
  247. deltaC := math32.NewVec3().SubVectors(&posA, &posB)
  248. if deltaC.Dot(&penetrationAxis) > 0.0 {
  249. penetrationAxis.Negate()
  250. }
  251. return true, penetrationAxis
  252. }
  253. // Both hulls are projected onto the axis and the overlap size (penetration depth) is returned if there is one.
  254. // return {number} The overlap depth, or FALSE if no penetration.
  255. func (n *Narrowphase) TestPenetrationAxis(worldAxis *math32.Vector3, bodyA, bodyB *object.Body) (bool, float32) {
  256. maxA, minA := n.ProjectOntoWorldAxis(bodyA, worldAxis)
  257. maxB, minB := n.ProjectOntoWorldAxis(bodyB, worldAxis)
  258. if maxA < minB || maxB < minA {
  259. return false, 0 // Separated
  260. }
  261. d0 := maxA - minB
  262. d1 := maxB - minA
  263. if d0 < d1 {
  264. return true, d0
  265. } else {
  266. return true, d1
  267. }
  268. }
  269. // ProjectOntoWorldAxis projects the geometry onto the specified world axis.
  270. func (n *Narrowphase) ProjectOntoWorldAxis(body *object.Body, axis *math32.Vector3) (float32, float32) {
  271. // Transform the axis to local
  272. quatConj := body.Quaternion().Conjugate()
  273. localAxis := axis.Clone().ApplyQuaternion(quatConj)
  274. max, min := body.GetGeometry().ProjectOntoAxis(localAxis)
  275. // Offset to obtain values relative to world origin
  276. bodyPos := body.Position()
  277. localOrigin := math32.NewVec3().Sub(&bodyPos).ApplyQuaternion(quatConj)
  278. add := localOrigin.Dot(localAxis)
  279. min -= add
  280. max -= add
  281. return max, min
  282. }
  283. //
  284. // Contact Finding =============================================
  285. //
  286. // Contact describes a contact point.
  287. type Contact struct {
  288. Point math32.Vector3
  289. Normal math32.Vector3
  290. Depth float32
  291. }
  292. //{array} result The an array of contact point objects, see clipFaceAgainstHull
  293. func (n *Narrowphase) ClipAgainstHull(bodyA, bodyB *object.Body, penAxis *math32.Vector3, minDist, maxDist float32) []Contact {
  294. var contacts []Contact
  295. // Invert penetration axis so it points from b to a
  296. invPenAxis := penAxis.Clone().Negate()
  297. // Find face of B that is closest (i.e. that is most aligned with the penetration axis)
  298. closestFaceBidx := -1
  299. dmax := math32.Inf(-1)
  300. worldFaceNormalsB := bodyB.WorldFaceNormals()
  301. for i, worldFaceNormal := range worldFaceNormalsB {
  302. // Note - normals must be pointing out of the body so that they align with the penetration axis in the line below
  303. d := worldFaceNormal.Dot(invPenAxis)
  304. if d > dmax {
  305. dmax = d
  306. closestFaceBidx = i
  307. }
  308. }
  309. // If found a closest face (sometimes we don't find one)
  310. if closestFaceBidx >= 0 {
  311. // Copy and transform face vertices to world coordinates
  312. faces := bodyB.Faces()
  313. worldClosestFaceB := n.WorldFace(faces[closestFaceBidx], bodyB)
  314. contacts = n.ClipFaceAgainstHull(penAxis, bodyA, worldClosestFaceB, minDist, maxDist)
  315. }
  316. return contacts
  317. }
  318. func (n *Narrowphase) WorldFace(face [3]math32.Vector3, body *object.Body) [3]math32.Vector3 {
  319. var result [3]math32.Vector3
  320. result[0] = face[0]
  321. result[1] = face[1]
  322. result[2] = face[2]
  323. pos := body.Position()
  324. result[0].ApplyQuaternion(body.Quaternion()).Add(&pos)
  325. result[1].ApplyQuaternion(body.Quaternion()).Add(&pos)
  326. result[2].ApplyQuaternion(body.Quaternion()).Add(&pos)
  327. return result
  328. }
  329. func (n *Narrowphase) WorldFaceNormal(normal *math32.Vector3, body *object.Body) math32.Vector3 {
  330. pos := body.Position()
  331. result := normal.Clone().ApplyQuaternion(body.Quaternion()).Add(&pos)
  332. return *result
  333. }
  334. // TODO move to geometry ?
  335. // Clip a face against a hull.
  336. //@param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
  337. //@param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  338. func (n *Narrowphase) ClipFaceAgainstHull(penAxis *math32.Vector3, bodyA *object.Body, worldClosestFaceB [3]math32.Vector3, minDist, maxDist float32) []Contact {
  339. contacts := make([]Contact, 0)
  340. // Find the face of A with normal closest to the separating axis (i.e. that is most aligned with the penetration axis)
  341. closestFaceAidx := -1
  342. dmax := math32.Inf(-1)
  343. worldFaceNormalsA := bodyA.WorldFaceNormals()
  344. for i, worldFaceNormal := range worldFaceNormalsA {
  345. // Note - normals must be pointing out of the body so that they align with the penetration axis in the line below
  346. d := worldFaceNormal.Dot(penAxis)
  347. if d > dmax {
  348. dmax = d
  349. closestFaceAidx = i
  350. }
  351. }
  352. if closestFaceAidx < 0 {
  353. // Did not find any closest face...
  354. return contacts
  355. }
  356. //console.log("closest A: ",worldClosestFaceA);
  357. // Get the face and construct connected faces
  358. facesA := bodyA.Faces()
  359. //worldClosestFaceA := n.WorldFace(facesA[closestFaceAidx], bodyA)
  360. closestFaceA := facesA[closestFaceAidx]
  361. connectedFaces := make([]int, 0) // indexes of the connected faces
  362. for faceIdx := 0; faceIdx < len(facesA); faceIdx++ {
  363. // Skip worldClosestFaceA
  364. if faceIdx == closestFaceAidx {
  365. continue
  366. }
  367. // Test that face has not already been added
  368. for _, cfidx := range connectedFaces {
  369. if cfidx == faceIdx {
  370. continue
  371. }
  372. }
  373. face := facesA[faceIdx]
  374. // Loop through face vertices and see if any of them are also present in the closest face
  375. // If a vertex is shared and this connected face hasn't been recorded yet - record and break inner loop
  376. for pConnFaceVidx := 0; pConnFaceVidx < len(face); pConnFaceVidx++ {
  377. var goToNextFace bool
  378. // Test if face shares a vertex with closetFaceA - add it to connectedFaces if so and break out of both loops
  379. for closFaceVidx := 0; closFaceVidx < len(closestFaceA); closFaceVidx++ {
  380. if closestFaceA[closFaceVidx].Equals(&face[pConnFaceVidx]) {
  381. connectedFaces = append(connectedFaces, faceIdx)
  382. goToNextFace = true
  383. break
  384. }
  385. }
  386. if goToNextFace {
  387. break
  388. }
  389. }
  390. }
  391. // DEBUGGING
  392. //log.Error("CONN-FACES: %v", len(connectedFaces))
  393. for _, fidx := range connectedFaces {
  394. wFace := n.WorldFace(facesA[fidx], bodyA)
  395. ShowWorldFace(n.simulation.Scene(), wFace[:], &math32.Color{0.8,0.8,0.8})
  396. }
  397. worldClosestFaceA := n.WorldFace(closestFaceA, bodyA)
  398. //log.Error("worldClosestFaceA: %v", worldClosestFaceA)
  399. //log.Error("worldClosestFaceB: %v", worldClosestFaceB)
  400. ShowWorldFace(n.simulation.Scene(), worldClosestFaceA[:], &math32.Color{2,0,0})
  401. ShowWorldFace(n.simulation.Scene(), worldClosestFaceB[:], &math32.Color{0,2,0})
  402. clippedFace := make([]math32.Vector3, len(worldClosestFaceB))
  403. for i, v := range worldClosestFaceB {
  404. clippedFace[i] = v
  405. }
  406. // TODO port simplified loop to cannon.js once done and verified
  407. // https://github.com/schteppe/cannon.js/issues/378
  408. // https://github.com/TheRohans/cannon.js/commit/62a1ce47a851b7045e68f7b120b9e4ecb0d91aab#r29106924
  409. posA := bodyA.Position()
  410. quatA := bodyA.Quaternion()
  411. // Iterate over connected faces and clip the planes associated with their normals
  412. for _, cfidx := range connectedFaces {
  413. connFace := facesA[cfidx]
  414. connFaceNormal := worldFaceNormalsA[cfidx]
  415. // Choose a vertex in the connected face and use it to find the plane constant
  416. worldFirstVertex := connFace[0].Clone().ApplyQuaternion(quatA).Add(&posA)
  417. planeDelta := - worldFirstVertex.Dot(&connFaceNormal)
  418. clippedFace = n.ClipFaceAgainstPlane(clippedFace, connFaceNormal.Clone(), planeDelta)
  419. }
  420. // Plot clipped face
  421. log.Error("worldClosestFaceBClipped: %v", clippedFace)
  422. ShowWorldFace(n.simulation.Scene(), clippedFace, &math32.Color{0,0,2})
  423. closestFaceAnormal := worldFaceNormalsA[closestFaceAidx]
  424. worldFirstVertex := worldClosestFaceA[0].Clone()//.ApplyQuaternion(quatA).Add(&posA)
  425. planeDelta := -worldFirstVertex.Dot(&closestFaceAnormal)
  426. for _, vertex := range clippedFace {
  427. depth := closestFaceAnormal.Dot(&vertex) + planeDelta
  428. // Cap distance
  429. if depth <= minDist {
  430. depth = minDist
  431. }
  432. if depth <= maxDist {
  433. if depth <= 0 {
  434. contacts = append(contacts, Contact{
  435. Point: vertex,
  436. Normal: closestFaceAnormal,
  437. Depth: depth,
  438. })
  439. }
  440. }
  441. }
  442. return contacts
  443. }
  444. // Clip a face in a hull against the back of a plane.
  445. // @param {Number} planeConstant The constant in the mathematical plane equation
  446. func (n *Narrowphase) ClipFaceAgainstPlane(face []math32.Vector3, planeNormal *math32.Vector3, planeConstant float32) []math32.Vector3 {
  447. // inVertices are the verts making up the face of hullB
  448. clippedFace := make([]math32.Vector3, 0)
  449. if len(face) < 2 {
  450. return face
  451. }
  452. firstVertex := face[len(face)-1]
  453. dotFirst := planeNormal.Dot(&firstVertex) + planeConstant
  454. for vi := 0; vi < len(face); vi++ {
  455. lastVertex := face[vi]
  456. dotLast := planeNormal.Dot(&lastVertex) + planeConstant
  457. if dotFirst < 0 { // Inside hull
  458. if dotLast < 0 { // Start < 0, end < 0, so output lastVertex
  459. clippedFace = append(clippedFace, lastVertex)
  460. } else { // Start < 0, end >= 0, so output intersection
  461. newv := firstVertex.Clone().Lerp(&lastVertex, dotFirst / (dotFirst - dotLast))
  462. clippedFace = append(clippedFace, *newv)
  463. }
  464. } else { // Outside hull
  465. if dotLast < 0 { // Start >= 0, end < 0 so output intersection and end
  466. newv := firstVertex.Clone().Lerp(&lastVertex, dotFirst / (dotFirst - dotLast))
  467. clippedFace = append(clippedFace, *newv)
  468. clippedFace = append(clippedFace, lastVertex)
  469. }
  470. }
  471. firstVertex = lastVertex
  472. dotFirst = dotLast
  473. }
  474. return clippedFace
  475. }
  476. //// TODO ?
  477. //func (n *Narrowphase) GetAveragePointLocal(target) {
  478. //
  479. // target = target || new Vec3()
  480. // n := this.vertices.length
  481. // verts := this.vertices
  482. // for i := 0; i < n; i++ {
  483. // target.vadd(verts[i],target)
  484. // }
  485. // target.mult(1/n,target)
  486. // return target
  487. //}
  488. //
  489. //
  490. //// Checks whether p is inside the polyhedra. Must be in local coords.
  491. //// The point lies outside of the convex hull of the other points if and only if
  492. //// the direction of all the vectors from it to those other points are on less than one half of a sphere around it.
  493. //// p is A point given in local coordinates
  494. //func (n *Narrowphase) PointIsInside(p) {
  495. //
  496. // verts := this.vertices
  497. // faces := this.faces
  498. // normals := this.faceNormals
  499. // positiveResult := null
  500. // N := this.faces.length
  501. // pointInside := ConvexPolyhedron_pointIsInside
  502. // this.getAveragePointLocal(pointInside)
  503. // for i := 0; i < N; i++ {
  504. // numVertices := this.faces[i].length
  505. // n := normals[i]
  506. // v := verts[faces[i][0]] // We only need one point in the face
  507. //
  508. // // This dot product determines which side of the edge the point is
  509. // vToP := ConvexPolyhedron_vToP
  510. // p.vsub(v,vToP)
  511. // r1 := n.dot(vToP)
  512. //
  513. // vToPointInside := ConvexPolyhedron_vToPointInside
  514. // pointInside.vsub(v,vToPointInside)
  515. // r2 := n.dot(vToPointInside)
  516. //
  517. // if (r1<0 && r2>0) || (r1>0 && r2<0) {
  518. // return false // Encountered some other sign. Exit.
  519. // }
  520. // }
  521. //
  522. // // If we got here, all dot products were of the same sign.
  523. // return positiveResult ? 1 : -1
  524. //}
  525. // TODO
  526. //func (n *Narrowphase) planevConvex(
  527. // planeShape,
  528. // convexShape,
  529. // planePosition,
  530. // convexPosition,
  531. // planeQuat,
  532. // convexQuat,
  533. // planeBody,
  534. // convexBody,
  535. // si,
  536. // sj,
  537. // justTest) {
  538. //
  539. // // Simply return the points behind the plane.
  540. // worldVertex := planeConvex_v
  541. // worldNormal := planeConvex_normal
  542. // worldNormal.set(0,0,1)
  543. // planeQuat.vmult(worldNormal,worldNormal) // Turn normal according to plane orientation
  544. //
  545. // var numContacts = 0
  546. // var relpos = planeConvex_relpos
  547. // for i := 0; i < len(convexShape.vertices); i++ {
  548. //
  549. // // Get world convex vertex
  550. // worldVertex.copy(convexShape.vertices[i])
  551. // convexQuat.vmult(worldVertex, worldVertex)
  552. // convexPosition.vadd(worldVertex, worldVertex)
  553. // worldVertex.vsub(planePosition, relpos)
  554. //
  555. // var dot = worldNormal.dot(relpos)
  556. // if dot <= 0.0 {
  557. // if justTest {
  558. // return true
  559. // }
  560. //
  561. // var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj)
  562. //
  563. // // Get vertex position projected on plane
  564. // var projected = planeConvex_projected
  565. // worldNormal.mult(worldNormal.dot(relpos),projected)
  566. // worldVertex.vsub(projected, projected)
  567. // projected.vsub(planePosition, r.ri) // From plane to vertex projected on plane
  568. //
  569. // r.ni.copy(worldNormal) // Contact normal is the plane normal out from plane
  570. //
  571. // // rj is now just the vector from the convex center to the vertex
  572. // worldVertex.vsub(convexPosition, r.rj)
  573. //
  574. // // Make it relative to the body
  575. // r.ri.vadd(planePosition, r.ri)
  576. // r.ri.vsub(planeBody.position, r.ri)
  577. // r.rj.vadd(convexPosition, r.rj)
  578. // r.rj.vsub(convexBody.position, r.rj)
  579. //
  580. // this.result.push(r)
  581. // numContacts++
  582. // if !this.enableFrictionReduction {
  583. // this.createFrictionEquationsFromContact(r, this.frictionResult)
  584. // }
  585. // }
  586. // }
  587. //
  588. // if this.enableFrictionReduction && numContacts {
  589. // this.createFrictionFromAverage(numContacts)
  590. // }
  591. //}