babylon.csg.ts 23 KB

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