DynamicPrimitive.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package h3d.prim;
  2. class DynamicPrimitive extends Primitive {
  3. var vbuf : hxd.FloatBuffer;
  4. var ibuf : hxd.IndexBuffer;
  5. var vsize : Int;
  6. var isize : Int;
  7. var format : hxd.BufferFormat;
  8. /** Minimum number of elements in vertex buffer **/
  9. public var minVSize = 0;
  10. /** Minimum number of elements in index index buffer **/
  11. public var minISize = 0;
  12. public var bounds = new h3d.col.Bounds();
  13. public function new( format ) {
  14. this.format = format;
  15. }
  16. override function getBounds() {
  17. return bounds;
  18. }
  19. public function getBuffer( vertices : Int ) {
  20. if( vbuf == null ) vbuf = hxd.impl.Allocator.get().allocFloats(vertices * format.stride) else vbuf.grow(vertices * format.stride);
  21. vsize = vertices;
  22. return vbuf;
  23. }
  24. public function getIndexes( count : Int ) {
  25. if( ibuf == null ) ibuf = hxd.impl.Allocator.get().allocIndexes(count) else ibuf.grow(count);
  26. isize = count;
  27. return ibuf;
  28. }
  29. public function flush() {
  30. var alloc = hxd.impl.Allocator.get();
  31. if( vsize == 0 || isize == 0 ) {
  32. if( buffer != null ) {
  33. alloc.disposeBuffer(buffer);
  34. buffer = null;
  35. }
  36. if( indexes != null ) {
  37. alloc.disposeIndexBuffer(indexes);
  38. indexes = null;
  39. }
  40. return;
  41. }
  42. if( buffer != null && (buffer.isDisposed() || buffer.vertices < vsize) ) {
  43. alloc.disposeBuffer(buffer);
  44. buffer = null;
  45. }
  46. if( indexes != null && (indexes.isDisposed() || indexes.count < isize) ) {
  47. alloc.disposeIndexBuffer(indexes);
  48. indexes = null;
  49. }
  50. if( buffer == null )
  51. buffer = alloc.allocBuffer(hxd.Math.imax(minVSize, vsize), format, Dynamic);
  52. if( indexes == null )
  53. indexes = alloc.allocIndexBuffer(hxd.Math.imax(minISize, isize));
  54. buffer.uploadFloats(vbuf, 0, vsize);
  55. indexes.uploadIndexes(ibuf, 0, isize);
  56. }
  57. override function dispose() {
  58. var alloc = hxd.impl.Allocator.get();
  59. if( buffer != null ) {
  60. alloc.disposeBuffer(buffer);
  61. buffer = null;
  62. }
  63. if( vbuf != null ) {
  64. alloc.disposeFloats(vbuf);
  65. vbuf = null;
  66. }
  67. if( ibuf != null ) {
  68. alloc.disposeIndexes(ibuf);
  69. ibuf = null;
  70. }
  71. super.dispose();
  72. }
  73. override function triCount() {
  74. return Std.int(isize / 3);
  75. }
  76. override public function render(engine:h3d.Engine) {
  77. if( buffer != null ) engine.renderIndexed(buffer, indexes, 0, triCount());
  78. }
  79. }