narrowphase.go 22 KB

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