ConvexObjectBreaker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. ( function () {
  2. /**
  3. * @fileoverview This class can be used to subdivide a convex Geometry object into pieces.
  4. *
  5. * Usage:
  6. *
  7. * Use the function prepareBreakableObject to prepare a THREE.Mesh object to be broken.
  8. *
  9. * Then, call the various functions to subdivide the object (subdivideByImpact, cutByPlane)
  10. *
  11. * Sub-objects that are product of subdivision don't need prepareBreakableObject to be called on them.
  12. *
  13. * Requisites for the object:
  14. *
  15. * - THREE.Mesh object must have a BufferGeometry (not Geometry) and a Material
  16. *
  17. * - Vertex normals must be planar (not smoothed)
  18. *
  19. * - The geometry must be convex (this is not checked in the library). You can create convex
  20. * geometries with THREE.ConvexGeometry. The BoxGeometry, SphereGeometry and other convex primitives
  21. * can also be used.
  22. *
  23. * Note: This lib adds member variables to object's userData member (see prepareBreakableObject function)
  24. * Use with caution and read the code when using with other libs.
  25. *
  26. * @param {double} minSizeForBreak Min size a debris can have to break.
  27. * @param {double} smallDelta Max distance to consider that a point belongs to a plane.
  28. *
  29. */
  30. const _v1 = new THREE.Vector3();
  31. class ConvexObjectBreaker {
  32. constructor( minSizeForBreak = 1.4, smallDelta = 0.0001 ) {
  33. this.minSizeForBreak = minSizeForBreak;
  34. this.smallDelta = smallDelta;
  35. this.tempLine1 = new THREE.Line3();
  36. this.tempPlane1 = new THREE.Plane();
  37. this.tempPlane2 = new THREE.Plane();
  38. this.tempPlane_Cut = new THREE.Plane();
  39. this.tempCM1 = new THREE.Vector3();
  40. this.tempCM2 = new THREE.Vector3();
  41. this.tempVector3 = new THREE.Vector3();
  42. this.tempVector3_2 = new THREE.Vector3();
  43. this.tempVector3_3 = new THREE.Vector3();
  44. this.tempVector3_P0 = new THREE.Vector3();
  45. this.tempVector3_P1 = new THREE.Vector3();
  46. this.tempVector3_P2 = new THREE.Vector3();
  47. this.tempVector3_N0 = new THREE.Vector3();
  48. this.tempVector3_N1 = new THREE.Vector3();
  49. this.tempVector3_AB = new THREE.Vector3();
  50. this.tempVector3_CB = new THREE.Vector3();
  51. this.tempResultObjects = {
  52. object1: null,
  53. object2: null
  54. };
  55. this.segments = [];
  56. const n = 30 * 30;
  57. for ( let i = 0; i < n; i ++ ) this.segments[ i ] = false;
  58. }
  59. prepareBreakableObject( object, mass, velocity, angularVelocity, breakable ) {
  60. // object is a Object3d (normally a THREE.Mesh), must have a BufferGeometry, and it must be convex.
  61. // Its material property is propagated to its children (sub-pieces)
  62. // mass must be > 0
  63. if ( ! object.geometry.isBufferGeometry ) {
  64. console.error( 'THREE.ConvexObjectBreaker.prepareBreakableObject(): Parameter object must have a BufferGeometry.' );
  65. }
  66. const userData = object.userData;
  67. userData.mass = mass;
  68. userData.velocity = velocity.clone();
  69. userData.angularVelocity = angularVelocity.clone();
  70. userData.breakable = breakable;
  71. }
  72. /*
  73. * @param {int} maxRadialIterations Iterations for radial cuts.
  74. * @param {int} maxRandomIterations Max random iterations for not-radial cuts
  75. *
  76. * Returns the array of pieces
  77. */
  78. subdivideByImpact( object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations ) {
  79. const debris = [];
  80. const tempPlane1 = this.tempPlane1;
  81. const tempPlane2 = this.tempPlane2;
  82. this.tempVector3.addVectors( pointOfImpact, normal );
  83. tempPlane1.setFromCoplanarPoints( pointOfImpact, object.position, this.tempVector3 );
  84. const maxTotalIterations = maxRandomIterations + maxRadialIterations;
  85. const scope = this;
  86. function subdivideRadial( subObject, startAngle, endAngle, numIterations ) {
  87. if ( Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations ) {
  88. debris.push( subObject );
  89. return;
  90. }
  91. let angle = Math.PI;
  92. if ( numIterations === 0 ) {
  93. tempPlane2.normal.copy( tempPlane1.normal );
  94. tempPlane2.constant = tempPlane1.constant;
  95. } else {
  96. if ( numIterations <= maxRadialIterations ) {
  97. angle = ( endAngle - startAngle ) * ( 0.2 + 0.6 * Math.random() ) + startAngle; // Rotate tempPlane2 at impact point around normal axis and the angle
  98. scope.tempVector3_2.copy( object.position ).sub( pointOfImpact ).applyAxisAngle( normal, angle ).add( pointOfImpact );
  99. tempPlane2.setFromCoplanarPoints( pointOfImpact, scope.tempVector3, scope.tempVector3_2 );
  100. } else {
  101. angle = ( 0.5 * ( numIterations & 1 ) + 0.2 * ( 2 - Math.random() ) ) * Math.PI; // Rotate tempPlane2 at object position around normal axis and the angle
  102. scope.tempVector3_2.copy( pointOfImpact ).sub( subObject.position ).applyAxisAngle( normal, angle ).add( subObject.position );
  103. scope.tempVector3_3.copy( normal ).add( subObject.position );
  104. tempPlane2.setFromCoplanarPoints( subObject.position, scope.tempVector3_3, scope.tempVector3_2 );
  105. }
  106. } // Perform the cut
  107. scope.cutByPlane( subObject, tempPlane2, scope.tempResultObjects );
  108. const obj1 = scope.tempResultObjects.object1;
  109. const obj2 = scope.tempResultObjects.object2;
  110. if ( obj1 ) {
  111. subdivideRadial( obj1, startAngle, angle, numIterations + 1 );
  112. }
  113. if ( obj2 ) {
  114. subdivideRadial( obj2, angle, endAngle, numIterations + 1 );
  115. }
  116. }
  117. subdivideRadial( object, 0, 2 * Math.PI, 0 );
  118. return debris;
  119. }
  120. cutByPlane( object, plane, output ) {
  121. // Returns breakable objects in output.object1 and output.object2 members, the resulting 2 pieces of the cut.
  122. // object2 can be null if the plane doesn't cut the object.
  123. // object1 can be null only in case of internal error
  124. // Returned value is number of pieces, 0 for error.
  125. const geometry = object.geometry;
  126. const coords = geometry.attributes.position.array;
  127. const normals = geometry.attributes.normal.array;
  128. const numPoints = coords.length / 3;
  129. let numFaces = numPoints / 3;
  130. let indices = geometry.getIndex();
  131. if ( indices ) {
  132. indices = indices.array;
  133. numFaces = indices.length / 3;
  134. }
  135. function getVertexIndex( faceIdx, vert ) {
  136. // vert = 0, 1 or 2.
  137. const idx = faceIdx * 3 + vert;
  138. return indices ? indices[ idx ] : idx;
  139. }
  140. const points1 = [];
  141. const points2 = [];
  142. const delta = this.smallDelta; // Reset segments mark
  143. const numPointPairs = numPoints * numPoints;
  144. for ( let i = 0; i < numPointPairs; i ++ ) this.segments[ i ] = false;
  145. const p0 = this.tempVector3_P0;
  146. const p1 = this.tempVector3_P1;
  147. const n0 = this.tempVector3_N0;
  148. const n1 = this.tempVector3_N1; // Iterate through the faces to mark edges shared by coplanar faces
  149. for ( let i = 0; i < numFaces - 1; i ++ ) {
  150. const a1 = getVertexIndex( i, 0 );
  151. const b1 = getVertexIndex( i, 1 );
  152. const c1 = getVertexIndex( i, 2 ); // Assuming all 3 vertices have the same normal
  153. n0.set( normals[ a1 ], normals[ a1 ] + 1, normals[ a1 ] + 2 );
  154. for ( let j = i + 1; j < numFaces; j ++ ) {
  155. const a2 = getVertexIndex( j, 0 );
  156. const b2 = getVertexIndex( j, 1 );
  157. const c2 = getVertexIndex( j, 2 ); // Assuming all 3 vertices have the same normal
  158. n1.set( normals[ a2 ], normals[ a2 ] + 1, normals[ a2 ] + 2 );
  159. const coplanar = 1 - n0.dot( n1 ) < delta;
  160. if ( coplanar ) {
  161. if ( a1 === a2 || a1 === b2 || a1 === c2 ) {
  162. if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  163. this.segments[ a1 * numPoints + b1 ] = true;
  164. this.segments[ b1 * numPoints + a1 ] = true;
  165. } else {
  166. this.segments[ c1 * numPoints + a1 ] = true;
  167. this.segments[ a1 * numPoints + c1 ] = true;
  168. }
  169. } else if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  170. this.segments[ c1 * numPoints + b1 ] = true;
  171. this.segments[ b1 * numPoints + c1 ] = true;
  172. }
  173. }
  174. }
  175. } // Transform the plane to object local space
  176. const localPlane = this.tempPlane_Cut;
  177. object.updateMatrix();
  178. ConvexObjectBreaker.transformPlaneToLocalSpace( plane, object.matrix, localPlane ); // Iterate through the faces adding points to both pieces
  179. for ( let i = 0; i < numFaces; i ++ ) {
  180. const va = getVertexIndex( i, 0 );
  181. const vb = getVertexIndex( i, 1 );
  182. const vc = getVertexIndex( i, 2 );
  183. for ( let segment = 0; segment < 3; segment ++ ) {
  184. const i0 = segment === 0 ? va : segment === 1 ? vb : vc;
  185. const i1 = segment === 0 ? vb : segment === 1 ? vc : va;
  186. const segmentState = this.segments[ i0 * numPoints + i1 ];
  187. if ( segmentState ) continue; // The segment already has been processed in another face
  188. // Mark segment as processed (also inverted segment)
  189. this.segments[ i0 * numPoints + i1 ] = true;
  190. this.segments[ i1 * numPoints + i0 ] = true;
  191. p0.set( coords[ 3 * i0 ], coords[ 3 * i0 + 1 ], coords[ 3 * i0 + 2 ] );
  192. p1.set( coords[ 3 * i1 ], coords[ 3 * i1 + 1 ], coords[ 3 * i1 + 2 ] ); // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  193. let mark0 = 0;
  194. let d = localPlane.distanceToPoint( p0 );
  195. if ( d > delta ) {
  196. mark0 = 2;
  197. points2.push( p0.clone() );
  198. } else if ( d < - delta ) {
  199. mark0 = 1;
  200. points1.push( p0.clone() );
  201. } else {
  202. mark0 = 3;
  203. points1.push( p0.clone() );
  204. points2.push( p0.clone() );
  205. } // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  206. let mark1 = 0;
  207. d = localPlane.distanceToPoint( p1 );
  208. if ( d > delta ) {
  209. mark1 = 2;
  210. points2.push( p1.clone() );
  211. } else if ( d < - delta ) {
  212. mark1 = 1;
  213. points1.push( p1.clone() );
  214. } else {
  215. mark1 = 3;
  216. points1.push( p1.clone() );
  217. points2.push( p1.clone() );
  218. }
  219. if ( mark0 === 1 && mark1 === 2 || mark0 === 2 && mark1 === 1 ) {
  220. // Intersection of segment with the plane
  221. this.tempLine1.start.copy( p0 );
  222. this.tempLine1.end.copy( p1 );
  223. let intersection = new THREE.Vector3();
  224. intersection = localPlane.intersectLine( this.tempLine1, intersection );
  225. if ( intersection === null ) {
  226. // Shouldn't happen
  227. console.error( 'Internal error: segment does not intersect plane.' );
  228. output.segmentedObject1 = null;
  229. output.segmentedObject2 = null;
  230. return 0;
  231. }
  232. points1.push( intersection );
  233. points2.push( intersection.clone() );
  234. }
  235. }
  236. } // Calculate debris mass (very fast and imprecise):
  237. const newMass = object.userData.mass * 0.5; // Calculate debris Center of Mass (again fast and imprecise)
  238. this.tempCM1.set( 0, 0, 0 );
  239. let radius1 = 0;
  240. const numPoints1 = points1.length;
  241. if ( numPoints1 > 0 ) {
  242. for ( let i = 0; i < numPoints1; i ++ ) this.tempCM1.add( points1[ i ] );
  243. this.tempCM1.divideScalar( numPoints1 );
  244. for ( let i = 0; i < numPoints1; i ++ ) {
  245. const p = points1[ i ];
  246. p.sub( this.tempCM1 );
  247. radius1 = Math.max( radius1, p.x, p.y, p.z );
  248. }
  249. this.tempCM1.add( object.position );
  250. }
  251. this.tempCM2.set( 0, 0, 0 );
  252. let radius2 = 0;
  253. const numPoints2 = points2.length;
  254. if ( numPoints2 > 0 ) {
  255. for ( let i = 0; i < numPoints2; i ++ ) this.tempCM2.add( points2[ i ] );
  256. this.tempCM2.divideScalar( numPoints2 );
  257. for ( let i = 0; i < numPoints2; i ++ ) {
  258. const p = points2[ i ];
  259. p.sub( this.tempCM2 );
  260. radius2 = Math.max( radius2, p.x, p.y, p.z );
  261. }
  262. this.tempCM2.add( object.position );
  263. }
  264. let object1 = null;
  265. let object2 = null;
  266. let numObjects = 0;
  267. if ( numPoints1 > 4 ) {
  268. object1 = new THREE.Mesh( new THREE.ConvexGeometry( points1 ), object.material );
  269. object1.position.copy( this.tempCM1 );
  270. object1.quaternion.copy( object.quaternion );
  271. this.prepareBreakableObject( object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak );
  272. numObjects ++;
  273. }
  274. if ( numPoints2 > 4 ) {
  275. object2 = new THREE.Mesh( new THREE.ConvexGeometry( points2 ), object.material );
  276. object2.position.copy( this.tempCM2 );
  277. object2.quaternion.copy( object.quaternion );
  278. this.prepareBreakableObject( object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak );
  279. numObjects ++;
  280. }
  281. output.object1 = object1;
  282. output.object2 = object2;
  283. return numObjects;
  284. }
  285. static transformFreeVector( v, m ) {
  286. // input:
  287. // vector interpreted as a free vector
  288. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  289. const x = v.x,
  290. y = v.y,
  291. z = v.z;
  292. const e = m.elements;
  293. v.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  294. v.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  295. v.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  296. return v;
  297. }
  298. static transformFreeVectorInverse( v, m ) {
  299. // input:
  300. // vector interpreted as a free vector
  301. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  302. const x = v.x,
  303. y = v.y,
  304. z = v.z;
  305. const e = m.elements;
  306. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z;
  307. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z;
  308. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z;
  309. return v;
  310. }
  311. static transformTiedVectorInverse( v, m ) {
  312. // input:
  313. // vector interpreted as a tied (ordinary) vector
  314. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  315. const x = v.x,
  316. y = v.y,
  317. z = v.z;
  318. const e = m.elements;
  319. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z - e[ 12 ];
  320. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z - e[ 13 ];
  321. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z - e[ 14 ];
  322. return v;
  323. }
  324. static transformPlaneToLocalSpace( plane, m, resultPlane ) {
  325. resultPlane.normal.copy( plane.normal );
  326. resultPlane.constant = plane.constant;
  327. const referencePoint = ConvexObjectBreaker.transformTiedVectorInverse( plane.coplanarPoint( _v1 ), m );
  328. ConvexObjectBreaker.transformFreeVectorInverse( resultPlane.normal, m ); // recalculate constant (like in setFromNormalAndCoplanarPoint)
  329. resultPlane.constant = - referencePoint.dot( resultPlane.normal );
  330. }
  331. }
  332. THREE.ConvexObjectBreaker = ConvexObjectBreaker;
  333. } )();