babylon.csg.js 23 KB

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