babylon.csg.js 23 KB

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