babylon.boundingBoxRenderer.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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<BoundingBox>(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(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  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 boundingBox = this.renderList.data[boundingBoxIndex];
  35. var min = boundingBox.minimum;
  36. var max = boundingBox.maximum;
  37. var diff = max.subtract(min);
  38. var median = min.add(diff.scale(0.5));
  39. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  40. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  41. .multiply(boundingBox.getWorldMatrix());
  42. // VBOs
  43. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  44. if (this.showBackLines) {
  45. // Back
  46. engine.setDepthFunctionToGreaterOrEqual();
  47. this._colorShader.setColor3("color", this.backColor);
  48. this._colorShader.bind(worldMatrix);
  49. // Draw order
  50. engine.draw(false, 0, 24);
  51. }
  52. // Front
  53. engine.setDepthFunctionToLess();
  54. this._colorShader.setColor3("color", this.frontColor);
  55. this._colorShader.bind(worldMatrix);
  56. // Draw order
  57. engine.draw(false, 0, 24);
  58. }
  59. this._colorShader.unbind();
  60. engine.setDepthFunctionToLessOrEqual();
  61. engine.setDepthWrite(true);
  62. }
  63. public dispose(): void {
  64. this._colorShader.dispose();
  65. this._vb.dispose();
  66. this._scene.getEngine()._releaseBuffer(this._ib);
  67. }
  68. }
  69. }