dracoCompression.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import { Tools } from "../../Misc/tools";
  2. import { WorkerPool } from '../../Misc/workerPool';
  3. import { Nullable } from "../../types";
  4. import { IDisposable } from "../../scene";
  5. import { VertexData } from "../../Meshes/mesh.vertexData";
  6. declare var DracoDecoderModule: any;
  7. declare var WebAssembly: any;
  8. // WorkerGlobalScope
  9. declare function importScripts(...urls: string[]): void;
  10. declare function postMessage(message: any, transfer?: any[]): void;
  11. function createDecoderAsync(wasmBinary?: ArrayBuffer): Promise<any> {
  12. return new Promise((resolve) => {
  13. DracoDecoderModule({ wasmBinary: wasmBinary }).then((module: any) => {
  14. resolve({ module: module });
  15. });
  16. });
  17. }
  18. function decodeMesh(decoderModule: any, dataView: ArrayBufferView, attributes: { [kind: string]: number } | undefined, onIndicesData: (data: Uint32Array) => void, onAttributeData: (kind: string, data: Float32Array) => void): void {
  19. const buffer = new decoderModule.DecoderBuffer();
  20. buffer.Init(dataView, dataView.byteLength);
  21. const decoder = new decoderModule.Decoder();
  22. let geometry: any;
  23. let status: any;
  24. try {
  25. const type = decoder.GetEncodedGeometryType(buffer);
  26. switch (type) {
  27. case decoderModule.TRIANGULAR_MESH:
  28. geometry = new decoderModule.Mesh();
  29. status = decoder.DecodeBufferToMesh(buffer, geometry);
  30. break;
  31. case decoderModule.POINT_CLOUD:
  32. geometry = new decoderModule.PointCloud();
  33. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  34. break;
  35. default:
  36. throw new Error(`Invalid geometry type ${type}`);
  37. }
  38. if (!status.ok() || !geometry.ptr) {
  39. throw new Error(status.error_msg());
  40. }
  41. if (type === decoderModule.TRIANGULAR_MESH) {
  42. const numFaces = geometry.num_faces();
  43. const numIndices = numFaces * 3;
  44. const byteLength = numIndices * 4;
  45. const ptr = decoderModule._malloc(byteLength);
  46. try {
  47. decoder.GetTrianglesUInt32Array(geometry, byteLength, ptr);
  48. const indices = new Uint32Array(numIndices);
  49. indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices));
  50. onIndicesData(indices);
  51. }
  52. finally {
  53. decoderModule._free(ptr);
  54. }
  55. }
  56. const processAttribute = (kind: string, attribute: any) => {
  57. var numComponents = attribute.num_components();
  58. var numPoints = geometry.num_points();
  59. var numValues = numPoints * numComponents;
  60. var byteLength = numValues * Float32Array.BYTES_PER_ELEMENT;
  61. var ptr = decoderModule._malloc(byteLength);
  62. try {
  63. decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, decoderModule.DT_FLOAT32, byteLength, ptr);
  64. const values = new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues);
  65. if (kind === "color" && numComponents === 3) {
  66. const babylonData = new Float32Array(numPoints * 4);
  67. for (let i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) {
  68. babylonData[i + 0] = values[j + 0];
  69. babylonData[i + 1] = values[j + 1];
  70. babylonData[i + 2] = values[j + 2];
  71. babylonData[i + 3] = 1;
  72. }
  73. onAttributeData(kind, babylonData);
  74. }
  75. else {
  76. const babylonData = new Float32Array(numValues);
  77. babylonData.set(new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues));
  78. onAttributeData(kind, babylonData);
  79. }
  80. }
  81. finally {
  82. decoderModule._free(ptr);
  83. }
  84. };
  85. if (attributes) {
  86. for (const kind in attributes) {
  87. const id = attributes[kind];
  88. const attribute = decoder.GetAttributeByUniqueId(geometry, id);
  89. processAttribute(kind, attribute);
  90. }
  91. }
  92. else {
  93. const nativeAttributeTypes: { [kind: string]: string } = {
  94. "position": "POSITION",
  95. "normal": "NORMAL",
  96. "color": "COLOR",
  97. "uv": "TEX_COORD"
  98. };
  99. for (const kind in nativeAttributeTypes) {
  100. const id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]);
  101. if (id !== -1) {
  102. const attribute = decoder.GetAttribute(geometry, id);
  103. processAttribute(kind, attribute);
  104. }
  105. }
  106. }
  107. }
  108. finally {
  109. if (geometry) {
  110. decoderModule.destroy(geometry);
  111. }
  112. decoderModule.destroy(decoder);
  113. decoderModule.destroy(buffer);
  114. }
  115. }
  116. /**
  117. * The worker function that gets converted to a blob url to pass into a worker.
  118. */
  119. function worker(): void {
  120. let decoderPromise: PromiseLike<any> | undefined;
  121. onmessage = (event) => {
  122. const data = event.data;
  123. switch (data.id) {
  124. case "init": {
  125. const decoder = data.decoder;
  126. if (decoder.url) {
  127. importScripts(decoder.url);
  128. decoderPromise = DracoDecoderModule({ wasmBinary: decoder.wasmBinary });
  129. }
  130. postMessage("done");
  131. break;
  132. }
  133. case "decodeMesh": {
  134. if (!decoderPromise) {
  135. throw new Error("Draco decoder module is not available");
  136. }
  137. decoderPromise.then((decoder) => {
  138. decodeMesh(decoder, data.dataView, data.attributes, (indices) => {
  139. postMessage({ id: "indices", value: indices }, [indices.buffer]);
  140. }, (kind, data) => {
  141. postMessage({ id: kind, value: data }, [data.buffer]);
  142. });
  143. postMessage("done");
  144. });
  145. break;
  146. }
  147. }
  148. };
  149. }
  150. function getAbsoluteUrl<T>(url: T): T | string {
  151. if (typeof document !== "object" || typeof url !== "string") {
  152. return url;
  153. }
  154. return Tools.GetAbsoluteUrl(url);
  155. }
  156. /**
  157. * Configuration for Draco compression
  158. */
  159. export interface IDracoCompressionConfiguration {
  160. /**
  161. * Configuration for the decoder.
  162. */
  163. decoder: {
  164. /**
  165. * The url to the WebAssembly module.
  166. */
  167. wasmUrl?: string;
  168. /**
  169. * The url to the WebAssembly binary.
  170. */
  171. wasmBinaryUrl?: string;
  172. /**
  173. * The url to the fallback JavaScript module.
  174. */
  175. fallbackUrl?: string;
  176. };
  177. }
  178. /**
  179. * Draco compression (https://google.github.io/draco/)
  180. *
  181. * This class wraps the Draco module.
  182. *
  183. * **Encoder**
  184. *
  185. * The encoder is not currently implemented.
  186. *
  187. * **Decoder**
  188. *
  189. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  190. *
  191. * To update the configuration, use the following code:
  192. * ```javascript
  193. * DracoCompression.Configuration = {
  194. * decoder: {
  195. * wasmUrl: "<url to the WebAssembly library>",
  196. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  197. * fallbackUrl: "<url to the fallback JavaScript library>",
  198. * }
  199. * };
  200. * ```
  201. *
  202. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  203. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  204. * Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context.
  205. *
  206. * To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync:
  207. * ```javascript
  208. * var vertexData = await DracoCompression.Default.decodeMeshAsync(data);
  209. * ```
  210. *
  211. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  212. */
  213. export class DracoCompression implements IDisposable {
  214. private _workerPoolPromise?: Promise<WorkerPool>;
  215. private _decoderModulePromise?: Promise<any>;
  216. /**
  217. * The configuration. Defaults to the following urls:
  218. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  219. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  220. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  221. */
  222. public static Configuration: IDracoCompressionConfiguration = {
  223. decoder: {
  224. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  225. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  226. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  227. }
  228. };
  229. /**
  230. * Returns true if the decoder configuration is available.
  231. */
  232. public static get DecoderAvailable(): boolean {
  233. const decoder = DracoCompression.Configuration.decoder;
  234. return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") || decoder.fallbackUrl);
  235. }
  236. /**
  237. * Default number of workers to create when creating the draco compression object.
  238. */
  239. public static DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers();
  240. private static GetDefaultNumWorkers(): number {
  241. if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
  242. return 1;
  243. }
  244. // Use 50% of the available logical processors but capped at 4.
  245. return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
  246. }
  247. private static _Default: Nullable<DracoCompression> = null;
  248. /**
  249. * Default instance for the draco compression object.
  250. */
  251. public static get Default(): DracoCompression {
  252. if (!DracoCompression._Default) {
  253. DracoCompression._Default = new DracoCompression();
  254. }
  255. return DracoCompression._Default;
  256. }
  257. /**
  258. * Constructor
  259. * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.
  260. */
  261. constructor(numWorkers = DracoCompression.DefaultNumWorkers) {
  262. const decoder = DracoCompression.Configuration.decoder;
  263. const decoderInfo: { url: string | undefined, wasmBinaryPromise: Promise<ArrayBuffer | string | undefined> } =
  264. (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") ? {
  265. url: decoder.wasmUrl,
  266. wasmBinaryPromise: Tools.LoadFileAsync(getAbsoluteUrl(decoder.wasmBinaryUrl))
  267. } : {
  268. url: decoder.fallbackUrl,
  269. wasmBinaryPromise: Promise.resolve(undefined)
  270. };
  271. if (numWorkers && typeof Worker === "function") {
  272. this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {
  273. const workerContent = `${decodeMesh}(${worker})()`;
  274. const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
  275. const workerPromises = new Array<Promise<Worker>>(numWorkers);
  276. for (let i = 0; i < workerPromises.length; i++) {
  277. workerPromises[i] = new Promise((resolve, reject) => {
  278. const worker = new Worker(workerBlobUrl);
  279. const onError = (error: ErrorEvent) => {
  280. worker.removeEventListener("error", onError);
  281. worker.removeEventListener("message", onMessage);
  282. reject(error);
  283. };
  284. const onMessage = (message: MessageEvent) => {
  285. if (message.data === "done") {
  286. worker.removeEventListener("error", onError);
  287. worker.removeEventListener("message", onMessage);
  288. resolve(worker);
  289. }
  290. };
  291. worker.addEventListener("error", onError);
  292. worker.addEventListener("message", onMessage);
  293. worker.postMessage({
  294. id: "init",
  295. decoder: {
  296. url: getAbsoluteUrl(decoderInfo.url),
  297. wasmBinary: decoderWasmBinary,
  298. }
  299. });
  300. });
  301. }
  302. return Promise.all(workerPromises).then((workers) => {
  303. return new WorkerPool(workers);
  304. });
  305. });
  306. }
  307. else {
  308. this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {
  309. if (!decoderInfo.url) {
  310. throw new Error("Draco decoder module is not available");
  311. }
  312. return Tools.LoadScriptAsync(decoderInfo.url).then(() => {
  313. return createDecoderAsync(decoderWasmBinary as ArrayBuffer);
  314. });
  315. });
  316. }
  317. }
  318. /**
  319. * Stop all async operations and release resources.
  320. */
  321. public dispose(): void {
  322. if (this._workerPoolPromise) {
  323. this._workerPoolPromise.then((workerPool) => {
  324. workerPool.dispose();
  325. });
  326. }
  327. delete this._workerPoolPromise;
  328. delete this._decoderModulePromise;
  329. }
  330. /**
  331. * Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use.
  332. * @returns a promise that resolves when ready
  333. */
  334. public whenReadyAsync(): Promise<void> {
  335. if (this._workerPoolPromise) {
  336. return this._workerPoolPromise.then(() => { });
  337. }
  338. if (this._decoderModulePromise) {
  339. return this._decoderModulePromise.then(() => { });
  340. }
  341. return Promise.resolve();
  342. }
  343. /**
  344. * Decode Draco compressed mesh data to vertex data.
  345. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  346. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  347. * @returns A promise that resolves with the decoded vertex data
  348. */
  349. public decodeMeshAsync(data: ArrayBuffer | ArrayBufferView, attributes?: { [kind: string]: number }): Promise<VertexData> {
  350. const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  351. if (this._workerPoolPromise) {
  352. return this._workerPoolPromise.then((workerPool) => {
  353. return new Promise<VertexData>((resolve, reject) => {
  354. workerPool.push((worker, onComplete) => {
  355. const vertexData = new VertexData();
  356. const onError = (error: ErrorEvent) => {
  357. worker.removeEventListener("error", onError);
  358. worker.removeEventListener("message", onMessage);
  359. reject(error);
  360. onComplete();
  361. };
  362. const onMessage = (message: MessageEvent) => {
  363. if (message.data === "done") {
  364. worker.removeEventListener("error", onError);
  365. worker.removeEventListener("message", onMessage);
  366. resolve(vertexData);
  367. onComplete();
  368. }
  369. else if (message.data.id === "indices") {
  370. vertexData.indices = message.data.value;
  371. }
  372. else {
  373. vertexData.set(message.data.value, message.data.id);
  374. }
  375. };
  376. worker.addEventListener("error", onError);
  377. worker.addEventListener("message", onMessage);
  378. const dataViewCopy = new Uint8Array(dataView.byteLength);
  379. dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));
  380. worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]);
  381. });
  382. });
  383. });
  384. }
  385. if (this._decoderModulePromise) {
  386. return this._decoderModulePromise.then((decoder) => {
  387. const vertexData = new VertexData();
  388. decodeMesh(decoder.module, dataView, attributes, (indices) => {
  389. vertexData.indices = indices;
  390. }, (kind, data) => {
  391. vertexData.set(data, kind);
  392. });
  393. return vertexData;
  394. });
  395. }
  396. throw new Error("Draco decoder module is not available");
  397. }
  398. }