babylon.csg.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. "use strict";
  2. var BABYLON = BABYLON || {};
  3. // Constructive Solid Geometry for BABYLON
  4. // Based on https://github.com/evanw/csg.js/
  5. (function() {
  6. // Unique ID when we import meshes from Babylon to CSG
  7. var _currentCSGMeshId = 0;
  8. BABYLON.CSG = function() {
  9. this.polygons = [];
  10. };
  11. // Convert BABYLON.Mesh to BABYLON.CSG
  12. BABYLON.CSG.FromMesh = function( mesh ) {
  13. var vertex, normal, uv, position,
  14. polygon,
  15. polygons = [],
  16. vertices;
  17. if ( mesh instanceof BABYLON.Mesh ) {
  18. mesh.computeWorldMatrix(true);
  19. this.matrix = mesh.getWorldMatrix();
  20. this.position = mesh.position.clone();
  21. this.rotation = mesh.rotation.clone();
  22. this.scaling = mesh.scaling.clone();
  23. } else {
  24. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25. }
  26. var indices = mesh.getIndices(),
  27. positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind),
  28. normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind),
  29. uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30. var subMeshes = mesh.subMeshes;
  31. for ( var sm = 0, sml = subMeshes.length; sm < sml; sm++ ) {
  32. for ( var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3 ) {
  33. vertices = [];
  34. for (var j = 0; j < 3; j++) {
  35. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  37. position = new BABYLON.Vector3( positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  38. position = BABYLON.Vector3.TransformCoordinates(position, this.matrix);
  39. normal = BABYLON.Vector3.TransformNormal(normal, this.matrix);
  40. vertex = new BABYLON.CSG.Vertex( position, normal, uv );
  41. vertices.push( vertex );
  42. }
  43. polygon = new BABYLON.CSG.Polygon(vertices, { subMeshId : sm, meshId : _currentCSGMeshId, materialIndex : subMeshes[sm].materialIndex });
  44. polygons.push( polygon );
  45. }
  46. }
  47. var csg = BABYLON.CSG.fromPolygons( polygons );
  48. csg.copyTransformAttributes(this);
  49. _currentCSGMeshId++
  50. return csg;
  51. };
  52. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  53. BABYLON.CSG.fromPolygons = function(polygons) {
  54. var csg = new BABYLON.CSG();
  55. csg.polygons = polygons;
  56. return csg;
  57. };
  58. BABYLON.CSG.prototype = {
  59. clone: function() {
  60. var csg = new BABYLON.CSG();
  61. csg.polygons = this.polygons.map(function(p) { return p.clone(); });
  62. csg.copyTransformAttributes(this);
  63. return csg;
  64. },
  65. toPolygons: function() {
  66. return this.polygons;
  67. },
  68. union: function(csg) {
  69. var a = new BABYLON.CSG.Node(this.clone().polygons);
  70. var b = new BABYLON.CSG.Node(csg.clone().polygons);
  71. a.clipTo(b);
  72. b.clipTo(a);
  73. b.invert();
  74. b.clipTo(a);
  75. b.invert();
  76. a.build(b.allPolygons());
  77. return BABYLON.CSG.fromPolygons(a.allPolygons()).copyTransformAttributes(this);
  78. },
  79. subtract: function(csg) {
  80. var a = new BABYLON.CSG.Node(this.clone().polygons);
  81. var b = new BABYLON.CSG.Node(csg.clone().polygons);
  82. a.invert();
  83. a.clipTo(b);
  84. b.clipTo(a);
  85. b.invert();
  86. b.clipTo(a);
  87. b.invert();
  88. a.build(b.allPolygons());
  89. a.invert();
  90. return BABYLON.CSG.fromPolygons(a.allPolygons()).copyTransformAttributes(this);
  91. },
  92. intersect: function(csg) {
  93. var a = new BABYLON.CSG.Node(this.clone().polygons);
  94. var b = new BABYLON.CSG.Node(csg.clone().polygons);
  95. a.invert();
  96. b.clipTo(a);
  97. b.invert();
  98. a.clipTo(b);
  99. b.clipTo(a);
  100. a.build(b.allPolygons());
  101. a.invert();
  102. return BABYLON.CSG.fromPolygons(a.allPolygons()).copyTransformAttributes(this);
  103. },
  104. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  105. // not modified.
  106. inverse: function() {
  107. var csg = this.clone();
  108. csg.polygons.map(function(p) { p.flip(); });
  109. return csg;
  110. }
  111. };
  112. // This is used to keep meshes transformations so they can be restored
  113. // when we build back a Babylon Mesh
  114. // NB : All CSG operations are performed in world coordinates
  115. BABYLON.CSG.prototype.copyTransformAttributes = function (object) {
  116. this.matrix = object.matrix;
  117. this.position = object.position;
  118. this.rotation = object.rotation;
  119. this.scaling = object.scaling;
  120. return this;
  121. }
  122. // Build Raw mesh from CSG
  123. // Coordinates here are in world space
  124. BABYLON.CSG.prototype.buildMeshGeometry = function(name, scene, keepSubMeshes) {
  125. var matrix = this.matrix.clone();
  126. matrix.invert();
  127. var mesh = new BABYLON.Mesh(name, scene),
  128. vertices = [],
  129. indices = [],
  130. normals = [],
  131. uvs = [],
  132. vertex, normal, uv,
  133. polygons = this.polygons,
  134. polygonIndices = [0, 0, 0],
  135. polygon,
  136. vertice_dict = {},
  137. vertex_idx,
  138. currentIndex = 0,
  139. subMesh_dict = {},
  140. subMesh_obj;
  141. if (keepSubMeshes) {
  142. // Sort Polygons, since subMeshes are indices range
  143. polygons.sort(function (a,b) {
  144. if (a.shared.meshId === b.shared.meshId)
  145. return a.shared.subMeshId - b.shared.subMeshId;
  146. else
  147. return a.shared.meshId - b.shared.meshId;
  148. });
  149. }
  150. for ( var i = 0, il = polygons.length; i < il; i++ ) {
  151. polygon = polygons[i];
  152. // Building SubMeshes
  153. if (!subMesh_dict[polygon.shared.meshId]) {
  154. subMesh_dict[polygon.shared.meshId] = {};
  155. }
  156. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  157. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = { indexStart : +Infinity,
  158. indexEnd : -Infinity,
  159. materialIndex : polygon.shared.materialIndex
  160. };
  161. }
  162. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  163. for ( var j = 2, jl = polygon.vertices.length; j < jl; j++ ) {
  164. polygonIndices[0] = 0;
  165. polygonIndices[1] = j - 1;
  166. polygonIndices[2] = j;
  167. for (var k = 0; k < 3; k++) {
  168. vertex = polygon.vertices[polygonIndices[k]].pos;
  169. normal = polygon.vertices[polygonIndices[k]].normal;
  170. uv = polygon.vertices[polygonIndices[k]].uv;
  171. vertex = new BABYLON.Vector3( vertex.x, vertex.y, vertex.z );
  172. normal = new BABYLON.Vector3( normal.x, normal.y, normal.z );
  173. vertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  174. normal = BABYLON.Vector3.TransformNormal(normal, matrix);
  175. vertex_idx = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
  176. // Check if 2 points can be merged
  177. if (!(typeof vertex_idx !== 'undefined' &&
  178. normals[vertex_idx * 3] === normal.x &&
  179. normals[vertex_idx * 3 + 1] === normal.y &&
  180. normals[vertex_idx * 3 + 2] === normal.z &&
  181. uvs[vertex_idx * 2] === uv.x &&
  182. uvs[vertex_idx * 2 + 1] === uv.y))
  183. {
  184. vertices.push( vertex.x, vertex.y, vertex.z );
  185. uvs.push(uv.x, uv.y);
  186. normals.push(normal.x, normal.y, normal.z);
  187. vertex_idx = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = (vertices.length / 3) - 1;
  188. }
  189. indices.push(vertex_idx);
  190. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  191. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  192. currentIndex++
  193. }
  194. }
  195. }
  196. mesh.setVerticesData(vertices, BABYLON.VertexBuffer.PositionKind);
  197. mesh.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind);
  198. mesh.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind);
  199. mesh.setIndices(indices);
  200. if (keepSubMeshes) {
  201. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  202. var materialIndexOffset = 0,
  203. materialMaxIndex;
  204. mesh.subMeshes.length = 0;
  205. for (var m in subMesh_dict) {
  206. materialMaxIndex = -1;
  207. for (var sm in subMesh_dict[m]) {
  208. subMesh_obj = subMesh_dict[m][sm];
  209. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  210. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  211. }
  212. materialIndexOffset += ++materialMaxIndex;
  213. }
  214. }
  215. return mesh;
  216. };
  217. // Build Mesh from CSG taking material and transforms into account
  218. BABYLON.CSG.prototype.toMesh = function( name, material, scene, keepSubMeshes ) {
  219. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  220. mesh.material = material;
  221. mesh.position.copyFrom(this.position);
  222. mesh.rotation.copyFrom(this.rotation);
  223. mesh.scaling.copyFrom(this.scaling);
  224. mesh.computeWorldMatrix(true);
  225. return mesh;
  226. };
  227. // # class Vector
  228. // Represents a 3D vector.
  229. //
  230. // Example usage:
  231. //
  232. // new BABYLON.CSG.Vector(1, 2, 3);
  233. // new BABYLON.CSG.Vector([1, 2, 3]);
  234. // new BABYLON.CSG.Vector({ x: 1, y: 2, z: 3 });
  235. BABYLON.CSG.Vector = function(x, y, z) {
  236. if (arguments.length == 3) {
  237. this.x = x;
  238. this.y = y;
  239. this.z = z;
  240. } else if ('x' in x) {
  241. this.x = x.x;
  242. this.y = x.y;
  243. this.z = x.z;
  244. } else {
  245. this.x = x[0];
  246. this.y = x[1];
  247. this.z = x[2];
  248. }
  249. };
  250. BABYLON.CSG.Vector.prototype = {
  251. clone: function() {
  252. return new BABYLON.CSG.Vector(this.x, this.y, this.z);
  253. },
  254. negated: function() {
  255. return new BABYLON.CSG.Vector(-this.x, -this.y, -this.z);
  256. },
  257. plus: function(a) {
  258. return new BABYLON.CSG.Vector(this.x + a.x, this.y + a.y, this.z + a.z);
  259. },
  260. minus: function(a) {
  261. return new BABYLON.CSG.Vector(this.x - a.x, this.y - a.y, this.z - a.z);
  262. },
  263. times: function(a) {
  264. return new BABYLON.CSG.Vector(this.x * a, this.y * a, this.z * a);
  265. },
  266. dividedBy: function(a) {
  267. return new BABYLON.CSG.Vector(this.x / a, this.y / a, this.z / a);
  268. },
  269. dot: function(a) {
  270. return this.x * a.x + this.y * a.y + this.z * a.z;
  271. },
  272. lerp: function(a, t) {
  273. return this.plus(a.minus(this).times(t));
  274. },
  275. length: function() {
  276. return Math.sqrt(this.dot(this));
  277. },
  278. unit: function() {
  279. return this.dividedBy(this.length());
  280. },
  281. cross: function(a) {
  282. return new BABYLON.CSG.Vector(
  283. this.y * a.z - this.z * a.y,
  284. this.z * a.x - this.x * a.z,
  285. this.x * a.y - this.y * a.x
  286. );
  287. }
  288. };
  289. // # class Vertex
  290. // Represents a vertex of a polygon. Use your own vertex class instead of this
  291. // one to provide additional features like texture coordinates and vertex
  292. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  293. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  294. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  295. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  296. // is not used anywhere else.
  297. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  298. BABYLON.CSG.Vertex = function(pos, normal, uv) {
  299. this.pos = new BABYLON.CSG.Vector(pos);
  300. this.normal = new BABYLON.CSG.Vector(normal);
  301. this.uv = new BABYLON.CSG.Vector(uv.x, uv.y, 0);
  302. };
  303. BABYLON.CSG.Vertex.prototype = {
  304. clone: function() {
  305. return new BABYLON.CSG.Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  306. },
  307. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  308. // orientation of a polygon is flipped.
  309. flip: function() {
  310. this.normal = this.normal.negated();
  311. },
  312. // Create a new vertex between this vertex and `other` by linearly
  313. // interpolating all properties using a parameter of `t`. Subclasses should
  314. // override this to interpolate additional properties.
  315. interpolate: function(other, t) {
  316. return new BABYLON.CSG.Vertex(
  317. this.pos.lerp(other.pos, t),
  318. this.normal.lerp(other.normal, t),
  319. this.uv.lerp(other.uv, t)
  320. );
  321. }
  322. };
  323. // # class Plane
  324. // Represents a plane in 3D space.
  325. BABYLON.CSG.Plane = function(normal, w) {
  326. this.normal = normal;
  327. this.w = w;
  328. };
  329. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  330. // point is on the plane.
  331. BABYLON.CSG.Plane.EPSILON = 1e-5;
  332. BABYLON.CSG.Plane.fromPoints = function(a, b, c) {
  333. var n = c.minus(a).cross(b.minus(a)).unit();
  334. return new BABYLON.CSG.Plane(n, n.dot(a));
  335. };
  336. BABYLON.CSG.Plane.prototype = {
  337. clone: function() {
  338. return new BABYLON.CSG.Plane(this.normal.clone(), this.w);
  339. },
  340. flip: function() {
  341. this.normal = this.normal.negated();
  342. this.w = -this.w;
  343. },
  344. // Split `polygon` by this plane if needed, then put the polygon or polygon
  345. // fragments in the appropriate lists. Coplanar polygons go into either
  346. // `coplanarFront` or `coplanarBack` depending on their orientation with
  347. // respect to this plane. Polygons in front or in back of this plane go into
  348. // either `front` or `back`.
  349. splitPolygon: function(polygon, coplanarFront, coplanarBack, front, back) {
  350. var COPLANAR = 0;
  351. var FRONT = 1;
  352. var BACK = 2;
  353. var SPANNING = 3;
  354. // Classify each point as well as the entire polygon into one of the above
  355. // four classes.
  356. var polygonType = 0;
  357. var types = [];
  358. for (var i = 0; i < polygon.vertices.length; i++) {
  359. var t = this.normal.dot(polygon.vertices[i].pos) - this.w;
  360. var type = (t < -BABYLON.CSG.Plane.EPSILON) ? BACK : (t > BABYLON.CSG.Plane.EPSILON) ? FRONT : COPLANAR;
  361. polygonType |= type;
  362. types.push(type);
  363. }
  364. // Put the polygon in the correct list, splitting it when necessary.
  365. switch (polygonType) {
  366. case COPLANAR:
  367. (this.normal.dot(polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  368. break;
  369. case FRONT:
  370. front.push(polygon);
  371. break;
  372. case BACK:
  373. back.push(polygon);
  374. break;
  375. case SPANNING:
  376. var f = [], b = [];
  377. for (var i = 0; i < polygon.vertices.length; i++) {
  378. var j = (i + 1) % polygon.vertices.length;
  379. var ti = types[i], tj = types[j];
  380. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  381. if (ti != BACK) f.push(vi);
  382. if (ti != FRONT) b.push(ti != BACK ? vi.clone() : vi);
  383. if ((ti | tj) == SPANNING) {
  384. var t = (this.w - this.normal.dot(vi.pos)) / this.normal.dot(vj.pos.minus(vi.pos));
  385. var v = vi.interpolate(vj, t);
  386. f.push(v);
  387. b.push(v.clone());
  388. }
  389. }
  390. if (f.length >= 3) front.push(new BABYLON.CSG.Polygon(f, polygon.shared));
  391. if (b.length >= 3) back.push(new BABYLON.CSG.Polygon(b, polygon.shared));
  392. break;
  393. }
  394. }
  395. };
  396. // # class Polygon
  397. // Represents a convex polygon. The vertices used to initialize a polygon must
  398. // be coplanar and form a convex loop. They do not have to be `BABYLON.CSG.Vertex`
  399. // instances but they must behave similarly (duck typing can be used for
  400. // customization).
  401. //
  402. // Each convex polygon has a `shared` property, which is shared between all
  403. // polygons that are clones of each other or were split from the same polygon.
  404. // This can be used to define per-polygon properties (such as surface color).
  405. BABYLON.CSG.Polygon = function(vertices, shared) {
  406. this.vertices = vertices;
  407. this.shared = shared;
  408. this.plane = BABYLON.CSG.Plane.fromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  409. };
  410. BABYLON.CSG.Polygon.prototype = {
  411. clone: function() {
  412. var vertices = this.vertices.map(function(v) { return v.clone(); });
  413. return new BABYLON.CSG.Polygon(vertices, this.shared);
  414. },
  415. flip: function() {
  416. this.vertices.reverse().map(function(v) { v.flip(); });
  417. this.plane.flip();
  418. }
  419. };
  420. // # class Node
  421. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  422. // by picking a polygon to split along. That polygon (and all other coplanar
  423. // polygons) are added directly to that node and the other polygons are added to
  424. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  425. // no distinction between internal and leaf nodes.
  426. BABYLON.CSG.Node = function(polygons) {
  427. this.plane = null;
  428. this.front = null;
  429. this.back = null;
  430. this.polygons = [];
  431. if (polygons) this.build(polygons);
  432. };
  433. BABYLON.CSG.Node.prototype = {
  434. clone: function() {
  435. var node = new BABYLON.CSG.Node();
  436. node.plane = this.plane && this.plane.clone();
  437. node.front = this.front && this.front.clone();
  438. node.back = this.back && this.back.clone();
  439. node.polygons = this.polygons.map(function(p) { return p.clone(); });
  440. return node;
  441. },
  442. // Convert solid space to empty space and empty space to solid space.
  443. invert: function() {
  444. for (var i = 0; i < this.polygons.length; i++) {
  445. this.polygons[i].flip();
  446. }
  447. this.plane.flip();
  448. if (this.front) this.front.invert();
  449. if (this.back) this.back.invert();
  450. var temp = this.front;
  451. this.front = this.back;
  452. this.back = temp;
  453. },
  454. // Recursively remove all polygons in `polygons` that are inside this BSP
  455. // tree.
  456. clipPolygons: function(polygons) {
  457. if (!this.plane) return polygons.slice();
  458. var front = [], back = [];
  459. for (var i = 0; i < polygons.length; i++) {
  460. this.plane.splitPolygon(polygons[i], front, back, front, back);
  461. }
  462. if (this.front) front = this.front.clipPolygons(front);
  463. if (this.back) back = this.back.clipPolygons(back);
  464. else back = [];
  465. return front.concat(back);
  466. },
  467. // Remove all polygons in this BSP tree that are inside the other BSP tree
  468. // `bsp`.
  469. clipTo: function(bsp) {
  470. this.polygons = bsp.clipPolygons(this.polygons);
  471. if (this.front) this.front.clipTo(bsp);
  472. if (this.back) this.back.clipTo(bsp);
  473. },
  474. // Return a list of all polygons in this BSP tree.
  475. allPolygons: function() {
  476. var polygons = this.polygons.slice();
  477. if (this.front) polygons = polygons.concat(this.front.allPolygons());
  478. if (this.back) polygons = polygons.concat(this.back.allPolygons());
  479. return polygons;
  480. },
  481. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  482. // new polygons are filtered down to the bottom of the tree and become new
  483. // nodes there. Each set of polygons is partitioned using the first polygon
  484. // (no heuristic is used to pick a good split).
  485. build: function(polygons) {
  486. if (!polygons.length) return;
  487. if (!this.plane) this.plane = polygons[0].plane.clone();
  488. var front = [], back = [];
  489. for (var i = 0; i < polygons.length; i++) {
  490. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  491. }
  492. if (front.length) {
  493. if (!this.front) this.front = new BABYLON.CSG.Node();
  494. this.front.build(front);
  495. }
  496. if (back.length) {
  497. if (!this.back) this.back = new BABYLON.CSG.Node();
  498. this.back.build(back);
  499. }
  500. }
  501. };
  502. })();