babylon.dynamicFloatArray.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. module BABYLON {
  2. export class DynamicFloatArrayElementInfo {
  3. offset: number;
  4. }
  5. /**
  6. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  7. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  8. * It was first built to effiently maintain the WebGlBuffer that contain instancing based data.
  9. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  10. * Beware, calling pack() may change the offset of some Entries because this method will defrag the Float32Array to replace empty elements by moving allocated ones at their location.
  11. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there're no "free holes".
  12. */
  13. export class DynamicFloatArray {
  14. /**
  15. * Construct an instance of the dynamic float array
  16. * @param stride size of one element in float (i.e. not bytes!)
  17. * @param initialElementCount the number of available entries at construction
  18. */
  19. constructor(stride: number, initialElementCount: number) {
  20. this._stride = stride;
  21. this.buffer = new Float32Array(stride * initialElementCount);
  22. this._lastUsed = 0;
  23. this._firstFree = 0;
  24. this._allEntries = new Array<DynamicFloatArrayElementInfo>(initialElementCount);
  25. this._freeEntries = new Array<DynamicFloatArrayElementInfo>(initialElementCount);
  26. for (let i = 0; i < initialElementCount; i++) {
  27. let element = new DynamicFloatArrayElementInfo();
  28. element.offset = i * stride;
  29. this._allEntries[i] = element;
  30. this._freeEntries[initialElementCount - i - 1] = element;
  31. }
  32. }
  33. /**
  34. * Allocate an element in the array.
  35. * @return the element info instance that contains the offset into the main buffer of the element's location.
  36. * Beware, this offset may change when you call pack()
  37. */
  38. allocElement(): DynamicFloatArrayElementInfo {
  39. if (this._freeEntries.length === 0) {
  40. this._growBuffer();
  41. }
  42. let el = this._freeEntries.pop();
  43. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44. if (el.offset === this._firstFree) {
  45. if (this._freeEntries.length > 0) {
  46. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  47. } else {
  48. this._firstFree += this._stride;
  49. }
  50. }
  51. return el;
  52. }
  53. /**
  54. * Free the element corresponding to the given element info
  55. * @param elInfo the element that describe the allocated element
  56. */
  57. freeElement(elInfo: DynamicFloatArrayElementInfo) {
  58. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  59. this._freeEntries.push(elInfo);
  60. }
  61. /**
  62. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  63. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  64. * @return the subarray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  65. */
  66. pack(): Float32Array {
  67. // no free slot? no need to pack
  68. if (this._freeEntries.length === 0) {
  69. return this.buffer;
  70. }
  71. // If the buffer is already packed the last used will always be lower than the first free
  72. if (this._lastUsed < this._firstFree) {
  73. let elementsBuffer = this.buffer.subarray(0, this._lastUsed + this._stride);
  74. return elementsBuffer;
  75. }
  76. let s = this._stride;
  77. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  78. let lastFree = new DynamicFloatArrayElementInfo();
  79. lastFree.offset = this.totalElementCount * s;
  80. this._freeEntries.push(lastFree);
  81. let sortedFree = this._freeEntries.sort((a, b) => a.offset - b.offset);
  82. let sortedAll = this._allEntries.sort((a, b) => a.offset - b.offset);
  83. let firstFreeSlotOffset = sortedFree[0].offset;
  84. let freeZoneSize = 1;
  85. // The sortedFree array is sorted in reverse, first free at the end, last free at the beginning, so we loop from the end to beginning
  86. let prevOffset = sortedFree[0].offset;
  87. for (let i = 1; i < sortedFree.length; i++) {
  88. let curFree = sortedFree[i];
  89. let curOffset = curFree.offset;
  90. // Compute the distance between this offset and the previous
  91. let distance = curOffset - prevOffset;
  92. // If the distance is the stride size, they are adjacents, it good, move to the next
  93. if (distance === s) {
  94. // Free zone is one element bigger
  95. ++freeZoneSize;
  96. // as we're about to iterate to the next, the cur becomes the prev...
  97. prevOffset = curOffset;
  98. continue;
  99. }
  100. // Distance is bigger, which means there's x element between the previous free and this one
  101. let usedRange = (distance / s) - 1;
  102. // Two cases the free zone is smaller than the data to move or bigger
  103. // Copy what can fit in the free zone
  104. let curMoveOffset = curOffset - s;
  105. let copyCount = Math.min(freeZoneSize, usedRange);
  106. for (let j = 0; j < copyCount; j++) {
  107. let freeI = firstFreeSlotOffset / s;
  108. let curI = curMoveOffset / s;
  109. let moveEl = sortedAll[curI];
  110. this._moveElement(moveEl, firstFreeSlotOffset);
  111. let replacedEl = sortedAll[freeI];
  112. // set the offset of the element element we replace with a value that will make it discard at the end of the method
  113. replacedEl.offset = curMoveOffset;
  114. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  115. sortedAll[freeI] = moveEl;
  116. sortedAll[curI] = replacedEl;
  117. curMoveOffset -= s;
  118. firstFreeSlotOffset += s;
  119. }
  120. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  121. if (freeZoneSize <= usedRange) {
  122. firstFreeSlotOffset = curOffset;
  123. freeZoneSize = 1;
  124. }
  125. // Free Zone was bigger, the firstFreeSlotOffset is already up to date, but we need to update the its size
  126. else {
  127. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  128. }
  129. // as we're about to iterate to the next, the cur becomes the prev...
  130. prevOffset = curOffset;
  131. }
  132. let elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  133. this._lastUsed = firstFreeSlotOffset - s;
  134. this._firstFree = firstFreeSlotOffset;
  135. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  136. this._freeEntries = sortedFree.sort((a, b) => b.offset - a.offset);
  137. this._allEntries = sortedAll;
  138. return elementsBuffer;
  139. }
  140. private _moveElement(element: DynamicFloatArrayElementInfo, destOffset: number) {
  141. for (let i = 0; i < this._stride; i++) {
  142. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  143. }
  144. element.offset = destOffset;
  145. }
  146. private _growBuffer() {
  147. // Allocate the new buffer with 50% more entries, copy the content of the current one
  148. let newElCount = this.totalElementCount * 1.5;
  149. let newBuffer = new Float32Array(newElCount * this._stride);
  150. newBuffer.set(this.buffer);
  151. let addedCount = newElCount - this.totalElementCount;
  152. this._allEntries.length += addedCount;
  153. this._freeEntries.length += addedCount;
  154. for (let i = this.totalElementCount; i < newElCount; i++) {
  155. let el = new DynamicFloatArrayElementInfo();
  156. el.offset = i * this._stride;
  157. this._allEntries[i] = el;
  158. this._freeEntries[i] = el;
  159. }
  160. this.buffer = newBuffer;
  161. this.totalElementCount = newElCount;
  162. }
  163. /**
  164. * This is the main buffer, all elements are stored inside, you use the DynamicFloatArrayElement instance of a given element to know its location into this buffer, then you have the responsability to perform write operations in this buffer at the right location!
  165. * Don't use this buffer for a WebGL bufferSubData() operation, but use the one returned by the pack() method.
  166. */
  167. buffer: Float32Array;
  168. /**
  169. * Get the total count of entries that can fit in the current buffer
  170. * @returns the elements count
  171. */
  172. get totalElementCount(): number {
  173. return this._allEntries.length;
  174. }
  175. /**
  176. * Get the count of free entries that can still be allocated without resizing the buffer
  177. * @returns the free elements count
  178. */
  179. get freeElementCount(): number {
  180. return this._freeEntries.length;
  181. }
  182. /**
  183. * Get the count of allocated elements
  184. * @returns the allocated elements count
  185. */
  186. get usedElementCount(): number {
  187. return this._allEntries.length - this._freeEntries.length;
  188. }
  189. /**
  190. * Return the size of one element in float
  191. * @returns the size in float
  192. */
  193. get stride(): number {
  194. return this._stride;
  195. }
  196. private _allEntries: Array<DynamicFloatArrayElementInfo>;
  197. private _freeEntries: Array<DynamicFloatArrayElementInfo>;
  198. private _stride: number;
  199. private _lastUsed: number;
  200. private _firstFree: number;
  201. }
  202. }