ConvexObjectBreaker.js 14 KB

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