narrowphase.go 21 KB

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