LiteTranscoder.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Nullable } from '../../types';
  2. import { Tools } from '../tools';
  3. import { Transcoder, sourceTextureFormat, transcodeTarget } from './transcoder';
  4. import { WASMMemoryManager } from './wasmMemoryManager';
  5. import { KTX2FileReader, IKTX2_ImageDesc } from './KTX2FileReader';
  6. /**
  7. * @hidden
  8. */
  9. export class LiteTranscoder extends Transcoder {
  10. private _modulePath: string;
  11. private _modulePromise: Promise<{ module: any }>;
  12. private _memoryManager: WASMMemoryManager;
  13. protected async _loadModule(): Promise<{ module: any }> {
  14. if (this._modulePromise) {
  15. return this._modulePromise;
  16. }
  17. this._modulePromise = new Promise((resolve) => {
  18. Tools.LoadFileAsync(this._modulePath).then((wasmBinary: string | ArrayBuffer) => {
  19. WebAssembly.instantiate(wasmBinary as ArrayBuffer, { env: { memory: this._memoryManager.wasmMemory } }).then((moduleWrapper) => {
  20. resolve({ module: moduleWrapper.instance.exports });
  21. });
  22. });
  23. });
  24. return this._modulePromise;
  25. }
  26. protected get memoryManager(): WASMMemoryManager {
  27. return this._memoryManager;
  28. }
  29. protected setModulePath(modulePath: string): void {
  30. this._modulePath = modulePath;
  31. }
  32. public needMemoryManager(): boolean {
  33. return true;
  34. }
  35. public setMemoryManager(memoryMgr: WASMMemoryManager): void {
  36. this._memoryManager = memoryMgr;
  37. }
  38. public transcode(src: sourceTextureFormat, dst: transcodeTarget, level: number, width: number, height: number, uncompressedByteLength: number, ktx2Reader: KTX2FileReader, imageDesc: Nullable<IKTX2_ImageDesc>, encodedData: Uint8Array): Promise<Nullable<Uint8Array>> {
  39. return this._loadModule().then((moduleWrapper: any) => {
  40. const transcoder: any = moduleWrapper.module;
  41. const nBlocks = ((width + 3) >> 2) * ((height + 3) >> 2);
  42. const texMemoryPages = ((nBlocks * 16 + 65535) >> 16) + 1;
  43. const textureView = this.memoryManager.getMemoryView(texMemoryPages, 65536, nBlocks * 16);
  44. textureView.set(encodedData);
  45. return transcoder.transcode(nBlocks) === 0 ? textureView.slice() : null;
  46. });
  47. }
  48. }