Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@loaders.gl/draco

Package Overview
Dependencies
Maintainers
9
Versions
339
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@loaders.gl/draco - npm Package Compare versions

Comparing version 4.0.2 to 4.0.3

2

dist/dist.dev.js

@@ -559,3 +559,3 @@ (function webpackUniversalModuleDefinition(root, factory) {

// ../worker-utils/src/lib/env-utils/version.ts
var NPM_TAG = "beta";
var NPM_TAG = "latest";
function getVersion() {

@@ -562,0 +562,0 @@ if (!globalThis._loadersgl_?.version) {

@@ -1,2 +0,1054 @@

"use strict";(()=>{var Y=Object.create;var R=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ee=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of J(e))!K.call(t,a)&&a!==r&&R(t,a,{get:()=>e[a],enumerable:!(o=X(e,a))||o.enumerable});return t};var te=(t,e,r)=>(r=t!=null?Y(H(t)):{},ee(e||!t||!t.__esModule?R(r,"default",{value:t,enumerable:!0}):r,t));var k=Z(()=>{"use strict"});function re(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.0.2"),globalThis._loadersgl_.version}var S=re();function F(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}var y={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},Oe=y.self||y.window||y.global||{},Ee=y.window||y.self||y.global||{},Le=y.global||y.self||y.window||{},Ie=y.document||{};var A=typeof process!="object"||String(process)!=="[object process]"||process.browser,_=typeof importScripts=="function",Pe=typeof window<"u"&&typeof window.orientation<"u",C=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),Re=C&&parseFloat(C[1])||0;function x(t,e=!0,r){let o=r||new Set;if(t){if(B(t))o.add(t);else if(B(t.buffer))o.add(t.buffer);else if(!ArrayBuffer.isView(t)){if(e&&typeof t=="object")for(let a in t)x(t[a],e,o)}}return r===void 0?Array.from(o):[]}function B(t){return t?t instanceof ArrayBuffer||typeof MessagePort<"u"&&t instanceof MessagePort||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas:!1}async function g(){let parentPort;try{eval("globalThis.parentPort = require('worker_threads').parentPort"),parentPort=globalThis.parentPort}catch{try{eval("globalThis.workerThreadsPromise = import('worker_threads')");let workerThreads=await globalThis.workerThreadsPromise;parentPort=workerThreads.parentPort}catch(t){console.error(t.message)}}return parentPort}var M=new Map,l=class{static async inWorkerThread(){return typeof self<"u"||Boolean(await g())}static set onmessage(e){async function r(o){let a=await g(),{type:n,payload:s}=a?o:o.data;e(n,s)}g().then(o=>{o?(o.on("message",r),o.on("exit",()=>console.debug("Node worker closing"))):globalThis.onmessage=r})}static async addEventListener(e){let r=M.get(e);r||(r=async a=>{if(!oe(a))return;let n=await g(),{type:s,payload:i}=n?a:a.data;e(s,i)}),await g()?console.error("not implemented"):globalThis.addEventListener("message",r)}static async removeEventListener(e){let r=M.get(e);M.delete(e),await g()?console.error("not implemented"):globalThis.removeEventListener("message",r)}static async postMessage(e,r){let o={source:"loaders.gl",type:e,payload:r},a=x(r),n=await g();n?n.postMessage(o,a):globalThis.postMessage(o,a)}};function oe(t){let{type:e,data:r}=t;return e==="message"&&r&&typeof r.source=="string"&&r.source.startsWith("loaders.gl")}var p=te(k(),1);var w={};async function b(t,e=null,r={},o=null){return e&&(t=N(t,e,r,o)),w[t]=w[t]||ae(t),await w[t]}function N(t,e,r={},o=null){if(!r.useLocalLibraries&&t.startsWith("http"))return t;o=o||t;let a=r.modules||{};return a[o]?a[o]:A?r.CDN?(F(r.CDN.startsWith("http")),`${r.CDN}/${e}@${S}/dist/libs/${o}`):_?`../src/libs/${o}`:`modules/${e}/src/libs/${o}`:`modules/${e}/dist/libs/${o}`}async function ae(t){if(t.endsWith("wasm"))return await se(t);if(!A)try{return p&&void 0&&await(void 0)(t)}catch(r){return console.error(r),null}if(_)return importScripts(t);let e=await ie(t);return ne(e,t)}function ne(t,e){if(!A)return void 0&&(void 0)(t,e);if(_)return eval.call(globalThis,t),null;let r=document.createElement("script");r.id=e;try{r.appendChild(document.createTextNode(t))}catch{r.text=t}return document.body.appendChild(r),null}async function se(t){return A||!void 0||t.startsWith("http")?await(await fetch(t)).arrayBuffer():await(void 0)(t)}async function ie(t){return A||!void 0||t.startsWith("http")?await(await fetch(t)).text():await(void 0)(t)}var ce=0;async function O(t){await l.inWorkerThread()&&(l.onmessage=async(e,r)=>{switch(e){case"process":try{let{input:o,options:a={},context:n={}}=r,s=await ue({loader:t,arrayBuffer:o,options:a,context:{...n,_parse:de}});l.postMessage("done",{result:s})}catch(o){let a=o instanceof Error?o.message:"";l.postMessage("error",{error:a})}break;default:}})}function de(t,e,r,o){return new Promise((a,n)=>{let s=ce++,i=(f,d)=>{if(d.id===s)switch(f){case"done":l.removeEventListener(i),a(d.result);break;case"error":l.removeEventListener(i),n(d.error);break;default:}};l.addEventListener(i);let c={id:s,input:t,options:r};l.postMessage("process",c)})}async function ue({loader:t,arrayBuffer:e,options:r,context:o}){let a,n;if(t.parseSync||t.parse)a=e,n=t.parseSync||t.parse;else if(t.parseTextSync)a=new TextDecoder().decode(e),n=t.parseTextSync;else throw new Error(`Could not load data with ${t.name} loader`);return r={...r,modules:t&&t.options&&t.options.modules||{},worker:!1},await n(a,{...r},o,t)}var W="4.0.2";var le={draco:{decoderType:typeof WebAssembly=="object"?"wasm":"js",libraryPath:"libs/",extraAttributes:{},attributeNameEntry:void 0}},v={name:"Draco",id:"draco",module:"draco",version:W,worker:!0,extensions:["drc"],mimeTypes:["application/octet-stream"],binary:!0,tests:["DRACO"],options:le};function z(t){switch(t.constructor){case Int8Array:return"int8";case Uint8Array:case Uint8ClampedArray:return"uint8";case Int16Array:return"int16";case Uint16Array:return"uint16";case Int32Array:return"int32";case Uint32Array:return"uint32";case Float32Array:return"float32";case Float64Array:return"float64";default:return"null"}}function E(t){let e=1/0,r=1/0,o=1/0,a=-1/0,n=-1/0,s=-1/0,i=t.POSITION?t.POSITION.value:[],c=i&&i.length;for(let f=0;f<c;f+=3){let d=i[f],m=i[f+1],h=i[f+2];e=d<e?d:e,r=m<r?m:r,o=h<o?h:o,a=d>a?d:a,n=m>n?m:n,s=h>s?h:s}return[[e,r,o],[a,n,s]]}function L(t,e,r){let o=z(e.value),a=r||V(e);return{name:t,type:{type:"fixed-size-list",listSize:e.size,children:[{name:"value",type:o}]},nullable:!1,metadata:a}}function V(t){let e={};return"byteOffset"in t&&(e.byteOffset=t.byteOffset.toString(10)),"byteStride"in t&&(e.byteStride=t.byteStride.toString(10)),"normalized"in t&&(e.normalized=t.normalized.toString()),e}function U(t,e,r){let o=q(e.metadata),a=[],n=pe(e.attributes);for(let s in t){let i=t[s],c=G(s,i,n[s]);a.push(c)}if(r){let s=G("indices",r);a.push(s)}return{fields:a,metadata:o}}function pe(t){let e={};for(let r in t){let o=t[r];e[o.name||"undefined"]=o}return e}function G(t,e,r){let o=r?q(r.metadata):void 0;return L(t,e,o)}function q(t){Object.entries(t);let e={};for(let r in t)e[`${r}.string`]=JSON.stringify(t[r]);return e}var $={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},fe={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},ye=4,T=class{draco;decoder;metadataQuerier;constructor(e){this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,r={}){let o=new this.draco.DecoderBuffer;o.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(r);let a=this.decoder.GetEncodedGeometryType(o),n=a===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let s;switch(a){case this.draco.TRIANGULAR_MESH:s=this.decoder.DecodeBufferToMesh(o,n);break;case this.draco.POINT_CLOUD:s=this.decoder.DecodeBufferToPointCloud(o,n);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!s.ok()||!n.ptr){let h=`DRACO decompression failed: ${s.error_msg()}`;throw new Error(h)}let i=this._getDracoLoaderData(n,a,r),c=this._getMeshData(n,i,r),f=E(c.attributes),d=U(c.attributes,i,c.indices);return{loader:"draco",loaderData:i,header:{vertexCount:n.num_points(),boundingBox:f},...c,schema:d}}finally{this.draco.destroy(o),n&&this.draco.destroy(n)}}_getDracoLoaderData(e,r,o){let a=this._getTopLevelMetadata(e),n=this._getDracoAttributes(e,o);return{geometry_type:r,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:a,attributes:n}}_getDracoAttributes(e,r){let o={};for(let a=0;a<e.num_attributes();a++){let n=this.decoder.GetAttribute(e,a),s=this._getAttributeMetadata(e,a);o[n.unique_id()]={unique_id:n.unique_id(),attribute_type:n.attribute_type(),data_type:n.data_type(),num_components:n.num_components(),byte_offset:n.byte_offset(),byte_stride:n.byte_stride(),normalized:n.normalized(),attribute_index:a,metadata:s};let i=this._getQuantizationTransform(n,r);i&&(o[n.unique_id()].quantization_transform=i);let c=this._getOctahedronTransform(n,r);c&&(o[n.unique_id()].octahedron_transform=c)}return o}_getMeshData(e,r,o){let a=this._getMeshAttributes(r,e,o);if(!a.POSITION)throw new Error("DRACO: No position attribute found.");if(e instanceof this.draco.Mesh)switch(o.topology){case"triangle-strip":return{topology:"triangle-strip",mode:4,attributes:a,indices:{value:this._getTriangleStripIndices(e),size:1}};case"triangle-list":default:return{topology:"triangle-list",mode:5,attributes:a,indices:{value:this._getTriangleListIndices(e),size:1}}}return{topology:"point-list",mode:0,attributes:a}}_getMeshAttributes(e,r,o){let a={};for(let n of Object.values(e.attributes)){let s=this._deduceAttributeName(n,o);n.name=s;let{value:i,size:c}=this._getAttributeValues(r,n);a[s]={value:i,size:c,byteOffset:n.byte_offset,byteStride:n.byte_stride,normalized:n.normalized}}return a}_getTriangleListIndices(e){let o=e.num_faces()*3,a=o*ye,n=this.draco._malloc(a);try{return this.decoder.GetTrianglesUInt32Array(e,a,n),new Uint32Array(this.draco.HEAPF32.buffer,n,o).slice()}finally{this.draco._free(n)}}_getTriangleStripIndices(e){let r=new this.draco.DracoInt32Array;try{return this.decoder.GetTriangleStripsFromMesh(e,r),he(r)}finally{this.draco.destroy(r)}}_getAttributeValues(e,r){let o=fe[r.data_type],a=r.num_components,s=e.num_points()*a,i=s*o.BYTES_PER_ELEMENT,c=me(this.draco,o),f,d=this.draco._malloc(i);try{let m=this.decoder.GetAttribute(e,r.attribute_index);this.decoder.GetAttributeDataArrayForAllPoints(e,m,c,i,d),f=new o(this.draco.HEAPF32.buffer,d,s).slice()}finally{this.draco._free(d)}return{value:f,size:a}}_deduceAttributeName(e,r){let o=e.unique_id;for(let[s,i]of Object.entries(r.extraAttributes||{}))if(i===o)return s;let a=e.attribute_type;for(let s in $)if(this.draco[s]===a)return $[s];let n=r.attributeNameEntry||"name";return e.metadata[n]?e.metadata[n].string:`CUSTOM_ATTRIBUTE_${o}`}_getTopLevelMetadata(e){let r=this.decoder.GetMetadata(e);return this._getDracoMetadata(r)}_getAttributeMetadata(e,r){let o=this.decoder.GetAttributeMetadata(e,r);return this._getDracoMetadata(o)}_getDracoMetadata(e){if(!e||!e.ptr)return{};let r={},o=this.metadataQuerier.NumEntries(e);for(let a=0;a<o;a++){let n=this.metadataQuerier.GetEntryName(e,a);r[n]=this._getDracoMetadataField(e,n)}return r}_getDracoMetadataField(e,r){let o=new this.draco.DracoInt32Array;try{this.metadataQuerier.GetIntEntryArray(e,r,o);let a=ge(o);return{int:this.metadataQuerier.GetIntEntry(e,r),string:this.metadataQuerier.GetStringEntry(e,r),double:this.metadataQuerier.GetDoubleEntry(e,r),intArray:a}}finally{this.draco.destroy(o)}}_disableAttributeTransforms(e){let{quantizedAttributes:r=[],octahedronAttributes:o=[]}=e,a=[...r,...o];for(let n of a)this.decoder.SkipAttributeTransform(this.draco[n])}_getQuantizationTransform(e,r){let{quantizedAttributes:o=[]}=r,a=e.attribute_type();if(o.map(s=>this.decoder[s]).includes(a)){let s=new this.draco.AttributeQuantizationTransform;try{if(s.InitFromAttribute(e))return{quantization_bits:s.quantization_bits(),range:s.range(),min_values:new Float32Array([1,2,3]).map(i=>s.min_value(i))}}finally{this.draco.destroy(s)}}return null}_getOctahedronTransform(e,r){let{octahedronAttributes:o=[]}=r,a=e.attribute_type();if(o.map(s=>this.decoder[s]).includes(a)){let s=new this.draco.AttributeQuantizationTransform;try{if(s.InitFromAttribute(e))return{quantization_bits:s.quantization_bits()}}finally{this.draco.destroy(s)}}return null}};function me(t,e){switch(e){case Float32Array:return t.DT_FLOAT32;case Int8Array:return t.DT_INT8;case Int16Array:return t.DT_INT16;case Int32Array:return t.DT_INT32;case Uint8Array:return t.DT_UINT8;case Uint16Array:return t.DT_UINT16;case Uint32Array:return t.DT_UINT32;default:return t.DT_INVALID}}function ge(t){let e=t.size(),r=new Int32Array(e);for(let o=0;o<e;o++)r[o]=t.GetValue(o);return r}function he(t){let e=t.size(),r=new Int32Array(e);for(let o=0;o<e;o++)r[o]=t.GetValue(o);return r}var Ae="1.5.6",be="1.4.1",I=`https://www.gstatic.com/draco/versioned/decoders/${Ae}`,u={DECODER:"draco_wasm_wrapper.js",DECODER_WASM:"draco_decoder.wasm",FALLBACK_DECODER:"draco_decoder.js",ENCODER:"draco_encoder.js"},P={[u.DECODER]:`${I}/${u.DECODER}`,[u.DECODER_WASM]:`${I}/${u.DECODER_WASM}`,[u.FALLBACK_DECODER]:`${I}/${u.FALLBACK_DECODER}`,[u.ENCODER]:`https://raw.githubusercontent.com/google/draco/${be}/javascript/${u.ENCODER}`},D;async function Q(t){let e=t.modules||{};return e.draco3d?D=D||e.draco3d.createDecoderModule({}).then(r=>({draco:r})):D=D||Te(t),await D}async function Te(t){let e,r;switch(t.draco&&t.draco.decoderType){case"js":e=await b(P[u.FALLBACK_DECODER],"draco",t,u.FALLBACK_DECODER);break;case"wasm":default:[e,r]=await Promise.all([await b(P[u.DECODER],"draco",t,u.DECODER),await b(P[u.DECODER_WASM],"draco",t,u.DECODER_WASM)])}return e=e||globalThis.DracoDecoderModule,await De(e,r)}function De(t,e){let r={};return e&&(r.wasmBinary=e),new Promise(o=>{t({...r,onModuleLoaded:a=>o({draco:a})})})}var j={...v,parse:_e};async function _e(t,e){let{draco:r}=await Q(e),o=new T(r);try{return o.parseSync(t,e?.draco)}finally{o.destroy()}}O(j);})();
"use strict";
(() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// (disabled):../worker-utils/src/lib/node/require-utils.node
var require_require_utils = __commonJS({
"(disabled):../worker-utils/src/lib/node/require-utils.node"() {
"use strict";
}
});
// ../worker-utils/src/lib/env-utils/version.ts
function getVersion() {
if (!globalThis._loadersgl_?.version) {
globalThis._loadersgl_ = globalThis._loadersgl_ || {};
if (false) {
console.warn(
"loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."
);
globalThis._loadersgl_.version = NPM_TAG;
} else {
globalThis._loadersgl_.version = "4.0.3";
}
}
return globalThis._loadersgl_.version;
}
var VERSION = getVersion();
// ../worker-utils/src/lib/env-utils/assert.ts
function assert(condition, message) {
if (!condition) {
throw new Error(message || "loaders.gl assertion failed.");
}
}
// ../worker-utils/src/lib/env-utils/globals.ts
var globals = {
self: typeof self !== "undefined" && self,
window: typeof window !== "undefined" && window,
global: typeof global !== "undefined" && global,
document: typeof document !== "undefined" && document
};
var self_ = globals.self || globals.window || globals.global || {};
var window_ = globals.window || globals.self || globals.global || {};
var global_ = globals.global || globals.self || globals.window || {};
var document_ = globals.document || {};
var isBrowser = (
// @ts-ignore process.browser
typeof process !== "object" || String(process) !== "[object process]" || process.browser
);
var isWorker = typeof importScripts === "function";
var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
var nodeVersion = matches && parseFloat(matches[1]) || 0;
// ../worker-utils/src/lib/worker-utils/get-transfer-list.ts
function getTransferList(object, recursive = true, transfers) {
const transfersSet = transfers || /* @__PURE__ */ new Set();
if (!object) {
} else if (isTransferable(object)) {
transfersSet.add(object);
} else if (isTransferable(object.buffer)) {
transfersSet.add(object.buffer);
} else if (ArrayBuffer.isView(object)) {
} else if (recursive && typeof object === "object") {
for (const key in object) {
getTransferList(object[key], recursive, transfersSet);
}
}
return transfers === void 0 ? Array.from(transfersSet) : [];
}
function isTransferable(object) {
if (!object) {
return false;
}
if (object instanceof ArrayBuffer) {
return true;
}
if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
return true;
}
if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
return true;
}
if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
return true;
}
return false;
}
// ../worker-utils/src/lib/worker-farm/worker-body.ts
async function getParentPort() {
let parentPort;
try {
eval("globalThis.parentPort = require('worker_threads').parentPort");
parentPort = globalThis.parentPort;
} catch {
try {
eval("globalThis.workerThreadsPromise = import('worker_threads')");
const workerThreads = await globalThis.workerThreadsPromise;
parentPort = workerThreads.parentPort;
} catch (error) {
console.error(error.message);
}
}
return parentPort;
}
var onMessageWrapperMap = /* @__PURE__ */ new Map();
var WorkerBody = class {
/** Check that we are actually in a worker thread */
static async inWorkerThread() {
return typeof self !== "undefined" || Boolean(await getParentPort());
}
/*
* (type: WorkerMessageType, payload: WorkerMessagePayload) => any
*/
static set onmessage(onMessage) {
async function handleMessage(message) {
const parentPort2 = await getParentPort();
const { type, payload } = parentPort2 ? message : message.data;
onMessage(type, payload);
}
getParentPort().then((parentPort2) => {
if (parentPort2) {
parentPort2.on("message", handleMessage);
parentPort2.on("exit", () => console.debug("Node worker closing"));
} else {
globalThis.onmessage = handleMessage;
}
});
}
static async addEventListener(onMessage) {
let onMessageWrapper = onMessageWrapperMap.get(onMessage);
if (!onMessageWrapper) {
onMessageWrapper = async (message) => {
if (!isKnownMessage(message)) {
return;
}
const parentPort3 = await getParentPort();
const { type, payload } = parentPort3 ? message : message.data;
onMessage(type, payload);
};
}
const parentPort2 = await getParentPort();
if (parentPort2) {
console.error("not implemented");
} else {
globalThis.addEventListener("message", onMessageWrapper);
}
}
static async removeEventListener(onMessage) {
const onMessageWrapper = onMessageWrapperMap.get(onMessage);
onMessageWrapperMap.delete(onMessage);
const parentPort2 = await getParentPort();
if (parentPort2) {
console.error("not implemented");
} else {
globalThis.removeEventListener("message", onMessageWrapper);
}
}
/**
* Send a message from a worker to creating thread (main thread)
* @param type
* @param payload
*/
static async postMessage(type, payload) {
const data = { source: "loaders.gl", type, payload };
const transferList = getTransferList(payload);
const parentPort2 = await getParentPort();
if (parentPort2) {
parentPort2.postMessage(data, transferList);
} else {
globalThis.postMessage(data, transferList);
}
}
};
function isKnownMessage(message) {
const { type, data } = message;
return type === "message" && data && typeof data.source === "string" && data.source.startsWith("loaders.gl");
}
// ../worker-utils/src/lib/library-utils/library-utils.ts
var node = __toESM(require_require_utils(), 1);
var loadLibraryPromises = {};
async function loadLibrary(libraryUrl, moduleName = null, options = {}, libraryName = null) {
if (moduleName) {
libraryUrl = getLibraryUrl(libraryUrl, moduleName, options, libraryName);
}
loadLibraryPromises[libraryUrl] = // eslint-disable-next-line @typescript-eslint/no-misused-promises
loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
return await loadLibraryPromises[libraryUrl];
}
function getLibraryUrl(library, moduleName, options = {}, libraryName = null) {
if (!options.useLocalLibraries && library.startsWith("http")) {
return library;
}
libraryName = libraryName || library;
const modules = options.modules || {};
if (modules[libraryName]) {
return modules[libraryName];
}
if (!isBrowser) {
return `modules/${moduleName}/dist/libs/${libraryName}`;
}
if (options.CDN) {
assert(options.CDN.startsWith("http"));
return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${libraryName}`;
}
if (isWorker) {
return `../src/libs/${libraryName}`;
}
return `modules/${moduleName}/src/libs/${libraryName}`;
}
async function loadLibraryFromFile(libraryUrl) {
if (libraryUrl.endsWith("wasm")) {
return await loadAsArrayBuffer(libraryUrl);
}
if (!isBrowser) {
try {
return node && void 0 && await (void 0)(libraryUrl);
} catch (error) {
console.error(error);
return null;
}
}
if (isWorker) {
return importScripts(libraryUrl);
}
const scriptSource = await loadAsText(libraryUrl);
return loadLibraryFromString(scriptSource, libraryUrl);
}
function loadLibraryFromString(scriptSource, id) {
if (!isBrowser) {
return void 0 && (void 0)(scriptSource, id);
}
if (isWorker) {
eval.call(globalThis, scriptSource);
return null;
}
const script = document.createElement("script");
script.id = id;
try {
script.appendChild(document.createTextNode(scriptSource));
} catch (e) {
script.text = scriptSource;
}
document.body.appendChild(script);
return null;
}
async function loadAsArrayBuffer(url) {
if (isBrowser || !void 0 || url.startsWith("http")) {
const response = await fetch(url);
return await response.arrayBuffer();
}
return await (void 0)(url);
}
async function loadAsText(url) {
if (isBrowser || !void 0 || url.startsWith("http")) {
const response = await fetch(url);
return await response.text();
}
return await (void 0)(url);
}
// ../loader-utils/src/lib/worker-loader-utils/create-loader-worker.ts
var requestId = 0;
async function createLoaderWorker(loader) {
if (!await WorkerBody.inWorkerThread()) {
return;
}
WorkerBody.onmessage = async (type, payload) => {
switch (type) {
case "process":
try {
const { input, options = {}, context = {} } = payload;
const result = await parseData({
loader,
arrayBuffer: input,
options,
// @ts-expect-error fetch missing
context: {
...context,
_parse: parseOnMainThread
}
});
WorkerBody.postMessage("done", { result });
} catch (error) {
const message = error instanceof Error ? error.message : "";
WorkerBody.postMessage("error", { error: message });
}
break;
default:
}
};
}
function parseOnMainThread(arrayBuffer, loader, options, context) {
return new Promise((resolve, reject) => {
const id = requestId++;
const onMessage = (type, payload2) => {
if (payload2.id !== id) {
return;
}
switch (type) {
case "done":
WorkerBody.removeEventListener(onMessage);
resolve(payload2.result);
break;
case "error":
WorkerBody.removeEventListener(onMessage);
reject(payload2.error);
break;
default:
}
};
WorkerBody.addEventListener(onMessage);
const payload = { id, input: arrayBuffer, options };
WorkerBody.postMessage("process", payload);
});
}
async function parseData({
loader,
arrayBuffer,
options,
context
}) {
let data;
let parser;
if (loader.parseSync || loader.parse) {
data = arrayBuffer;
parser = loader.parseSync || loader.parse;
} else if (loader.parseTextSync) {
const textDecoder = new TextDecoder();
data = textDecoder.decode(arrayBuffer);
parser = loader.parseTextSync;
} else {
throw new Error(`Could not load data with ${loader.name} loader`);
}
options = {
...options,
modules: loader && loader.options && loader.options.modules || {},
worker: false
};
return await parser(data, { ...options }, context, loader);
}
// src/lib/utils/version.ts
var VERSION2 = true ? "4.0.3" : "latest";
// src/draco-loader.ts
var DEFAULT_DRACO_OPTIONS = {
draco: {
decoderType: typeof WebAssembly === "object" ? "wasm" : "js",
// 'js' for IE11
libraryPath: "libs/",
extraAttributes: {},
attributeNameEntry: void 0
}
};
var DracoLoader = {
name: "Draco",
id: "draco",
module: "draco",
// shapes: ['mesh'],
version: VERSION2,
worker: true,
extensions: ["drc"],
mimeTypes: ["application/octet-stream"],
binary: true,
tests: ["DRACO"],
options: DEFAULT_DRACO_OPTIONS
};
// ../schema/src/lib/table/simple-table/data-type.ts
function getDataTypeFromTypedArray(array) {
switch (array.constructor) {
case Int8Array:
return "int8";
case Uint8Array:
case Uint8ClampedArray:
return "uint8";
case Int16Array:
return "int16";
case Uint16Array:
return "uint16";
case Int32Array:
return "int32";
case Uint32Array:
return "uint32";
case Float32Array:
return "float32";
case Float64Array:
return "float64";
default:
return "null";
}
}
// ../schema/src/lib/mesh/mesh-utils.ts
function getMeshBoundingBox(attributes) {
let minX = Infinity;
let minY = Infinity;
let minZ = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
let maxZ = -Infinity;
const positions = attributes.POSITION ? attributes.POSITION.value : [];
const len = positions && positions.length;
for (let i = 0; i < len; i += 3) {
const x = positions[i];
const y = positions[i + 1];
const z = positions[i + 2];
minX = x < minX ? x : minX;
minY = y < minY ? y : minY;
minZ = z < minZ ? z : minZ;
maxX = x > maxX ? x : maxX;
maxY = y > maxY ? y : maxY;
maxZ = z > maxZ ? z : maxZ;
}
return [
[minX, minY, minZ],
[maxX, maxY, maxZ]
];
}
// ../schema/src/lib/mesh/deduce-mesh-schema.ts
function deduceMeshField(name, attribute, optionalMetadata) {
const type = getDataTypeFromTypedArray(attribute.value);
const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
return {
name,
type: { type: "fixed-size-list", listSize: attribute.size, children: [{ name: "value", type }] },
nullable: false,
metadata
};
}
function makeMeshAttributeMetadata(attribute) {
const result = {};
if ("byteOffset" in attribute) {
result.byteOffset = attribute.byteOffset.toString(10);
}
if ("byteStride" in attribute) {
result.byteStride = attribute.byteStride.toString(10);
}
if ("normalized" in attribute) {
result.normalized = attribute.normalized.toString();
}
return result;
}
// src/lib/utils/get-draco-schema.ts
function getDracoSchema(attributes, loaderData, indices) {
const metadata = makeMetadata(loaderData.metadata);
const fields = [];
const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
for (const attributeName in attributes) {
const attribute = attributes[attributeName];
const field = getArrowFieldFromAttribute(
attributeName,
attribute,
namedLoaderDataAttributes[attributeName]
);
fields.push(field);
}
if (indices) {
const indicesField = getArrowFieldFromAttribute("indices", indices);
fields.push(indicesField);
}
return { fields, metadata };
}
function transformAttributesLoaderData(loaderData) {
const result = {};
for (const key in loaderData) {
const dracoAttribute = loaderData[key];
result[dracoAttribute.name || "undefined"] = dracoAttribute;
}
return result;
}
function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : void 0;
const field = deduceMeshField(attributeName, attribute, metadataMap);
return field;
}
function makeMetadata(metadata) {
Object.entries(metadata);
const serializedMetadata = {};
for (const key in metadata) {
serializedMetadata[`${key}.string`] = JSON.stringify(metadata[key]);
}
return serializedMetadata;
}
// src/lib/draco-parser.ts
var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
POSITION: "POSITION",
NORMAL: "NORMAL",
COLOR: "COLOR_0",
TEX_COORD: "TEXCOORD_0"
};
var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
1: Int8Array,
2: Uint8Array,
3: Int16Array,
4: Uint16Array,
5: Int32Array,
6: Uint32Array,
9: Float32Array
};
var INDEX_ITEM_SIZE = 4;
var DracoParser = class {
draco;
decoder;
metadataQuerier;
// draco - the draco decoder, either import `draco3d` or load dynamically
constructor(draco) {
this.draco = draco;
this.decoder = new this.draco.Decoder();
this.metadataQuerier = new this.draco.MetadataQuerier();
}
/**
* Destroy draco resources
*/
destroy() {
this.draco.destroy(this.decoder);
this.draco.destroy(this.metadataQuerier);
}
/**
* NOTE: caller must call `destroyGeometry` on the return value after using it
* @param arrayBuffer
* @param options
*/
parseSync(arrayBuffer, options = {}) {
const buffer = new this.draco.DecoderBuffer();
buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
this._disableAttributeTransforms(options);
const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
try {
let dracoStatus;
switch (geometry_type) {
case this.draco.TRIANGULAR_MESH:
dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
break;
case this.draco.POINT_CLOUD:
dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
break;
default:
throw new Error("DRACO: Unknown geometry type.");
}
if (!dracoStatus.ok() || !dracoGeometry.ptr) {
const message = `DRACO decompression failed: ${dracoStatus.error_msg()}`;
throw new Error(message);
}
const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
const geometry = this._getMeshData(dracoGeometry, loaderData, options);
const boundingBox = getMeshBoundingBox(geometry.attributes);
const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
const data = {
loader: "draco",
loaderData,
header: {
vertexCount: dracoGeometry.num_points(),
boundingBox
},
...geometry,
schema
};
return data;
} finally {
this.draco.destroy(buffer);
if (dracoGeometry) {
this.draco.destroy(dracoGeometry);
}
}
}
// Draco specific "loader data"
/**
* Extract
* @param dracoGeometry
* @param geometry_type
* @param options
* @returns
*/
_getDracoLoaderData(dracoGeometry, geometry_type, options) {
const metadata = this._getTopLevelMetadata(dracoGeometry);
const attributes = this._getDracoAttributes(dracoGeometry, options);
return {
geometry_type,
num_attributes: dracoGeometry.num_attributes(),
num_points: dracoGeometry.num_points(),
num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
metadata,
attributes
};
}
/**
* Extract all draco provided information and metadata for each attribute
* @param dracoGeometry
* @param options
* @returns
*/
_getDracoAttributes(dracoGeometry, options) {
const dracoAttributes = {};
for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
dracoAttributes[dracoAttribute.unique_id()] = {
unique_id: dracoAttribute.unique_id(),
attribute_type: dracoAttribute.attribute_type(),
data_type: dracoAttribute.data_type(),
num_components: dracoAttribute.num_components(),
byte_offset: dracoAttribute.byte_offset(),
byte_stride: dracoAttribute.byte_stride(),
normalized: dracoAttribute.normalized(),
attribute_index: attributeId,
metadata
};
const quantization = this._getQuantizationTransform(dracoAttribute, options);
if (quantization) {
dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
}
const octahedron = this._getOctahedronTransform(dracoAttribute, options);
if (octahedron) {
dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
}
}
return dracoAttributes;
}
/**
* Get standard loaders.gl mesh category data
* Extracts the geometry from draco
* @param dracoGeometry
* @param options
*/
_getMeshData(dracoGeometry, loaderData, options) {
const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
const positionAttribute = attributes.POSITION;
if (!positionAttribute) {
throw new Error("DRACO: No position attribute found.");
}
if (dracoGeometry instanceof this.draco.Mesh) {
switch (options.topology) {
case "triangle-strip":
return {
topology: "triangle-strip",
mode: 4,
// GL.TRIANGLES
attributes,
indices: {
value: this._getTriangleStripIndices(dracoGeometry),
size: 1
}
};
case "triangle-list":
default:
return {
topology: "triangle-list",
mode: 5,
// GL.TRIANGLE_STRIP
attributes,
indices: {
value: this._getTriangleListIndices(dracoGeometry),
size: 1
}
};
}
}
return {
topology: "point-list",
mode: 0,
// GL.POINTS
attributes
};
}
_getMeshAttributes(loaderData, dracoGeometry, options) {
const attributes = {};
for (const loaderAttribute of Object.values(loaderData.attributes)) {
const attributeName = this._deduceAttributeName(loaderAttribute, options);
loaderAttribute.name = attributeName;
const { value, size } = this._getAttributeValues(dracoGeometry, loaderAttribute);
attributes[attributeName] = {
value,
size,
byteOffset: loaderAttribute.byte_offset,
byteStride: loaderAttribute.byte_stride,
normalized: loaderAttribute.normalized
};
}
return attributes;
}
// MESH INDICES EXTRACTION
/**
* For meshes, we need indices to define the faces.
* @param dracoGeometry
*/
_getTriangleListIndices(dracoGeometry) {
const numFaces = dracoGeometry.num_faces();
const numIndices = numFaces * 3;
const byteLength = numIndices * INDEX_ITEM_SIZE;
const ptr = this.draco._malloc(byteLength);
try {
this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
} finally {
this.draco._free(ptr);
}
}
/**
* For meshes, we need indices to define the faces.
* @param dracoGeometry
*/
_getTriangleStripIndices(dracoGeometry) {
const dracoArray = new this.draco.DracoInt32Array();
try {
this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
return getUint32Array(dracoArray);
} finally {
this.draco.destroy(dracoArray);
}
}
/**
*
* @param dracoGeometry
* @param dracoAttribute
* @param attributeName
*/
_getAttributeValues(dracoGeometry, attribute) {
const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
const numComponents = attribute.num_components;
const numPoints = dracoGeometry.num_points();
const numValues = numPoints * numComponents;
const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
const dataType = getDracoDataType(this.draco, TypedArrayCtor);
let value;
const ptr = this.draco._malloc(byteLength);
try {
const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
this.decoder.GetAttributeDataArrayForAllPoints(
dracoGeometry,
dracoAttribute,
dataType,
byteLength,
ptr
);
value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
} finally {
this.draco._free(ptr);
}
return { value, size: numComponents };
}
// Attribute names
/**
* DRACO does not store attribute names - We need to deduce an attribute name
* for each attribute
_getAttributeNames(
dracoGeometry: Mesh | PointCloud,
options: DracoParseOptions
): {[unique_id: number]: string} {
const attributeNames: {[unique_id: number]: string} = {};
for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
const attributeName = this._deduceAttributeName(dracoAttribute, options);
attributeNames[attributeName] = attributeName;
}
return attributeNames;
}
*/
/**
* Deduce an attribute name.
* @note DRACO does not save attribute names, just general type (POSITION, COLOR)
* to help optimize compression. We generate GLTF compatible names for the Draco-recognized
* types
* @param attributeData
*/
_deduceAttributeName(attribute, options) {
const uniqueId = attribute.unique_id;
for (const [attributeName, attributeUniqueId] of Object.entries(
options.extraAttributes || {}
)) {
if (attributeUniqueId === uniqueId) {
return attributeName;
}
}
const thisAttributeType = attribute.attribute_type;
for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
const attributeType = this.draco[dracoAttributeConstant];
if (attributeType === thisAttributeType) {
return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
}
}
const entryName = options.attributeNameEntry || "name";
if (attribute.metadata[entryName]) {
return attribute.metadata[entryName].string;
}
return `CUSTOM_ATTRIBUTE_${uniqueId}`;
}
// METADATA EXTRACTION
/** Get top level metadata */
_getTopLevelMetadata(dracoGeometry) {
const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
return this._getDracoMetadata(dracoMetadata);
}
/** Get per attribute metadata */
_getAttributeMetadata(dracoGeometry, attributeId) {
const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
return this._getDracoMetadata(dracoMetadata);
}
/**
* Extract metadata field values
* @param dracoMetadata
* @returns
*/
_getDracoMetadata(dracoMetadata) {
if (!dracoMetadata || !dracoMetadata.ptr) {
return {};
}
const result = {};
const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
}
return result;
}
/**
* Extracts possible values for one metadata entry by name
* @param dracoMetadata
* @param entryName
*/
_getDracoMetadataField(dracoMetadata, entryName) {
const dracoArray = new this.draco.DracoInt32Array();
try {
this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
const intArray = getInt32Array(dracoArray);
return {
int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
intArray
};
} finally {
this.draco.destroy(dracoArray);
}
}
// QUANTIZED ATTRIBUTE SUPPORT (NO DECOMPRESSION)
/** Skip transforms for specific attribute types */
_disableAttributeTransforms(options) {
const { quantizedAttributes = [], octahedronAttributes = [] } = options;
const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
for (const dracoAttributeName of skipAttributes) {
this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
}
}
/**
* Extract (and apply?) Position Transform
* @todo not used
*/
_getQuantizationTransform(dracoAttribute, options) {
const { quantizedAttributes = [] } = options;
const attribute_type = dracoAttribute.attribute_type();
const skip = quantizedAttributes.map((type) => this.decoder[type]).includes(attribute_type);
if (skip) {
const transform = new this.draco.AttributeQuantizationTransform();
try {
if (transform.InitFromAttribute(dracoAttribute)) {
return {
quantization_bits: transform.quantization_bits(),
range: transform.range(),
min_values: new Float32Array([1, 2, 3]).map((i) => transform.min_value(i))
};
}
} finally {
this.draco.destroy(transform);
}
}
return null;
}
_getOctahedronTransform(dracoAttribute, options) {
const { octahedronAttributes = [] } = options;
const attribute_type = dracoAttribute.attribute_type();
const octahedron = octahedronAttributes.map((type) => this.decoder[type]).includes(attribute_type);
if (octahedron) {
const transform = new this.draco.AttributeQuantizationTransform();
try {
if (transform.InitFromAttribute(dracoAttribute)) {
return {
quantization_bits: transform.quantization_bits()
};
}
} finally {
this.draco.destroy(transform);
}
}
return null;
}
// HELPERS
};
function getDracoDataType(draco, attributeType) {
switch (attributeType) {
case Float32Array:
return draco.DT_FLOAT32;
case Int8Array:
return draco.DT_INT8;
case Int16Array:
return draco.DT_INT16;
case Int32Array:
return draco.DT_INT32;
case Uint8Array:
return draco.DT_UINT8;
case Uint16Array:
return draco.DT_UINT16;
case Uint32Array:
return draco.DT_UINT32;
default:
return draco.DT_INVALID;
}
}
function getInt32Array(dracoArray) {
const numValues = dracoArray.size();
const intArray = new Int32Array(numValues);
for (let i = 0; i < numValues; i++) {
intArray[i] = dracoArray.GetValue(i);
}
return intArray;
}
function getUint32Array(dracoArray) {
const numValues = dracoArray.size();
const intArray = new Int32Array(numValues);
for (let i = 0; i < numValues; i++) {
intArray[i] = dracoArray.GetValue(i);
}
return intArray;
}
// src/lib/draco-module-loader.ts
var DRACO_DECODER_VERSION = "1.5.6";
var DRACO_ENCODER_VERSION = "1.4.1";
var STATIC_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_DECODER_VERSION}`;
var DRACO_EXTERNAL_LIBRARIES = {
/** The primary Draco3D encoder, javascript wrapper part */
DECODER: "draco_wasm_wrapper.js",
/** The primary draco decoder, compiled web assembly part */
DECODER_WASM: "draco_decoder.wasm",
/** Fallback decoder for non-webassebly environments. Very big bundle, lower performance */
FALLBACK_DECODER: "draco_decoder.js",
/** Draco encoder */
ENCODER: "draco_encoder.js"
};
var DRACO_EXTERNAL_LIBRARY_URLS = {
[DRACO_EXTERNAL_LIBRARIES.DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER}`,
[DRACO_EXTERNAL_LIBRARIES.DECODER_WASM]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER_WASM}`,
[DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER}`,
[DRACO_EXTERNAL_LIBRARIES.ENCODER]: `https://raw.githubusercontent.com/google/draco/${DRACO_ENCODER_VERSION}/javascript/${DRACO_EXTERNAL_LIBRARIES.ENCODER}`
};
var loadDecoderPromise;
async function loadDracoDecoderModule(options) {
const modules = options.modules || {};
if (modules.draco3d) {
loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then((draco) => {
return { draco };
});
} else {
loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
}
return await loadDecoderPromise;
}
async function loadDracoDecoder(options) {
let DracoDecoderModule;
let wasmBinary;
switch (options.draco && options.draco.decoderType) {
case "js":
DracoDecoderModule = await loadLibrary(
DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER],
"draco",
options,
DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER
);
break;
case "wasm":
default:
[DracoDecoderModule, wasmBinary] = await Promise.all([
await loadLibrary(
DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER],
"draco",
options,
DRACO_EXTERNAL_LIBRARIES.DECODER
),
await loadLibrary(
DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER_WASM],
"draco",
options,
DRACO_EXTERNAL_LIBRARIES.DECODER_WASM
)
]);
}
DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
}
function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
const options = {};
if (wasmBinary) {
options.wasmBinary = wasmBinary;
}
return new Promise((resolve) => {
DracoDecoderModule({
...options,
onModuleLoaded: (draco) => resolve({ draco })
// Module is Promise-like. Wrap in object to avoid loop.
});
});
}
// src/index.ts
var DracoLoader2 = {
...DracoLoader,
parse
};
async function parse(arrayBuffer, options) {
const { draco } = await loadDracoDecoderModule(options);
const dracoParser = new DracoParser(draco);
try {
return dracoParser.parseSync(arrayBuffer, options?.draco);
} finally {
dracoParser.destroy();
}
}
// src/workers/draco-worker.ts
createLoaderWorker(DracoLoader2);
})();
//# sourceMappingURL=draco-worker.js.map

