babylon.csg.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 = new Array(), vertices;
  261. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  262. if (mesh instanceof BABYLON.Mesh) {
  263. mesh.computeWorldMatrix(true);
  264. matrix = mesh.getWorldMatrix();
  265. meshPosition = mesh.position.clone();
  266. meshRotation = mesh.rotation.clone();
  267. if (mesh.rotationQuaternion) {
  268. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  269. }
  270. meshScaling = mesh.scaling.clone();
  271. }
  272. else {
  273. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  274. }
  275. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  276. var subMeshes = mesh.subMeshes;
  277. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  278. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  279. vertices = [];
  280. for (var j = 0; j < 3; j++) {
  281. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  282. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  283. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  284. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  285. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  286. vertex = new Vertex(position, normal, uv);
  287. vertices.push(vertex);
  288. }
  289. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  290. // To handle the case of degenerated triangle
  291. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  292. if (polygon.plane)
  293. polygons.push(polygon);
  294. }
  295. }
  296. var csg = CSG.FromPolygons(polygons);
  297. csg.matrix = matrix;
  298. csg.position = meshPosition;
  299. csg.rotation = meshRotation;
  300. csg.scaling = meshScaling;
  301. csg.rotationQuaternion = meshRotationQuaternion;
  302. currentCSGMeshId++;
  303. return csg;
  304. };
  305. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  306. CSG.FromPolygons = function (polygons) {
  307. var csg = new CSG();
  308. csg.polygons = polygons;
  309. return csg;
  310. };
  311. CSG.prototype.clone = function () {
  312. var csg = new CSG();
  313. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  314. csg.copyTransformAttributes(this);
  315. return csg;
  316. };
  317. CSG.prototype.toPolygons = function () {
  318. return this.polygons;
  319. };
  320. CSG.prototype.union = function (csg) {
  321. var a = new Node(this.clone().polygons);
  322. var b = new Node(csg.clone().polygons);
  323. a.clipTo(b);
  324. b.clipTo(a);
  325. b.invert();
  326. b.clipTo(a);
  327. b.invert();
  328. a.build(b.allPolygons());
  329. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  330. };
  331. CSG.prototype.unionInPlace = function (csg) {
  332. var a = new Node(this.polygons);
  333. var b = new Node(csg.polygons);
  334. a.clipTo(b);
  335. b.clipTo(a);
  336. b.invert();
  337. b.clipTo(a);
  338. b.invert();
  339. a.build(b.allPolygons());
  340. this.polygons = a.allPolygons();
  341. };
  342. CSG.prototype.subtract = function (csg) {
  343. var a = new Node(this.clone().polygons);
  344. var b = new Node(csg.clone().polygons);
  345. a.invert();
  346. a.clipTo(b);
  347. b.clipTo(a);
  348. b.invert();
  349. b.clipTo(a);
  350. b.invert();
  351. a.build(b.allPolygons());
  352. a.invert();
  353. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  354. };
  355. CSG.prototype.subtractInPlace = function (csg) {
  356. var a = new Node(this.polygons);
  357. var b = new Node(csg.polygons);
  358. a.invert();
  359. a.clipTo(b);
  360. b.clipTo(a);
  361. b.invert();
  362. b.clipTo(a);
  363. b.invert();
  364. a.build(b.allPolygons());
  365. a.invert();
  366. this.polygons = a.allPolygons();
  367. };
  368. CSG.prototype.intersect = function (csg) {
  369. var a = new Node(this.clone().polygons);
  370. var b = new Node(csg.clone().polygons);
  371. a.invert();
  372. b.clipTo(a);
  373. b.invert();
  374. a.clipTo(b);
  375. b.clipTo(a);
  376. a.build(b.allPolygons());
  377. a.invert();
  378. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  379. };
  380. CSG.prototype.intersectInPlace = function (csg) {
  381. var a = new Node(this.polygons);
  382. var b = new Node(csg.polygons);
  383. a.invert();
  384. b.clipTo(a);
  385. b.invert();
  386. a.clipTo(b);
  387. b.clipTo(a);
  388. a.build(b.allPolygons());
  389. a.invert();
  390. this.polygons = a.allPolygons();
  391. };
  392. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  393. // not modified.
  394. CSG.prototype.inverse = function () {
  395. var csg = this.clone();
  396. csg.inverseInPlace();
  397. return csg;
  398. };
  399. CSG.prototype.inverseInPlace = function () {
  400. this.polygons.map(function (p) { p.flip(); });
  401. };
  402. // This is used to keep meshes transformations so they can be restored
  403. // when we build back a Babylon Mesh
  404. // NB : All CSG operations are performed in world coordinates
  405. CSG.prototype.copyTransformAttributes = function (csg) {
  406. this.matrix = csg.matrix;
  407. this.position = csg.position;
  408. this.rotation = csg.rotation;
  409. this.scaling = csg.scaling;
  410. this.rotationQuaternion = csg.rotationQuaternion;
  411. return this;
  412. };
  413. // Build Raw mesh from CSG
  414. // Coordinates here are in world space
  415. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  416. var matrix = this.matrix.clone();
  417. matrix.invert();
  418. 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;
  419. if (keepSubMeshes) {
  420. // Sort Polygons, since subMeshes are indices range
  421. polygons.sort(function (a, b) {
  422. if (a.shared.meshId === b.shared.meshId) {
  423. return a.shared.subMeshId - b.shared.subMeshId;
  424. }
  425. else {
  426. return a.shared.meshId - b.shared.meshId;
  427. }
  428. });
  429. }
  430. for (var i = 0, il = polygons.length; i < il; i++) {
  431. polygon = polygons[i];
  432. // Building SubMeshes
  433. if (!subMesh_dict[polygon.shared.meshId]) {
  434. subMesh_dict[polygon.shared.meshId] = {};
  435. }
  436. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  437. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  438. indexStart: +Infinity,
  439. indexEnd: -Infinity,
  440. materialIndex: polygon.shared.materialIndex
  441. };
  442. }
  443. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  444. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  445. polygonIndices[0] = 0;
  446. polygonIndices[1] = j - 1;
  447. polygonIndices[2] = j;
  448. for (var k = 0; k < 3; k++) {
  449. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  450. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  451. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  452. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  453. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  454. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  455. // Check if 2 points can be merged
  456. if (!(typeof vertex_idx !== 'undefined' &&
  457. normals[vertex_idx * 3] === localNormal.x &&
  458. normals[vertex_idx * 3 + 1] === localNormal.y &&
  459. normals[vertex_idx * 3 + 2] === localNormal.z &&
  460. uvs[vertex_idx * 2] === uv.x &&
  461. uvs[vertex_idx * 2 + 1] === uv.y)) {
  462. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  463. uvs.push(uv.x, uv.y);
  464. normals.push(normal.x, normal.y, normal.z);
  465. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  466. }
  467. indices.push(vertex_idx);
  468. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  469. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  470. currentIndex++;
  471. }
  472. }
  473. }
  474. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  475. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  476. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  477. mesh.setIndices(indices);
  478. if (keepSubMeshes) {
  479. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  480. var materialIndexOffset = 0, materialMaxIndex;
  481. mesh.subMeshes.length = 0;
  482. for (var m in subMesh_dict) {
  483. materialMaxIndex = -1;
  484. for (var sm in subMesh_dict[m]) {
  485. subMesh_obj = subMesh_dict[m][sm];
  486. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  487. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  488. }
  489. materialIndexOffset += ++materialMaxIndex;
  490. }
  491. }
  492. return mesh;
  493. };
  494. // Build Mesh from CSG taking material and transforms into account
  495. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  496. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  497. mesh.material = material;
  498. mesh.position.copyFrom(this.position);
  499. mesh.rotation.copyFrom(this.rotation);
  500. if (this.rotationQuaternion) {
  501. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  502. }
  503. mesh.scaling.copyFrom(this.scaling);
  504. mesh.computeWorldMatrix(true);
  505. return mesh;
  506. };
  507. return CSG;
  508. })();
  509. BABYLON.CSG = CSG;
  510. })(BABYLON || (BABYLON = {}));
  511. //# sourceMappingURL=babylon.csg.js.map