ConvexObjectBreaker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. console.warn( "THREE.ConvexObjectBreaker: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  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 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. * - 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.ConvexBufferGeometry. The BoxBufferGeometry, SphereBufferGeometry 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. THREE.ConvexObjectBreaker = function ( minSizeForBreak, smallDelta ) {
  31. this.minSizeForBreak = minSizeForBreak || 1.4;
  32. this.smallDelta = smallDelta || 0.0001;
  33. this.tempLine1 = new THREE.Line3();
  34. this.tempPlane1 = new THREE.Plane();
  35. this.tempPlane2 = new THREE.Plane();
  36. this.tempPlane_Cut = new THREE.Plane();
  37. this.tempCM1 = new THREE.Vector3();
  38. this.tempCM2 = new THREE.Vector3();
  39. this.tempVector3 = new THREE.Vector3();
  40. this.tempVector3_2 = new THREE.Vector3();
  41. this.tempVector3_3 = new THREE.Vector3();
  42. this.tempVector3_P0 = new THREE.Vector3();
  43. this.tempVector3_P1 = new THREE.Vector3();
  44. this.tempVector3_P2 = new THREE.Vector3();
  45. this.tempVector3_N0 = new THREE.Vector3();
  46. this.tempVector3_N1 = new THREE.Vector3();
  47. this.tempVector3_AB = new THREE.Vector3();
  48. this.tempVector3_CB = new THREE.Vector3();
  49. this.tempResultObjects = { object1: null, object2: null };
  50. this.segments = [];
  51. var n = 30 * 30;
  52. for ( var i = 0; i < n; i ++ ) this.segments[ i ] = false;
  53. };
  54. THREE.ConvexObjectBreaker.prototype = {
  55. constructor: THREE.ConvexObjectBreaker,
  56. prepareBreakableObject: function ( object, mass, velocity, angularVelocity, breakable ) {
  57. // object is a THREE.Object3d (normally a Mesh), must have a BufferGeometry, and it must be convex.
  58. // Its material property is propagated to its children (sub-pieces)
  59. // mass must be > 0
  60. if ( ! object.geometry.isBufferGeometry ) {
  61. console.error( 'THREE.ConvexObjectBreaker.prepareBreakableObject(): Parameter object must have a BufferGeometry.' );
  62. }
  63. var userData = object.userData;
  64. userData.mass = mass;
  65. userData.velocity = velocity.clone();
  66. userData.angularVelocity = angularVelocity.clone();
  67. userData.breakable = breakable;
  68. },
  69. /*
  70. * @param {int} maxRadialIterations Iterations for radial cuts.
  71. * @param {int} maxRandomIterations Max random iterations for not-radial cuts
  72. *
  73. * Returns the array of pieces
  74. */
  75. subdivideByImpact: function ( object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations ) {
  76. var debris = [];
  77. var tempPlane1 = this.tempPlane1;
  78. var tempPlane2 = this.tempPlane2;
  79. this.tempVector3.addVectors( pointOfImpact, normal );
  80. tempPlane1.setFromCoplanarPoints( pointOfImpact, object.position, this.tempVector3 );
  81. var maxTotalIterations = maxRandomIterations + maxRadialIterations;
  82. var scope = this;
  83. function subdivideRadial( subObject, startAngle, endAngle, numIterations ) {
  84. if ( Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations ) {
  85. debris.push( subObject );
  86. return;
  87. }
  88. var angle = Math.PI;
  89. if ( numIterations === 0 ) {
  90. tempPlane2.normal.copy( tempPlane1.normal );
  91. tempPlane2.constant = tempPlane1.constant;
  92. } else {
  93. if ( numIterations <= maxRadialIterations ) {
  94. angle = ( endAngle - startAngle ) * ( 0.2 + 0.6 * Math.random() ) + startAngle;
  95. // Rotate tempPlane2 at impact point around normal axis and the angle
  96. scope.tempVector3_2.copy( object.position ).sub( pointOfImpact ).applyAxisAngle( normal, angle ).add( pointOfImpact );
  97. tempPlane2.setFromCoplanarPoints( pointOfImpact, scope.tempVector3, scope.tempVector3_2 );
  98. } else {
  99. angle = ( ( 0.5 * ( numIterations & 1 ) ) + 0.2 * ( 2 - Math.random() ) ) * Math.PI;
  100. // Rotate tempPlane2 at object position around normal axis and the angle
  101. scope.tempVector3_2.copy( pointOfImpact ).sub( subObject.position ).applyAxisAngle( normal, angle ).add( subObject.position );
  102. scope.tempVector3_3.copy( normal ).add( subObject.position );
  103. tempPlane2.setFromCoplanarPoints( subObject.position, scope.tempVector3_3, scope.tempVector3_2 );
  104. }
  105. }
  106. // Perform the cut
  107. scope.cutByPlane( subObject, tempPlane2, scope.tempResultObjects );
  108. var obj1 = scope.tempResultObjects.object1;
  109. var 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: function ( 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. var geometry = object.geometry;
  126. var coords = geometry.attributes.position.array;
  127. var normals = geometry.attributes.normal.array;
  128. var numPoints = coords.length / 3;
  129. var numFaces = numPoints / 3;
  130. var 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. var idx = faceIdx * 3 + vert;
  138. return indices ? indices[ idx ] : idx;
  139. }
  140. var points1 = [];
  141. var points2 = [];
  142. var delta = this.smallDelta;
  143. // Reset segments mark
  144. var numPointPairs = numPoints * numPoints;
  145. for ( var i = 0; i < numPointPairs; i ++ ) this.segments[ i ] = false;
  146. var p0 = this.tempVector3_P0;
  147. var p1 = this.tempVector3_P1;
  148. var n0 = this.tempVector3_N0;
  149. var n1 = this.tempVector3_N1;
  150. // Iterate through the faces to mark edges shared by coplanar faces
  151. for ( var i = 0; i < numFaces - 1; i ++ ) {
  152. var a1 = getVertexIndex( i, 0 );
  153. var b1 = getVertexIndex( i, 1 );
  154. var c1 = getVertexIndex( i, 2 );
  155. // Assuming all 3 vertices have the same normal
  156. n0.set( normals[ a1 ], normals[ a1 ] + 1, normals[ a1 ] + 2 );
  157. for ( var j = i + 1; j < numFaces; j ++ ) {
  158. var a2 = getVertexIndex( j, 0 );
  159. var b2 = getVertexIndex( j, 1 );
  160. var c2 = getVertexIndex( j, 2 );
  161. // Assuming all 3 vertices have the same normal
  162. n1.set( normals[ a2 ], normals[ a2 ] + 1, normals[ a2 ] + 2 );
  163. var coplanar = 1 - n0.dot( n1 ) < delta;
  164. if ( coplanar ) {
  165. if ( a1 === a2 || a1 === b2 || a1 === c2 ) {
  166. if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  167. this.segments[ a1 * numPoints + b1 ] = true;
  168. this.segments[ b1 * numPoints + a1 ] = true;
  169. } else {
  170. this.segments[ c1 * numPoints + a1 ] = true;
  171. this.segments[ a1 * numPoints + c1 ] = true;
  172. }
  173. } else if ( b1 === a2 || b1 === b2 || b1 === c2 ) {
  174. this.segments[ c1 * numPoints + b1 ] = true;
  175. this.segments[ b1 * numPoints + c1 ] = true;
  176. }
  177. }
  178. }
  179. }
  180. // Transform the plane to object local space
  181. var localPlane = this.tempPlane_Cut;
  182. object.updateMatrix();
  183. THREE.ConvexObjectBreaker.transformPlaneToLocalSpace( plane, object.matrix, localPlane );
  184. // Iterate through the faces adding points to both pieces
  185. for ( var i = 0; i < numFaces; i ++ ) {
  186. var va = getVertexIndex( i, 0 );
  187. var vb = getVertexIndex( i, 1 );
  188. var vc = getVertexIndex( i, 2 );
  189. for ( var segment = 0; segment < 3; segment ++ ) {
  190. var i0 = segment === 0 ? va : ( segment === 1 ? vb : vc );
  191. var i1 = segment === 0 ? vb : ( segment === 1 ? vc : va );
  192. var segmentState = this.segments[ i0 * numPoints + i1 ];
  193. if ( segmentState ) continue; // The segment already has been processed in another face
  194. // Mark segment as processed (also inverted segment)
  195. this.segments[ i0 * numPoints + i1 ] = true;
  196. this.segments[ i1 * numPoints + i0 ] = true;
  197. p0.set( coords[ 3 * i0 ], coords[ 3 * i0 + 1 ], coords[ 3 * i0 + 2 ] );
  198. p1.set( coords[ 3 * i1 ], coords[ 3 * i1 + 1 ], coords[ 3 * i1 + 2 ] );
  199. // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  200. var mark0 = 0;
  201. var d = localPlane.distanceToPoint( p0 );
  202. if ( d > delta ) {
  203. mark0 = 2;
  204. points2.push( p0.clone() );
  205. } else if ( d < - delta ) {
  206. mark0 = 1;
  207. points1.push( p0.clone() );
  208. } else {
  209. mark0 = 3;
  210. points1.push( p0.clone() );
  211. points2.push( p0.clone() );
  212. }
  213. // mark: 1 for negative side, 2 for positive side, 3 for coplanar point
  214. var mark1 = 0;
  215. var d = localPlane.distanceToPoint( p1 );
  216. if ( d > delta ) {
  217. mark1 = 2;
  218. points2.push( p1.clone() );
  219. } else if ( d < - delta ) {
  220. mark1 = 1;
  221. points1.push( p1.clone() );
  222. } else {
  223. mark1 = 3;
  224. points1.push( p1.clone() );
  225. points2.push( p1.clone() );
  226. }
  227. if ( ( mark0 === 1 && mark1 === 2 ) || ( mark0 === 2 && mark1 === 1 ) ) {
  228. // Intersection of segment with the plane
  229. this.tempLine1.start.copy( p0 );
  230. this.tempLine1.end.copy( p1 );
  231. var intersection = new THREE.Vector3();
  232. intersection = localPlane.intersectLine( this.tempLine1, intersection );
  233. if ( intersection === undefined ) {
  234. // Shouldn't happen
  235. console.error( "Internal error: segment does not intersect plane." );
  236. output.segmentedObject1 = null;
  237. output.segmentedObject2 = null;
  238. return 0;
  239. }
  240. points1.push( intersection );
  241. points2.push( intersection.clone() );
  242. }
  243. }
  244. }
  245. // Calculate debris mass (very fast and imprecise):
  246. var newMass = object.userData.mass * 0.5;
  247. // Calculate debris Center of Mass (again fast and imprecise)
  248. this.tempCM1.set( 0, 0, 0 );
  249. var radius1 = 0;
  250. var numPoints1 = points1.length;
  251. if ( numPoints1 > 0 ) {
  252. for ( var i = 0; i < numPoints1; i ++ ) this.tempCM1.add( points1[ i ] );
  253. this.tempCM1.divideScalar( numPoints1 );
  254. for ( var i = 0; i < numPoints1; i ++ ) {
  255. var p = points1[ i ];
  256. p.sub( this.tempCM1 );
  257. radius1 = Math.max( radius1, p.x, p.y, p.z );
  258. }
  259. this.tempCM1.add( object.position );
  260. }
  261. this.tempCM2.set( 0, 0, 0 );
  262. var radius2 = 0;
  263. var numPoints2 = points2.length;
  264. if ( numPoints2 > 0 ) {
  265. for ( var i = 0; i < numPoints2; i ++ ) this.tempCM2.add( points2[ i ] );
  266. this.tempCM2.divideScalar( numPoints2 );
  267. for ( var i = 0; i < numPoints2; i ++ ) {
  268. var p = points2[ i ];
  269. p.sub( this.tempCM2 );
  270. radius2 = Math.max( radius2, p.x, p.y, p.z );
  271. }
  272. this.tempCM2.add( object.position );
  273. }
  274. var object1 = null;
  275. var object2 = null;
  276. var numObjects = 0;
  277. if ( numPoints1 > 4 ) {
  278. object1 = new THREE.Mesh( new THREE.ConvexBufferGeometry( points1 ), object.material );
  279. object1.position.copy( this.tempCM1 );
  280. object1.quaternion.copy( object.quaternion );
  281. this.prepareBreakableObject( object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak );
  282. numObjects ++;
  283. }
  284. if ( numPoints2 > 4 ) {
  285. object2 = new THREE.Mesh( new THREE.ConvexBufferGeometry( points2 ), object.material );
  286. object2.position.copy( this.tempCM2 );
  287. object2.quaternion.copy( object.quaternion );
  288. this.prepareBreakableObject( object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak );
  289. numObjects ++;
  290. }
  291. output.object1 = object1;
  292. output.object2 = object2;
  293. return numObjects;
  294. }
  295. };
  296. THREE.ConvexObjectBreaker.transformFreeVector = function ( v, m ) {
  297. // input:
  298. // vector interpreted as a free vector
  299. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  300. var x = v.x, y = v.y, z = v.z;
  301. var e = m.elements;
  302. v.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  303. v.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  304. v.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  305. return v;
  306. };
  307. THREE.ConvexObjectBreaker.transformFreeVectorInverse = function ( v, m ) {
  308. // input:
  309. // vector interpreted as a free vector
  310. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  311. var x = v.x, y = v.y, z = v.z;
  312. var e = m.elements;
  313. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z;
  314. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z;
  315. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z;
  316. return v;
  317. };
  318. THREE.ConvexObjectBreaker.transformTiedVectorInverse = function ( v, m ) {
  319. // input:
  320. // vector interpreted as a tied (ordinary) vector
  321. // THREE.Matrix4 orthogonal matrix (matrix without scale)
  322. var x = v.x, y = v.y, z = v.z;
  323. var e = m.elements;
  324. v.x = e[ 0 ] * x + e[ 1 ] * y + e[ 2 ] * z - e[ 12 ];
  325. v.y = e[ 4 ] * x + e[ 5 ] * y + e[ 6 ] * z - e[ 13 ];
  326. v.z = e[ 8 ] * x + e[ 9 ] * y + e[ 10 ] * z - e[ 14 ];
  327. return v;
  328. };
  329. THREE.ConvexObjectBreaker.transformPlaneToLocalSpace = function () {
  330. var v1 = new THREE.Vector3();
  331. return function transformPlaneToLocalSpace( plane, m, resultPlane ) {
  332. resultPlane.normal.copy( plane.normal );
  333. resultPlane.constant = plane.constant;
  334. var referencePoint = THREE.ConvexObjectBreaker.transformTiedVectorInverse( plane.coplanarPoint( v1 ), m );
  335. THREE.ConvexObjectBreaker.transformFreeVectorInverse( resultPlane.normal, m );
  336. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  337. resultPlane.constant = - referencePoint.dot( resultPlane.normal );
  338. };
  339. }();