@@ -1,4 +0,721 @@

"use strict";(()=>{var S=Object.create;var O=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var $=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var V=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var G=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of F(e))!v.call(r,a)&&a!==t&&O(r,a,{get:()=>e[a],enumerable:!(o=N(e,a))||o.enumerable});return r};var j=(r,e,t)=>(t=r!=null?S($(r)):{},G(e||!r||!r.__esModule?O(t,"default",{value:r,enumerable:!0}):t,r));var B=V(()=>{"use strict"});function q(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.0.2"),globalThis._loadersgl_.version}var b=q();function T(r,e){if(!r)throw new Error(e||"loaders.gl assertion failed.")}var l={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},ie=l.self||l.window||l.global||{},de=l.window||l.self||l.global||{},ce=l.global||l.self||l.window||{},le=l.document||{};var h=typeof process!="object"||String(process)!=="[object process]"||process.browser,E=typeof importScripts=="function",ue=typeof window<"u"&&typeof window.orientation<"u",R=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),fe=R&&parseFloat(R[1])||0;function A(r,e=!0,t){let o=t||new Set;if(r){if(P(r))o.add(r);else if(P(r.buffer))o.add(r.buffer);else if(!ArrayBuffer.isView(r)){if(e&&typeof r=="object")for(let a in r)A(r[a],e,o)}}return t===void 0?Array.from(o):[]}function P(r){return r?r instanceof ArrayBuffer||typeof MessagePort<"u"&&r instanceof MessagePort||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas:!1}async function y(){let parentPort;try{eval("globalThis.parentPort = require('worker_threads').parentPort"),parentPort=globalThis.parentPort}catch{try{eval("globalThis.workerThreadsPromise = import('worker_threads')");let workerThreads=await globalThis.workerThreadsPromise;parentPort=workerThreads.parentPort}catch(r){console.error(r.message)}}return parentPort}var D=new Map,f=class{static async inWorkerThread(){return typeof self<"u"||Boolean(await y())}static set onmessage(e){async function t(o){let a=await y(),{type:s,payload:i}=a?o:o.data;e(s,i)}y().then(o=>{o?(o.on("message",t),o.on("exit",()=>console.debug("Node worker closing"))):globalThis.onmessage=t})}static async addEventListener(e){let t=D.get(e);t||(t=async a=>{if(!z(a))return;let s=await y(),{type:i,payload:n}=s?a:a.data;e(i,n)}),await y()?console.error("not implemented"):globalThis.addEventListener("message",t)}static async removeEventListener(e){let t=D.get(e);D.delete(e),await y()?console.error("not implemented"):globalThis.removeEventListener("message",t)}static async postMessage(e,t){let o={source:"loaders.gl",type:e,payload:t},a=A(t),s=await y();s?s.postMessage(o,a):globalThis.postMessage(o,a)}};function z(r){let{type:e,data:t}=r;return e==="message"&&t&&typeof t.source=="string"&&t.source.startsWith("loaders.gl")}var d=j(B(),1);var _={};async function M(r,e=null,t={},o=null){return e&&(r=C(r,e,t,o)),_[r]=_[r]||U(r),await _[r]}function C(r,e,t={},o=null){if(!t.useLocalLibraries&&r.startsWith("http"))return r;o=o||r;let a=t.modules||{};return a[o]?a[o]:h?t.CDN?(T(t.CDN.startsWith("http")),`${t.CDN}/${e}@${b}/dist/libs/${o}`):E?`../src/libs/${o}`:`modules/${e}/src/libs/${o}`:`modules/${e}/dist/libs/${o}`}async function U(r){if(r.endsWith("wasm"))return await X(r);if(!h)try{return d&&void 0&&await(void 0)(r)}catch(t){return console.error(t),null}if(E)return importScripts(r);let e=await Q(r);return K(e,r)}function K(r,e){if(!h)return void 0&&(void 0)(r,e);if(E)return eval.call(globalThis,r),null;let t=document.createElement("script");t.id=e;try{t.appendChild(document.createTextNode(r))}catch{t.text=r}return document.body.appendChild(t),null}async function X(r){return h||!void 0||r.startsWith("http")?await(await fetch(r)).arrayBuffer():await(void 0)(r)}async function Q(r){return h||!void 0||r.startsWith("http")?await(await fetch(r)).text():await(void 0)(r)}var W={POSITION:"POSITION",NORMAL:"NORMAL",COLOR_0:"COLOR",TEXCOORD_0:"TEX_COORD"},H=()=>{},g=class{draco;dracoEncoder;dracoMeshBuilder;dracoMetadataBuilder;log;constructor(e){this.draco=e,this.dracoEncoder=new this.draco.Encoder,this.dracoMeshBuilder=new this.draco.MeshBuilder,this.dracoMetadataBuilder=new this.draco.MetadataBuilder}destroy(){this.destroyEncodedObject(this.dracoMeshBuilder),this.destroyEncodedObject(this.dracoEncoder),this.destroyEncodedObject(this.dracoMetadataBuilder),this.dracoMeshBuilder=null,this.dracoEncoder=null,this.draco=null}destroyEncodedObject(e){e&&this.draco.destroy(e)}encodeSync(e,t={}){return this.log=H,this._setOptions(t),t.pointcloud?this._encodePointCloud(e,t):this._encodeMesh(e,t)}_getAttributesFromMesh(e){let t={...e,...e.attributes};return e.indices&&(t.indices=e.indices),t}_encodePointCloud(e,t){let o=new this.draco.PointCloud;t.metadata&&this._addGeometryMetadata(o,t.metadata);let a=this._getAttributesFromMesh(e);this._createDracoPointCloud(o,a,t);let s=new this.draco.DracoInt8Array;try{let i=this.dracoEncoder.EncodePointCloudToDracoBuffer(o,!1,s);if(!(i>0))throw new Error("Draco encoding failed.");return this.log(`DRACO encoded ${o.num_points()} points
with ${o.num_attributes()} attributes into ${i} bytes`),I(s)}finally{this.destroyEncodedObject(s),this.destroyEncodedObject(o)}}_encodeMesh(e,t){let o=new this.draco.Mesh;t.metadata&&this._addGeometryMetadata(o,t.metadata);let a=this._getAttributesFromMesh(e);this._createDracoMesh(o,a,t);let s=new this.draco.DracoInt8Array;try{let i=this.dracoEncoder.EncodeMeshToDracoBuffer(o,s);if(i<=0)throw new Error("Draco encoding failed.");return this.log(`DRACO encoded ${o.num_points()} points
with ${o.num_attributes()} attributes into ${i} bytes`),I(s)}finally{this.destroyEncodedObject(s),this.destroyEncodedObject(o)}}_setOptions(e){if("speed"in e&&this.dracoEncoder.SetSpeedOptions(...e.speed),"method"in e){let t=this.draco[e.method||"MESH_SEQUENTIAL_ENCODING"];this.dracoEncoder.SetEncodingMethod(t)}if("quantization"in e)for(let t in e.quantization){let o=e.quantization[t],a=this.draco[t];this.dracoEncoder.SetAttributeQuantization(a,o)}}_createDracoMesh(e,t,o){let a=o.attributesMetadata||{};try{let s=this._getPositionAttribute(t);if(!s)throw new Error("positions");let i=s.length/3;for(let n in t){let c=t[n];n=W[n]||n;let p=this._addAttributeToMesh(e,n,c,i);p!==-1&&this._addAttributeMetadata(e,p,{name:n,...a[n]||{}})}}catch(s){throw this.destroyEncodedObject(e),s}return e}_createDracoPointCloud(e,t,o){let a=o.attributesMetadata||{};try{let s=this._getPositionAttribute(t);if(!s)throw new Error("positions");let i=s.length/3;for(let n in t){let c=t[n];n=W[n]||n;let p=this._addAttributeToMesh(e,n,c,i);p!==-1&&this._addAttributeMetadata(e,p,{name:n,...a[n]||{}})}}catch(s){throw this.destroyEncodedObject(e),s}return e}_addAttributeToMesh(e,t,o,a){if(!ArrayBuffer.isView(o))return-1;let s=this._getDracoAttributeType(t),i=o.length/a;if(s==="indices"){let p=o.length/3;return this.log(`Adding attribute ${t}, size ${p}`),this.dracoMeshBuilder.AddFacesToMesh(e,p,o),-1}this.log(`Adding attribute ${t}, size ${i}`);let n=this.dracoMeshBuilder,{buffer:c}=o;switch(o.constructor){case Int8Array:return n.AddInt8Attribute(e,s,a,i,new Int8Array(c));case Int16Array:return n.AddInt16Attribute(e,s,a,i,new Int16Array(c));case Int32Array:return n.AddInt32Attribute(e,s,a,i,new Int32Array(c));case Uint8Array:case Uint8ClampedArray:return n.AddUInt8Attribute(e,s,a,i,new Uint8Array(c));case Uint16Array:return n.AddUInt16Attribute(e,s,a,i,new Uint16Array(c));case Uint32Array:return n.AddUInt32Attribute(e,s,a,i,new Uint32Array(c));case Float32Array:default:return n.AddFloatAttribute(e,s,a,i,new Float32Array(c))}}_getDracoAttributeType(e){switch(e.toLowerCase()){case"indices":return"indices";case"position":case"positions":case"vertices":return this.draco.POSITION;case"normal":case"normals":return this.draco.NORMAL;case"color":case"colors":return this.draco.COLOR;case"texcoord":case"texcoords":return this.draco.TEX_COORD;default:return this.draco.GENERIC}}_getPositionAttribute(e){for(let t in e){let o=e[t];if(this._getDracoAttributeType(t)===this.draco.POSITION)return o}return null}_addGeometryMetadata(e,t){let o=new this.draco.Metadata;this._populateDracoMetadata(o,t),this.dracoMeshBuilder.AddMetadata(e,o)}_addAttributeMetadata(e,t,o){let a=new this.draco.Metadata;this._populateDracoMetadata(a,o),this.dracoMeshBuilder.SetMetadataForAttribute(e,t,a)}_populateDracoMetadata(e,t){for(let[o,a]of J(t))switch(typeof a){case"number":Math.trunc(a)===a?this.dracoMetadataBuilder.AddIntEntry(e,o,a):this.dracoMetadataBuilder.AddDoubleEntry(e,o,a);break;case"object":a instanceof Int32Array&&this.dracoMetadataBuilder.AddIntEntryArray(e,o,a,a.length);break;case"string":default:this.dracoMetadataBuilder.AddStringEntry(e,o,a)}}};function I(r){let e=r.size(),t=new ArrayBuffer(e),o=new Int8Array(t);for(let a=0;a<e;++a)o[a]=r.GetValue(a);return t}function J(r){return r.entries&&!r.hasOwnProperty("entries")?r.entries():Object.entries(r)}var Y="1.5.6",Z="1.4.1",w=`https://www.gstatic.com/draco/versioned/decoders/${Y}`,u={DECODER:"draco_wasm_wrapper.js",DECODER_WASM:"draco_decoder.wasm",FALLBACK_DECODER:"draco_decoder.js",ENCODER:"draco_encoder.js"},ee={[u.DECODER]:`${w}/${u.DECODER}`,[u.DECODER_WASM]:`${w}/${u.DECODER_WASM}`,[u.FALLBACK_DECODER]:`${w}/${u.FALLBACK_DECODER}`,[u.ENCODER]:`https://raw.githubusercontent.com/google/draco/${Z}/javascript/${u.ENCODER}`};var m;async function k(r){let e=r.modules||{};return e.draco3d?m=m||e.draco3d.createEncoderModule({}).then(t=>({draco:t})):m=m||te(r),await m}async function te(r){let e=await M(ee[u.ENCODER],"draco",r,u.ENCODER);return e=e||globalThis.DracoEncoderModule,new Promise(t=>{e({onModuleLoaded:o=>t({draco:o})})})}var L="4.0.2";var re={pointcloud:!1,attributeNameEntry:"name"},x={name:"DRACO",id:"draco",module:"draco",version:L,extensions:["drc"],options:{draco:re},encode:oe};async function oe(r,e={}){let{draco:t}=await k(e),o=new g(t);try{return o.encodeSync(r,e.draco)}finally{o.destroy()}}(async()=>await f.inWorkerThread()&&(f.onmessage=async(r,e)=>{switch(r){case"process":try{let{input:t,options:o}=e,a=await x.encode(t,o);f.postMessage("done",{result:a})}catch(t){let o=t instanceof Error?t.message:"";f.postMessage("error",{error:o})}break;default:}}))();})();
"use strict";
(() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// (disabled):../worker-utils/src/lib/node/require-utils.node
var require_require_utils = __commonJS({
"(disabled):../worker-utils/src/lib/node/require-utils.node"() {
"use strict";
}
});
// ../worker-utils/src/lib/env-utils/version.ts
function getVersion() {
if (!globalThis._loadersgl_?.version) {
globalThis._loadersgl_ = globalThis._loadersgl_ || {};
if (false) {
console.warn(
"loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."
);
globalThis._loadersgl_.version = NPM_TAG;
} else {
globalThis._loadersgl_.version = "4.0.3";
}
}
return globalThis._loadersgl_.version;
}
var VERSION = getVersion();
// ../worker-utils/src/lib/env-utils/assert.ts
function assert(condition, message) {
if (!condition) {
throw new Error(message || "loaders.gl assertion failed.");
}
}
// ../worker-utils/src/lib/env-utils/globals.ts
var globals = {
self: typeof self !== "undefined" && self,
window: typeof window !== "undefined" && window,
global: typeof global !== "undefined" && global,
document: typeof document !== "undefined" && document
};
var self_ = globals.self || globals.window || globals.global || {};
var window_ = globals.window || globals.self || globals.global || {};
var global_ = globals.global || globals.self || globals.window || {};
var document_ = globals.document || {};
var isBrowser = (
// @ts-ignore process.browser
typeof process !== "object" || String(process) !== "[object process]" || process.browser
);
var isWorker = typeof importScripts === "function";
var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
var nodeVersion = matches && parseFloat(matches[1]) || 0;
// ../worker-utils/src/lib/worker-utils/get-transfer-list.ts
function getTransferList(object, recursive = true, transfers) {
const transfersSet = transfers || /* @__PURE__ */ new Set();
if (!object) {
} else if (isTransferable(object)) {
transfersSet.add(object);
} else if (isTransferable(object.buffer)) {
transfersSet.add(object.buffer);
} else if (ArrayBuffer.isView(object)) {
} else if (recursive && typeof object === "object") {
for (const key in object) {
getTransferList(object[key], recursive, transfersSet);
}
}
return transfers === void 0 ? Array.from(transfersSet) : [];
}
function isTransferable(object) {
if (!object) {
return false;
}
if (object instanceof ArrayBuffer) {
return true;
}
if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
return true;
}
if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
return true;
}
if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
return true;
}
return false;
}
// ../worker-utils/src/lib/worker-farm/worker-body.ts
async function getParentPort() {
let parentPort;
try {
eval("globalThis.parentPort = require('worker_threads').parentPort");
parentPort = globalThis.parentPort;
} catch {
try {
eval("globalThis.workerThreadsPromise = import('worker_threads')");
const workerThreads = await globalThis.workerThreadsPromise;
parentPort = workerThreads.parentPort;
} catch (error) {
console.error(error.message);
}
}
return parentPort;
}
var onMessageWrapperMap = /* @__PURE__ */ new Map();
var WorkerBody = class {
/** Check that we are actually in a worker thread */
static async inWorkerThread() {
return typeof self !== "undefined" || Boolean(await getParentPort());
}
/*
* (type: WorkerMessageType, payload: WorkerMessagePayload) => any
*/
static set onmessage(onMessage) {
async function handleMessage(message) {
const parentPort2 = await getParentPort();
const { type, payload } = parentPort2 ? message : message.data;
onMessage(type, payload);
}
getParentPort().then((parentPort2) => {
if (parentPort2) {
parentPort2.on("message", handleMessage);
parentPort2.on("exit", () => console.debug("Node worker closing"));
} else {
globalThis.onmessage = handleMessage;
}
});
}
static async addEventListener(onMessage) {
let onMessageWrapper = onMessageWrapperMap.get(onMessage);
if (!onMessageWrapper) {
onMessageWrapper = async (message) => {
if (!isKnownMessage(message)) {
return;
}
const parentPort3 = await getParentPort();
const { type, payload } = parentPort3 ? message : message.data;
onMessage(type, payload);
};
}
const parentPort2 = await getParentPort();
if (parentPort2) {
console.error("not implemented");
} else {
globalThis.addEventListener("message", onMessageWrapper);
}
}
static async removeEventListener(onMessage) {
const onMessageWrapper = onMessageWrapperMap.get(onMessage);
onMessageWrapperMap.delete(onMessage);
const parentPort2 = await getParentPort();
if (parentPort2) {
console.error("not implemented");
} else {
globalThis.removeEventListener("message", onMessageWrapper);
}
}
/**
* Send a message from a worker to creating thread (main thread)
* @param type
* @param payload
*/
static async postMessage(type, payload) {
const data = { source: "loaders.gl", type, payload };
const transferList = getTransferList(payload);
const parentPort2 = await getParentPort();
if (parentPort2) {
parentPort2.postMessage(data, transferList);
} else {
globalThis.postMessage(data, transferList);
}
}
};
function isKnownMessage(message) {
const { type, data } = message;
return type === "message" && data && typeof data.source === "string" && data.source.startsWith("loaders.gl");
}
// ../worker-utils/src/lib/library-utils/library-utils.ts
var node = __toESM(require_require_utils(), 1);
var loadLibraryPromises = {};
async function loadLibrary(libraryUrl, moduleName = null, options = {}, libraryName = null) {
if (moduleName) {
libraryUrl = getLibraryUrl(libraryUrl, moduleName, options, libraryName);
}
loadLibraryPromises[libraryUrl] = // eslint-disable-next-line @typescript-eslint/no-misused-promises
loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
return await loadLibraryPromises[libraryUrl];
}
function getLibraryUrl(library, moduleName, options = {}, libraryName = null) {
if (!options.useLocalLibraries && library.startsWith("http")) {
return library;
}
libraryName = libraryName || library;
const modules = options.modules || {};
if (modules[libraryName]) {
return modules[libraryName];
}
if (!isBrowser) {
return `modules/${moduleName}/dist/libs/${libraryName}`;
}
if (options.CDN) {
assert(options.CDN.startsWith("http"));
return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${libraryName}`;
}
if (isWorker) {
return `../src/libs/${libraryName}`;
}
return `modules/${moduleName}/src/libs/${libraryName}`;
}
async function loadLibraryFromFile(libraryUrl) {
if (libraryUrl.endsWith("wasm")) {
return await loadAsArrayBuffer(libraryUrl);
}
if (!isBrowser) {
try {
return node && void 0 && await (void 0)(libraryUrl);
} catch (error) {
console.error(error);
return null;
}
}
if (isWorker) {
return importScripts(libraryUrl);
}
const scriptSource = await loadAsText(libraryUrl);
return loadLibraryFromString(scriptSource, libraryUrl);
}
function loadLibraryFromString(scriptSource, id) {
if (!isBrowser) {
return void 0 && (void 0)(scriptSource, id);
}
if (isWorker) {
eval.call(globalThis, scriptSource);
return null;
}
const script = document.createElement("script");
script.id = id;
try {
script.appendChild(document.createTextNode(scriptSource));
} catch (e) {
script.text = scriptSource;
}
document.body.appendChild(script);
return null;
}
async function loadAsArrayBuffer(url) {
if (isBrowser || !void 0 || url.startsWith("http")) {
const response = await fetch(url);
return await response.arrayBuffer();
}
return await (void 0)(url);
}
async function loadAsText(url) {
if (isBrowser || !void 0 || url.startsWith("http")) {
const response = await fetch(url);
return await response.text();
}
return await (void 0)(url);
}
// src/lib/draco-builder.ts
var GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP = {
POSITION: "POSITION",
NORMAL: "NORMAL",
COLOR_0: "COLOR",
TEXCOORD_0: "TEX_COORD"
};
var noop = () => {
};
var DracoBuilder = class {
draco;
dracoEncoder;
dracoMeshBuilder;
dracoMetadataBuilder;
log;
// draco - the draco decoder, either import `draco3d` or load dynamically
constructor(draco) {
this.draco = draco;
this.dracoEncoder = new this.draco.Encoder();
this.dracoMeshBuilder = new this.draco.MeshBuilder();
this.dracoMetadataBuilder = new this.draco.MetadataBuilder();
}
destroy() {
this.destroyEncodedObject(this.dracoMeshBuilder);
this.destroyEncodedObject(this.dracoEncoder);
this.destroyEncodedObject(this.dracoMetadataBuilder);
this.dracoMeshBuilder = null;
this.dracoEncoder = null;
this.draco = null;
}
// TBD - when does this need to be called?
destroyEncodedObject(object) {
if (object) {
this.draco.destroy(object);
}
}
/**
* Encode mesh or point cloud
* @param mesh =({})
* @param options
*/
encodeSync(mesh, options = {}) {
this.log = noop;
this._setOptions(options);
return options.pointcloud ? this._encodePointCloud(mesh, options) : this._encodeMesh(mesh, options);
}
// PRIVATE
_getAttributesFromMesh(mesh) {
const attributes = { ...mesh, ...mesh.attributes };
if (mesh.indices) {
attributes.indices = mesh.indices;
}
return attributes;
}
_encodePointCloud(pointcloud, options) {
const dracoPointCloud = new this.draco.PointCloud();
if (options.metadata) {
this._addGeometryMetadata(dracoPointCloud, options.metadata);
}
const attributes = this._getAttributesFromMesh(pointcloud);
this._createDracoPointCloud(dracoPointCloud, attributes, options);
const dracoData = new this.draco.DracoInt8Array();
try {
const encodedLen = this.dracoEncoder.EncodePointCloudToDracoBuffer(
dracoPointCloud,
false,
dracoData
);
if (!(encodedLen > 0)) {
throw new Error("Draco encoding failed.");
}
this.log(`DRACO encoded ${dracoPointCloud.num_points()} points
with ${dracoPointCloud.num_attributes()} attributes into ${encodedLen} bytes`);
return dracoInt8ArrayToArrayBuffer(dracoData);
} finally {
this.destroyEncodedObject(dracoData);
this.destroyEncodedObject(dracoPointCloud);
}
}
_encodeMesh(mesh, options) {
const dracoMesh = new this.draco.Mesh();
if (options.metadata) {
this._addGeometryMetadata(dracoMesh, options.metadata);
}
const attributes = this._getAttributesFromMesh(mesh);
this._createDracoMesh(dracoMesh, attributes, options);
const dracoData = new this.draco.DracoInt8Array();
try {
const encodedLen = this.dracoEncoder.EncodeMeshToDracoBuffer(dracoMesh, dracoData);
if (encodedLen <= 0) {
throw new Error("Draco encoding failed.");
}
this.log(`DRACO encoded ${dracoMesh.num_points()} points
with ${dracoMesh.num_attributes()} attributes into ${encodedLen} bytes`);
return dracoInt8ArrayToArrayBuffer(dracoData);
} finally {
this.destroyEncodedObject(dracoData);
this.destroyEncodedObject(dracoMesh);
}
}
/**
* Set encoding options.
* @param {{speed?: any; method?: any; quantization?: any;}} options
*/
_setOptions(options) {
if ("speed" in options) {
this.dracoEncoder.SetSpeedOptions(...options.speed);
}
if ("method" in options) {
const dracoMethod = this.draco[options.method || "MESH_SEQUENTIAL_ENCODING"];
this.dracoEncoder.SetEncodingMethod(dracoMethod);
}
if ("quantization" in options) {
for (const attribute in options.quantization) {
const bits = options.quantization[attribute];
const dracoPosition = this.draco[attribute];
this.dracoEncoder.SetAttributeQuantization(dracoPosition, bits);
}
}
}
/**
* @param {Mesh} dracoMesh
* @param {object} attributes
* @returns {Mesh}
*/
_createDracoMesh(dracoMesh, attributes, options) {
const optionalMetadata = options.attributesMetadata || {};
try {
const positions = this._getPositionAttribute(attributes);
if (!positions) {
throw new Error("positions");
}
const vertexCount = positions.length / 3;
for (let attributeName in attributes) {
const attribute = attributes[attributeName];
attributeName = GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP[attributeName] || attributeName;
const uniqueId = this._addAttributeToMesh(dracoMesh, attributeName, attribute, vertexCount);
if (uniqueId !== -1) {
this._addAttributeMetadata(dracoMesh, uniqueId, {
name: attributeName,
...optionalMetadata[attributeName] || {}
});
}
}
} catch (error) {
this.destroyEncodedObject(dracoMesh);
throw error;
}
return dracoMesh;
}
/**
* @param {} dracoPointCloud
* @param {object} attributes
*/
_createDracoPointCloud(dracoPointCloud, attributes, options) {
const optionalMetadata = options.attributesMetadata || {};
try {
const positions = this._getPositionAttribute(attributes);
if (!positions) {
throw new Error("positions");
}
const vertexCount = positions.length / 3;
for (let attributeName in attributes) {
const attribute = attributes[attributeName];
attributeName = GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP[attributeName] || attributeName;
const uniqueId = this._addAttributeToMesh(
dracoPointCloud,
attributeName,
attribute,
vertexCount
);
if (uniqueId !== -1) {
this._addAttributeMetadata(dracoPointCloud, uniqueId, {
name: attributeName,
...optionalMetadata[attributeName] || {}
});
}
}
} catch (error) {
this.destroyEncodedObject(dracoPointCloud);
throw error;
}
return dracoPointCloud;
}
/**
* @param mesh
* @param attributeName
* @param attribute
* @param vertexCount
*/
_addAttributeToMesh(mesh, attributeName, attribute, vertexCount) {
if (!ArrayBuffer.isView(attribute)) {
return -1;
}
const type = this._getDracoAttributeType(attributeName);
const size = attribute.length / vertexCount;
if (type === "indices") {
const numFaces = attribute.length / 3;
this.log(`Adding attribute ${attributeName}, size ${numFaces}`);
this.dracoMeshBuilder.AddFacesToMesh(mesh, numFaces, attribute);
return -1;
}
this.log(`Adding attribute ${attributeName}, size ${size}`);
const builder = this.dracoMeshBuilder;
const { buffer } = attribute;
switch (attribute.constructor) {
case Int8Array:
return builder.AddInt8Attribute(mesh, type, vertexCount, size, new Int8Array(buffer));
case Int16Array:
return builder.AddInt16Attribute(mesh, type, vertexCount, size, new Int16Array(buffer));
case Int32Array:
return builder.AddInt32Attribute(mesh, type, vertexCount, size, new Int32Array(buffer));
case Uint8Array:
case Uint8ClampedArray:
return builder.AddUInt8Attribute(mesh, type, vertexCount, size, new Uint8Array(buffer));
case Uint16Array:
return builder.AddUInt16Attribute(mesh, type, vertexCount, size, new Uint16Array(buffer));
case Uint32Array:
return builder.AddUInt32Attribute(mesh, type, vertexCount, size, new Uint32Array(buffer));
case Float32Array:
default:
return builder.AddFloatAttribute(mesh, type, vertexCount, size, new Float32Array(buffer));
}
}
/**
* DRACO can compress attributes of know type better
* TODO - expose an attribute type map?
* @param attributeName
*/
_getDracoAttributeType(attributeName) {
switch (attributeName.toLowerCase()) {
case "indices":
return "indices";
case "position":
case "positions":
case "vertices":
return this.draco.POSITION;
case "normal":
case "normals":
return this.draco.NORMAL;
case "color":
case "colors":
return this.draco.COLOR;
case "texcoord":
case "texcoords":
return this.draco.TEX_COORD;
default:
return this.draco.GENERIC;
}
}
_getPositionAttribute(attributes) {
for (const attributeName in attributes) {
const attribute = attributes[attributeName];
const dracoType = this._getDracoAttributeType(attributeName);
if (dracoType === this.draco.POSITION) {
return attribute;
}
}
return null;
}
/**
* Add metadata for the geometry.
* @param dracoGeometry - WASM Draco Object
* @param metadata
*/
_addGeometryMetadata(dracoGeometry, metadata) {
const dracoMetadata = new this.draco.Metadata();
this._populateDracoMetadata(dracoMetadata, metadata);
this.dracoMeshBuilder.AddMetadata(dracoGeometry, dracoMetadata);
}
/**
* Add metadata for an attribute to geometry.
* @param dracoGeometry - WASM Draco Object
* @param uniqueAttributeId
* @param metadata
*/
_addAttributeMetadata(dracoGeometry, uniqueAttributeId, metadata) {
const dracoAttributeMetadata = new this.draco.Metadata();
this._populateDracoMetadata(dracoAttributeMetadata, metadata);
this.dracoMeshBuilder.SetMetadataForAttribute(
dracoGeometry,
uniqueAttributeId,
dracoAttributeMetadata
);
}
/**
* Add contents of object or map to a WASM Draco Metadata Object
* @param dracoMetadata - WASM Draco Object
* @param metadata
*/
_populateDracoMetadata(dracoMetadata, metadata) {
for (const [key, value] of getEntries(metadata)) {
switch (typeof value) {
case "number":
if (Math.trunc(value) === value) {
this.dracoMetadataBuilder.AddIntEntry(dracoMetadata, key, value);
} else {
this.dracoMetadataBuilder.AddDoubleEntry(dracoMetadata, key, value);
}
break;
case "object":
if (value instanceof Int32Array) {
this.dracoMetadataBuilder.AddIntEntryArray(dracoMetadata, key, value, value.length);
}
break;
case "string":
default:
this.dracoMetadataBuilder.AddStringEntry(dracoMetadata, key, value);
}
}
}
};
function dracoInt8ArrayToArrayBuffer(dracoData) {
const byteLength = dracoData.size();
const outputBuffer = new ArrayBuffer(byteLength);
const outputData = new Int8Array(outputBuffer);
for (let i = 0; i < byteLength; ++i) {
outputData[i] = dracoData.GetValue(i);
}
return outputBuffer;
}
function getEntries(container) {
const hasEntriesFunc = container.entries && !container.hasOwnProperty("entries");
return hasEntriesFunc ? container.entries() : Object.entries(container);
}
// src/lib/draco-module-loader.ts
var DRACO_DECODER_VERSION = "1.5.6";
var DRACO_ENCODER_VERSION = "1.4.1";
var STATIC_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_DECODER_VERSION}`;
var DRACO_EXTERNAL_LIBRARIES = {
/** The primary Draco3D encoder, javascript wrapper part */
DECODER: "draco_wasm_wrapper.js",
/** The primary draco decoder, compiled web assembly part */
DECODER_WASM: "draco_decoder.wasm",
/** Fallback decoder for non-webassebly environments. Very big bundle, lower performance */
FALLBACK_DECODER: "draco_decoder.js",
/** Draco encoder */
ENCODER: "draco_encoder.js"
};
var DRACO_EXTERNAL_LIBRARY_URLS = {
[DRACO_EXTERNAL_LIBRARIES.DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER}`,
[DRACO_EXTERNAL_LIBRARIES.DECODER_WASM]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER_WASM}`,
[DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER}`,
[DRACO_EXTERNAL_LIBRARIES.ENCODER]: `https://raw.githubusercontent.com/google/draco/${DRACO_ENCODER_VERSION}/javascript/${DRACO_EXTERNAL_LIBRARIES.ENCODER}`
};
var loadEncoderPromise;
async function loadDracoEncoderModule(options) {
const modules = options.modules || {};
if (modules.draco3d) {
loadEncoderPromise = loadEncoderPromise || modules.draco3d.createEncoderModule({}).then((draco) => {
return { draco };
});
} else {
loadEncoderPromise = loadEncoderPromise || loadDracoEncoder(options);
}
return await loadEncoderPromise;
}
async function loadDracoEncoder(options) {
let DracoEncoderModule = await loadLibrary(
DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.ENCODER],
"draco",
options,
DRACO_EXTERNAL_LIBRARIES.ENCODER
);
DracoEncoderModule = DracoEncoderModule || globalThis.DracoEncoderModule;
return new Promise((resolve) => {
DracoEncoderModule({
onModuleLoaded: (draco) => resolve({ draco })
// Module is Promise-like. Wrap in object to avoid loop.
});
});
}
// src/lib/utils/version.ts
var VERSION2 = true ? "4.0.3" : "latest";
// src/draco-writer.ts
var DEFAULT_DRACO_WRITER_OPTIONS = {
pointcloud: false,
// Set to true if pointcloud (mode: 0, no indices)
attributeNameEntry: "name"
// Draco Compression Parameters
// method: 'MESH_EDGEBREAKER_ENCODING', // Use draco defaults
// speed: [5, 5], // Use draco defaults
// quantization: { // Use draco defaults
// POSITION: 10
// }
};
var DracoWriter = {
name: "DRACO",
id: "draco",
module: "draco",
version: VERSION2,
extensions: ["drc"],
options: {
draco: DEFAULT_DRACO_WRITER_OPTIONS
},
encode
};
async function encode(data, options = {}) {
const { draco } = await loadDracoEncoderModule(options);
const dracoBuilder = new DracoBuilder(draco);
try {
return dracoBuilder.encodeSync(data, options.draco);
} finally {
dracoBuilder.destroy();
}
}
// src/workers/draco-writer-worker.ts
(async () => {
if (!await WorkerBody.inWorkerThread()) {
return;
}
WorkerBody.onmessage = async (type, payload) => {
switch (type) {
case "process":
try {
const { input, options } = payload;
const result = await DracoWriter.encode(input, options);
WorkerBody.postMessage("done", { result });
} catch (error) {
const message = error instanceof Error ? error.message : "";
WorkerBody.postMessage("error", { error: message });
}
break;
default:
}
};
})();
})();
//# sourceMappingURL=draco-writer-worker.js.map

