babylon.boundingBoxRenderer.ts 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. module BABYLON {
  2. export class BoundingBoxRenderer {
  3. public frontColor = new Color3(1, 1, 1);
  4. public backColor = new Color3(0.1, 0.1, 0.1);
  5. public showBackLines = true;
  6. public renderList = new 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 = VertexData.CreateBox(1.0);
  20. this._vb = new VertexBuffer(engine, boxdata.positions, 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 = Matrix.Scaling(diff.x, diff.y, diff.z)
  40. .multiply(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._scene.resetCachedMaterial();
  48. this._colorShader.setColor4("color", this.backColor.toColor4());
  49. this._colorShader.bind(worldMatrix);
  50. // Draw order
  51. engine.draw(false, 0, 24);
  52. }
  53. // Front
  54. engine.setDepthFunctionToLess();
  55. this._scene.resetCachedMaterial();
  56. this._colorShader.setColor4("color", this.frontColor.toColor4());
  57. this._colorShader.bind(worldMatrix);
  58. // Draw order
  59. engine.draw(false, 0, 24);
  60. }
  61. this._colorShader.unbind();
  62. engine.setDepthFunctionToLessOrEqual();
  63. engine.setDepthWrite(true);
  64. }
  65. public dispose(): void {
  66. this._colorShader.dispose();
  67. this._vb.dispose();
  68. this._scene.getEngine()._releaseBuffer(this._ib);
  69. }
  70. }
  71. }