babylon.boundingBoxRenderer.ts 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. module BABYLON {
  2. export class BoundingBoxRenderer {
  3. public frontColor = new BABYLON.Color3(1, 1, 1);
  4. public backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  5. public showBackLines = true;
  6. public renderList = new BABYLON.SmartArray(32);
  7. private _scene: Scene;
  8. private _colorShader: ShaderMaterial;
  9. private _vb: VertexBuffer;
  10. private _ib: WebGLBuffer;
  11. constructor(scene: Scene) {
  12. this._scene = scene;
  13. this._colorShader = new ShaderMaterial("colorShader", scene, "color",
  14. {
  15. attributes: ["position"],
  16. uniforms: ["worldViewProjection", "color"]
  17. });
  18. var engine = this._scene.getEngine();
  19. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20. this._vb = new BABYLON.VertexBuffer(null, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false, engine);
  21. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  22. }
  23. public reset(): void {
  24. this.renderList.reset();
  25. }
  26. public render(): void {
  27. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  28. return;
  29. }
  30. var engine = this._scene.getEngine();
  31. engine.setDepthWrite(false);
  32. this._colorShader._preBind();
  33. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34. var mesh = this.renderList.data[boundingBoxIndex];
  35. var boundingBox = mesh.getBoundingInfo().boundingBox;
  36. var min = boundingBox.minimum;
  37. var max = boundingBox.maximum;
  38. var diff = max.subtract(min);
  39. var median = min.add(diff.scale(0.5));
  40. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  41. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  42. .multiply(mesh.getWorldMatrix());
  43. // VBOs
  44. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  45. if (this.showBackLines) {
  46. // Back
  47. engine.setDepthFunctionToGreaterOrEqual();
  48. this._colorShader.setColor3("color", this.backColor);
  49. this._colorShader.bind(worldMatrix, mesh);
  50. // Draw order
  51. engine.draw(false, 0, 24);
  52. }
  53. // Front
  54. engine.setDepthFunctionToLess();
  55. this._colorShader.setColor3("color", this.frontColor);
  56. this._colorShader.bind(worldMatrix, mesh);
  57. // Draw order
  58. engine.draw(false, 0, 24);
  59. }
  60. this._colorShader.unbind();
  61. engine.setDepthFunctionToLessOrEqual();
  62. engine.setDepthWrite(true);
  63. }
  64. public dispose(): void {
  65. this._colorShader.dispose();
  66. this._vb.dispose();
  67. this._scene.getEngine()._releaseBuffer(this._ib);
  68. }
  69. }
  70. }