babylon.csg.ts 23 KB

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