@@ -1,2 +0,2 @@

import type { Writer, WriterOptions } from '@loaders.gl/loader-utils';
import type { WriterWithEncoder, WriterOptions } from '@loaders.gl/loader-utils';
import type { DracoMesh } from './lib/draco-types';

@@ -16,3 +16,3 @@ import type { DracoBuildOptions } from './lib/draco-builder';

*/
export declare const DracoWriter: Writer<DracoMesh, unknown, DracoWriterOptions>;
export declare const DracoWriter: WriterWithEncoder<DracoMesh, unknown, DracoWriterOptions>;
//# sourceMappingURL=draco-writer.d.ts.map
{
"name": "@loaders.gl/draco",
"version": "4.0.2",
"version": "4.0.3",
"description": "Framework-independent loader and writer for Draco compressed meshes and point clouds",

@@ -47,18 +47,18 @@ "license": "MIT",

"build-workers": "yarn build-loader-worker && yarn build-loader-worker-node && yarn build-writer-worker && yarn build-writer-worker-node",
"build-loader-worker": "esbuild src/workers/draco-worker.ts --outfile=dist/draco-worker.js --target=esnext --bundle --minify --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-loader-worker-node": "esbuild src/workers/draco-worker-node.ts --outfile=dist/draco-worker-node.js --target=node16 --platform=node --minify --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-writer-worker": "esbuild src/workers/draco-writer-worker.ts --outfile=dist/draco-writer-worker.js --target=esnext --minify --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-writer-worker-node": "esbuild src/workers/draco-writer-worker-node.ts --outfile=dist/draco-writer-worker-node.js --target=node16 --platform=node --minify --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\""
"build-loader-worker": "esbuild src/workers/draco-worker.ts --outfile=dist/draco-worker.js --target=esnext --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-loader-worker-node": "esbuild src/workers/draco-worker-node.ts --outfile=dist/draco-worker-node.js --target=node16 --format=esm --platform=node --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-writer-worker": "esbuild src/workers/draco-writer-worker.ts --outfile=dist/draco-writer-worker.js --target=esnext --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\"",
"build-writer-worker-node": "esbuild src/workers/draco-writer-worker-node.ts --outfile=dist/draco-writer-worker-node.js --target=node16 --platform=node --bundle --sourcemap --define:__VERSION__=\\\"$npm_package_version\\\""
},
"dependencies": {
"@babel/runtime": "^7.3.1",
"@loaders.gl/loader-utils": "4.0.2",
"@loaders.gl/schema": "4.0.2",
"@loaders.gl/worker-utils": "4.0.2",
"@loaders.gl/loader-utils": "4.0.3",
"@loaders.gl/schema": "4.0.3",
"@loaders.gl/worker-utils": "4.0.3",
"draco3d": "1.5.5"
},
"devDependencies": {
"@loaders.gl/polyfills": "4.0.2"
"@loaders.gl/polyfills": "4.0.3"
},
"gitHead": "471058d109d5652f28c32c1f296fd632f9a5c806"
"gitHead": "03c871839b36c997249dabae1844df53a35d3760"
}

@@ -1,2 +0,2 @@

import type {Writer, WriterOptions} from '@loaders.gl/loader-utils';
import type {WriterWithEncoder, WriterOptions} from '@loaders.gl/loader-utils';
import type {DracoMesh} from './lib/draco-types';

@@ -32,3 +32,3 @@ import type {DracoBuildOptions} from './lib/draco-builder';

*/
export const DracoWriter: Writer<DracoMesh, unknown, DracoWriterOptions> = {
export const DracoWriter: WriterWithEncoder<DracoMesh, unknown, DracoWriterOptions> = {
name: 'DRACO',

@@ -35,0 +35,0 @@ id: 'draco',

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc