babylon.csg.js 21 KB

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