csg.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var CreateCSGTestScene = function (engine) {
  2. var scene = new BABYLON.Scene(engine);
  3. var light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(0, -0.5, -1.0), scene);
  4. var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 10, new BABYLON.Vector3(0, 0, 0), scene);
  5. camera.setPosition(new BABYLON.Vector3(10, 10, 10));
  6. light.position = new BABYLON.Vector3(20, 150, 70);
  7. camera.minZ = 10.0;
  8. scene.ambientColor = new BABYLON.Color3(0.3, 0.3, 0.3);
  9. var sourceMat = new BABYLON.StandardMaterial("sourceMat", scene);
  10. sourceMat.wireframe = true;
  11. sourceMat.backFaceCulling = false;
  12. var a = BABYLON.Mesh.CreateSphere("sphere", 16, 4, scene);
  13. var b = BABYLON.Mesh.CreateBox("box", 4, scene);
  14. var c = BABYLON.Mesh.CreateBox("box", 4, scene);
  15. a.material = sourceMat;
  16. b.material = sourceMat;
  17. c.material = sourceMat;
  18. a.position.y += 5;
  19. b.position.y += 2.5;
  20. c.position.y += 3.5;
  21. c.rotation.y += Math.PI / 8.0;
  22. var aCSG = BABYLON.CSG.FromMesh(a);
  23. var bCSG = BABYLON.CSG.FromMesh(b);
  24. var cCSG = BABYLON.CSG.FromMesh(c);
  25. // Set up a MultiMaterial
  26. var mat0 = new BABYLON.StandardMaterial("mat0", scene);
  27. var mat1 = new BABYLON.StandardMaterial("mat1", scene);
  28. mat0.diffuseColor.copyFromFloats(0.8, 0.2, 0.2);
  29. mat0.backFaceCulling = false;
  30. mat1.diffuseColor.copyFromFloats(0.2, 0.8, 0.2);
  31. mat1.backFaceCulling = false;
  32. var subCSG = bCSG.subtract(aCSG);
  33. var newMesh = subCSG.toMesh("csg", mat0, scene);
  34. newMesh.position = new BABYLON.Vector3(-10, 0, 0);
  35. subCSG = aCSG.subtract(bCSG);
  36. newMesh = subCSG.toMesh("csg2", mat0, scene);
  37. newMesh.position = new BABYLON.Vector3(10, 0, 0);
  38. subCSG = aCSG.intersect(bCSG);
  39. newMesh = subCSG.toMesh("csg3", mat0, scene);
  40. newMesh.position = new BABYLON.Vector3(0, 0, 10);
  41. // Submeshes are built in order : mat0 will be for the first cube, and mat1 for the second
  42. var multiMat = new BABYLON.MultiMaterial("multiMat", scene);
  43. multiMat.subMaterials.push(mat0, mat1);
  44. // Last parameter to true means you want to build 1 subMesh for each mesh involved
  45. subCSG = bCSG.subtract(cCSG);
  46. newMesh = subCSG.toMesh("csg4", multiMat, scene, true);
  47. newMesh.position = new BABYLON.Vector3(0, 0, -10);
  48. return scene;
  49. };