babylon.csg.js 22 KB

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