buffer.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import { Nullable, DataArray } from "../types";
  2. import { ThinEngine } from "../Engines/thinEngine";
  3. import { DataBuffer } from './dataBuffer';
  4. /**
  5. * Class used to store data that will be store in GPU memory
  6. */
  7. export class Buffer {
  8. private _engine: ThinEngine;
  9. private _buffer: Nullable<DataBuffer>;
  10. /** @hidden */
  11. public _data: Nullable<DataArray>;
  12. private _updatable: boolean;
  13. private _instanced: boolean;
  14. private _divisor: number;
  15. private _isAlreadyOwned = false;
  16. /**
  17. * Gets the byte stride.
  18. */
  19. public readonly byteStride: number;
  20. /**
  21. * Constructor
  22. * @param engine the engine
  23. * @param data the data to use for this buffer
  24. * @param updatable whether the data is updatable
  25. * @param stride the stride (optional)
  26. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  27. * @param instanced whether the buffer is instanced (optional)
  28. * @param useBytes set to true if the stride in in bytes (optional)
  29. * @param divisor sets an optional divisor for instances (1 by default)
  30. */
  31. constructor(engine: any, data: DataArray, updatable: boolean, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor?: number) {
  32. if (engine.getScene) { // old versions of VertexBuffer accepted 'mesh' instead of 'engine'
  33. this._engine = engine.getScene().getEngine();
  34. }
  35. else {
  36. this._engine = engine;
  37. }
  38. this._updatable = updatable;
  39. this._instanced = instanced;
  40. this._divisor = divisor || 1;
  41. this._data = data;
  42. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  43. if (!postponeInternalCreation) { // by default
  44. this.create();
  45. }
  46. }
  47. /**
  48. * Create a new VertexBuffer based on the current buffer
  49. * @param kind defines the vertex buffer kind (position, normal, etc.)
  50. * @param offset defines offset in the buffer (0 by default)
  51. * @param size defines the size in floats of attributes (position is 3 for instance)
  52. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  53. * @param instanced defines if the vertex buffer contains indexed data
  54. * @param useBytes defines if the offset and stride are in bytes *
  55. * @param divisor sets an optional divisor for instances (1 by default)
  56. * @returns the new vertex buffer
  57. */
  58. public createVertexBuffer(kind: string, offset: number, size: number, stride?: number, instanced?: boolean, useBytes = false, divisor?: number): VertexBuffer {
  59. const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  60. const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  61. // a lot of these parameters are ignored as they are overriden by the buffer
  62. return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor);
  63. }
  64. // Properties
  65. /**
  66. * Gets a boolean indicating if the Buffer is updatable?
  67. * @returns true if the buffer is updatable
  68. */
  69. public isUpdatable(): boolean {
  70. return this._updatable;
  71. }
  72. /**
  73. * Gets current buffer's data
  74. * @returns a DataArray or null
  75. */
  76. public getData(): Nullable<DataArray> {
  77. return this._data;
  78. }
  79. /**
  80. * Gets underlying native buffer
  81. * @returns underlying native buffer
  82. */
  83. public getBuffer(): Nullable<DataBuffer> {
  84. return this._buffer;
  85. }
  86. /**
  87. * Gets the stride in float32 units (i.e. byte stride / 4).
  88. * May not be an integer if the byte stride is not divisible by 4.
  89. * @returns the stride in float32 units
  90. * @deprecated Please use byteStride instead.
  91. */
  92. public getStrideSize(): number {
  93. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  94. }
  95. // Methods
  96. /**
  97. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  98. * @param data defines the data to store
  99. */
  100. public create(data: Nullable<DataArray> = null): void {
  101. if (!data && this._buffer) {
  102. return; // nothing to do
  103. }
  104. data = data || this._data;
  105. if (!data) {
  106. return;
  107. }
  108. if (!this._buffer) { // create buffer
  109. if (this._updatable) {
  110. this._buffer = this._engine.createDynamicVertexBuffer(data);
  111. this._data = data;
  112. } else {
  113. this._buffer = this._engine.createVertexBuffer(data);
  114. }
  115. } else if (this._updatable) { // update buffer
  116. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  117. this._data = data;
  118. }
  119. }
  120. /** @hidden */
  121. public _rebuild(): void {
  122. this._buffer = null;
  123. this.create(this._data);
  124. }
  125. /**
  126. * Update current buffer data
  127. * @param data defines the data to store
  128. */
  129. public update(data: DataArray): void {
  130. this.create(data);
  131. }
  132. /**
  133. * Updates the data directly.
  134. * @param data the new data
  135. * @param offset the new offset
  136. * @param vertexCount the vertex count (optional)
  137. * @param useBytes set to true if the offset is in bytes
  138. */
  139. public updateDirectly(data: DataArray, offset: number, vertexCount?: number, useBytes: boolean = false): void {
  140. if (!this._buffer) {
  141. return;
  142. }
  143. if (this._updatable) { // update buffer
  144. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  145. this._data = null;
  146. }
  147. }
  148. /** @hidden */
  149. public _increaseReferences() {
  150. if (!this._buffer) {
  151. return;
  152. }
  153. if (!this._isAlreadyOwned) {
  154. this._isAlreadyOwned = true;
  155. return;
  156. }
  157. this._buffer.references++;
  158. }
  159. /**
  160. * Release all resources
  161. */
  162. public dispose(): void {
  163. if (!this._buffer) {
  164. return;
  165. }
  166. if (this._engine._releaseBuffer(this._buffer)) {
  167. this._buffer = null;
  168. }
  169. }
  170. }
  171. /**
  172. * Specialized buffer used to store vertex data
  173. */
  174. export class VertexBuffer {
  175. private static _Counter = 0;
  176. /** @hidden */
  177. public _buffer: Buffer;
  178. private _kind: string;
  179. private _size: number;
  180. private _ownsBuffer: boolean;
  181. private _instanced: boolean;
  182. private _instanceDivisor: number;
  183. /**
  184. * The byte type.
  185. */
  186. public static readonly BYTE = 5120;
  187. /**
  188. * The unsigned byte type.
  189. */
  190. public static readonly UNSIGNED_BYTE = 5121;
  191. /**
  192. * The short type.
  193. */
  194. public static readonly SHORT = 5122;
  195. /**
  196. * The unsigned short type.
  197. */
  198. public static readonly UNSIGNED_SHORT = 5123;
  199. /**
  200. * The integer type.
  201. */
  202. public static readonly INT = 5124;
  203. /**
  204. * The unsigned integer type.
  205. */
  206. public static readonly UNSIGNED_INT = 5125;
  207. /**
  208. * The float type.
  209. */
  210. public static readonly FLOAT = 5126;
  211. /**
  212. * Gets or sets the instance divisor when in instanced mode
  213. */
  214. public get instanceDivisor(): number {
  215. return this._instanceDivisor;
  216. }
  217. public set instanceDivisor(value: number) {
  218. this._instanceDivisor = value;
  219. if (value == 0) {
  220. this._instanced = false;
  221. } else {
  222. this._instanced = true;
  223. }
  224. }
  225. /**
  226. * Gets the byte stride.
  227. */
  228. public readonly byteStride: number;
  229. /**
  230. * Gets the byte offset.
  231. */
  232. public readonly byteOffset: number;
  233. /**
  234. * Gets whether integer data values should be normalized into a certain range when being casted to a float.
  235. */
  236. public readonly normalized: boolean;
  237. /**
  238. * Gets the data type of each component in the array.
  239. */
  240. public readonly type: number;
  241. /**
  242. * Gets the unique id of this vertex buffer
  243. */
  244. public readonly uniqueId: number;
  245. /**
  246. * Constructor
  247. * @param engine the engine
  248. * @param data the data to use for this vertex buffer
  249. * @param kind the vertex buffer kind
  250. * @param updatable whether the data is updatable
  251. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  252. * @param stride the stride (optional)
  253. * @param instanced whether the buffer is instanced (optional)
  254. * @param offset the offset of the data (optional)
  255. * @param size the number of components (optional)
  256. * @param type the type of the component (optional)
  257. * @param normalized whether the data contains normalized data (optional)
  258. * @param useBytes set to true if stride and offset are in bytes (optional)
  259. * @param divisor defines the instance divisor to use (1 by default)
  260. * @param takeBufferOwnership defines if the buffer should be released when the vertex buffer is disposed
  261. */
  262. constructor(engine: any, data: DataArray | Buffer, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number,
  263. instanced?: boolean, offset?: number, size?: number, type?: number, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) {
  264. if (data instanceof Buffer) {
  265. this._buffer = data;
  266. this._ownsBuffer = takeBufferOwnership;
  267. if (takeBufferOwnership) {
  268. this._buffer._increaseReferences();
  269. }
  270. } else {
  271. this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  272. this._ownsBuffer = true;
  273. }
  274. this.uniqueId = VertexBuffer._Counter++;
  275. this._kind = kind;
  276. if (type == undefined) {
  277. const data = this.getData();
  278. this.type = VertexBuffer.FLOAT;
  279. if (data instanceof Int8Array) { this.type = VertexBuffer.BYTE; }
  280. else if (data instanceof Uint8Array) { this.type = VertexBuffer.UNSIGNED_BYTE; }
  281. else if (data instanceof Int16Array) { this.type = VertexBuffer.SHORT; }
  282. else if (data instanceof Uint16Array) { this.type = VertexBuffer.UNSIGNED_SHORT; }
  283. else if (data instanceof Int32Array) { this.type = VertexBuffer.INT; }
  284. else if (data instanceof Uint32Array) { this.type = VertexBuffer.UNSIGNED_INT; }
  285. }
  286. else {
  287. this.type = type;
  288. }
  289. const typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  290. if (useBytes) {
  291. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  292. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  293. this.byteOffset = offset || 0;
  294. }
  295. else {
  296. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  297. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  298. this.byteOffset = (offset || 0) * typeByteLength;
  299. }
  300. this.normalized = normalized;
  301. this._instanced = instanced !== undefined ? instanced : false;
  302. this._instanceDivisor = instanced ? divisor : 0;
  303. }
  304. /** @hidden */
  305. public _rebuild(): void {
  306. if (!this._buffer) {
  307. return;
  308. }
  309. this._buffer._rebuild();
  310. }
  311. /**
  312. * Returns the kind of the VertexBuffer (string)
  313. * @returns a string
  314. */
  315. public getKind(): string {
  316. return this._kind;
  317. }
  318. // Properties
  319. /**
  320. * Gets a boolean indicating if the VertexBuffer is updatable?
  321. * @returns true if the buffer is updatable
  322. */
  323. public isUpdatable(): boolean {
  324. return this._buffer.isUpdatable();
  325. }
  326. /**
  327. * Gets current buffer's data
  328. * @returns a DataArray or null
  329. */
  330. public getData(): Nullable<DataArray> {
  331. return this._buffer.getData();
  332. }
  333. /**
  334. * Gets underlying native buffer
  335. * @returns underlying native buffer
  336. */
  337. public getBuffer(): Nullable<DataBuffer> {
  338. return this._buffer.getBuffer();
  339. }
  340. /**
  341. * Gets the stride in float32 units (i.e. byte stride / 4).
  342. * May not be an integer if the byte stride is not divisible by 4.
  343. * @returns the stride in float32 units
  344. * @deprecated Please use byteStride instead.
  345. */
  346. public getStrideSize(): number {
  347. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  348. }
  349. /**
  350. * Returns the offset as a multiple of the type byte length.
  351. * @returns the offset in bytes
  352. * @deprecated Please use byteOffset instead.
  353. */
  354. public getOffset(): number {
  355. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  356. }
  357. /**
  358. * Returns the number of components per vertex attribute (integer)
  359. * @returns the size in float
  360. */
  361. public getSize(): number {
  362. return this._size;
  363. }
  364. /**
  365. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  366. * @returns true if this buffer is instanced
  367. */
  368. public getIsInstanced(): boolean {
  369. return this._instanced;
  370. }
  371. /**
  372. * Returns the instancing divisor, zero for non-instanced (integer).
  373. * @returns a number
  374. */
  375. public getInstanceDivisor(): number {
  376. return this._instanceDivisor;
  377. }
  378. // Methods
  379. /**
  380. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  381. * @param data defines the data to store
  382. */
  383. public create(data?: DataArray): void {
  384. this._buffer.create(data);
  385. }
  386. /**
  387. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  388. * This function will create a new buffer if the current one is not updatable
  389. * @param data defines the data to store
  390. */
  391. public update(data: DataArray): void {
  392. this._buffer.update(data);
  393. }
  394. /**
  395. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  396. * Returns the directly updated WebGLBuffer.
  397. * @param data the new data
  398. * @param offset the new offset
  399. * @param useBytes set to true if the offset is in bytes
  400. */
  401. public updateDirectly(data: DataArray, offset: number, useBytes: boolean = false): void {
  402. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  403. }
  404. /**
  405. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  406. */
  407. public dispose(): void {
  408. if (this._ownsBuffer) {
  409. this._buffer.dispose();
  410. }
  411. }
  412. /**
  413. * Enumerates each value of this vertex buffer as numbers.
  414. * @param count the number of values to enumerate
  415. * @param callback the callback function called for each value
  416. */
  417. public forEach(count: number, callback: (value: number, index: number) => void): void {
  418. VertexBuffer.ForEach(this._buffer.getData()!, this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  419. }
  420. // Enums
  421. /**
  422. * Positions
  423. */
  424. public static readonly PositionKind = "position";
  425. /**
  426. * Normals
  427. */
  428. public static readonly NormalKind = "normal";
  429. /**
  430. * Tangents
  431. */
  432. public static readonly TangentKind = "tangent";
  433. /**
  434. * Texture coordinates
  435. */
  436. public static readonly UVKind = "uv";
  437. /**
  438. * Texture coordinates 2
  439. */
  440. public static readonly UV2Kind = "uv2";
  441. /**
  442. * Texture coordinates 3
  443. */
  444. public static readonly UV3Kind = "uv3";
  445. /**
  446. * Texture coordinates 4
  447. */
  448. public static readonly UV4Kind = "uv4";
  449. /**
  450. * Texture coordinates 5
  451. */
  452. public static readonly UV5Kind = "uv5";
  453. /**
  454. * Texture coordinates 6
  455. */
  456. public static readonly UV6Kind = "uv6";
  457. /**
  458. * Colors
  459. */
  460. public static readonly ColorKind = "color";
  461. /**
  462. * Matrix indices (for bones)
  463. */
  464. public static readonly MatricesIndicesKind = "matricesIndices";
  465. /**
  466. * Matrix weights (for bones)
  467. */
  468. public static readonly MatricesWeightsKind = "matricesWeights";
  469. /**
  470. * Additional matrix indices (for bones)
  471. */
  472. public static readonly MatricesIndicesExtraKind = "matricesIndicesExtra";
  473. /**
  474. * Additional matrix weights (for bones)
  475. */
  476. public static readonly MatricesWeightsExtraKind = "matricesWeightsExtra";
  477. /**
  478. * Deduces the stride given a kind.
  479. * @param kind The kind string to deduce
  480. * @returns The deduced stride
  481. */
  482. public static DeduceStride(kind: string): number {
  483. switch (kind) {
  484. case VertexBuffer.UVKind:
  485. case VertexBuffer.UV2Kind:
  486. case VertexBuffer.UV3Kind:
  487. case VertexBuffer.UV4Kind:
  488. case VertexBuffer.UV5Kind:
  489. case VertexBuffer.UV6Kind:
  490. return 2;
  491. case VertexBuffer.NormalKind:
  492. case VertexBuffer.PositionKind:
  493. return 3;
  494. case VertexBuffer.ColorKind:
  495. case VertexBuffer.MatricesIndicesKind:
  496. case VertexBuffer.MatricesIndicesExtraKind:
  497. case VertexBuffer.MatricesWeightsKind:
  498. case VertexBuffer.MatricesWeightsExtraKind:
  499. case VertexBuffer.TangentKind:
  500. return 4;
  501. default:
  502. throw new Error("Invalid kind '" + kind + "'");
  503. }
  504. }
  505. /**
  506. * Gets the byte length of the given type.
  507. * @param type the type
  508. * @returns the number of bytes
  509. */
  510. public static GetTypeByteLength(type: number): number {
  511. switch (type) {
  512. case VertexBuffer.BYTE:
  513. case VertexBuffer.UNSIGNED_BYTE:
  514. return 1;
  515. case VertexBuffer.SHORT:
  516. case VertexBuffer.UNSIGNED_SHORT:
  517. return 2;
  518. case VertexBuffer.INT:
  519. case VertexBuffer.UNSIGNED_INT:
  520. case VertexBuffer.FLOAT:
  521. return 4;
  522. default:
  523. throw new Error(`Invalid type '${type}'`);
  524. }
  525. }
  526. /**
  527. * Enumerates each value of the given parameters as numbers.
  528. * @param data the data to enumerate
  529. * @param byteOffset the byte offset of the data
  530. * @param byteStride the byte stride of the data
  531. * @param componentCount the number of components per element
  532. * @param componentType the type of the component
  533. * @param count the number of values to enumerate
  534. * @param normalized whether the data is normalized
  535. * @param callback the callback function called for each value
  536. */
  537. public static ForEach(data: DataArray, byteOffset: number, byteStride: number, componentCount: number, componentType: number, count: number, normalized: boolean, callback: (value: number, index: number) => void): void {
  538. if (data instanceof Array) {
  539. let offset = byteOffset / 4;
  540. const stride = byteStride / 4;
  541. for (let index = 0; index < count; index += componentCount) {
  542. for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  543. callback(data[offset + componentIndex], index + componentIndex);
  544. }
  545. offset += stride;
  546. }
  547. }
  548. else {
  549. const dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  550. const componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  551. for (let index = 0; index < count; index += componentCount) {
  552. let componentByteOffset = byteOffset;
  553. for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  554. const value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  555. callback(value, index + componentIndex);
  556. componentByteOffset += componentByteLength;
  557. }
  558. byteOffset += byteStride;
  559. }
  560. }
  561. }
  562. private static _GetFloatValue(dataView: DataView, type: number, byteOffset: number, normalized: boolean): number {
  563. switch (type) {
  564. case VertexBuffer.BYTE: {
  565. let value = dataView.getInt8(byteOffset);
  566. if (normalized) {
  567. value = Math.max(value / 127, -1);
  568. }
  569. return value;
  570. }
  571. case VertexBuffer.UNSIGNED_BYTE: {
  572. let value = dataView.getUint8(byteOffset);
  573. if (normalized) {
  574. value = value / 255;
  575. }
  576. return value;
  577. }
  578. case VertexBuffer.SHORT: {
  579. let value = dataView.getInt16(byteOffset, true);
  580. if (normalized) {
  581. value = Math.max(value / 32767, -1);
  582. }
  583. return value;
  584. }
  585. case VertexBuffer.UNSIGNED_SHORT: {
  586. let value = dataView.getUint16(byteOffset, true);
  587. if (normalized) {
  588. value = value / 65535;
  589. }
  590. return value;
  591. }
  592. case VertexBuffer.INT: {
  593. return dataView.getInt32(byteOffset, true);
  594. }
  595. case VertexBuffer.UNSIGNED_INT: {
  596. return dataView.getUint32(byteOffset, true);
  597. }
  598. case VertexBuffer.FLOAT: {
  599. return dataView.getFloat32(byteOffset, true);
  600. }
  601. default: {
  602. throw new Error(`Invalid component type ${type}`);
  603. }
  604. }
  605. }
  606. }