babylon.csg.js 23 KB

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