2
0

ConvexObjectBreaker.js 13 KB

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