//# sourceMappingURL=combined.min.js.map let DecodeStream=function(){function e(){this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=null}return e.prototype={ensureBuffer:function(e){var t=this.buffer,r=t?t.byteLength:0;if(ea&&(r=a)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}return this.pos=r,this.buffer.subarray(t,r)},lookChar:function(){for(var e=this.pos;this.bufferLength<=e;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos])},getChar:function(){for(var e=this.pos;this.bufferLength<=e;){if(this.eof)return null;this.readBlock()}return String.fromCharCode(this.buffer[this.pos++])},makeSubStream:function(e,t,r){for(var a=e+t;this.bufferLength<=a&&!this.eof;)this.readBlock();return new Stream(this.buffer,e,t,r)},skip:function(e){e||(e=1),this.pos+=e},reset:function(){this.pos=0}},e}(),FlateStream=function(){var e=new Uint32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),t=new Uint32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),r=new Uint32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),a=[new Uint32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],n=[new Uint32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];function s(e){throw new Error(e)}function i(e){var t=0,r=e[t++],a=e[t++];-1!=r&&-1!=a||s("Invalid header in flate stream"),8!=(15&r)&&s("Unknown compression method in flate stream"),((r<<8)+a)%31!=0&&s("Bad FCHECK in flate stream"),32&a&&s("FDICT bit set in flate stream"),this.bytes=e,this.bytesPos=2,this.codeSize=0,this.codeBuf=0,DecodeStream.call(this)}return i.prototype=Object.create(DecodeStream.prototype),i.prototype.getBits=function(e){for(var t,r=this.codeSize,a=this.codeBuf,n=this.bytes,i=this.bytesPos;r>e,this.codeSize=r-=e,this.bytesPos=i,t},i.prototype.getCode=function(e){for(var t=e[0],r=e[1],a=this.codeSize,n=this.codeBuf,i=this.bytes,o=this.bytesPos;a>16,d=65535&c;return(0==a||a>u,this.codeSize=a-u,this.bytesPos=o,d},i.prototype.generateHuffmanTable=function(e){for(var t=e.length,r=0,a=0;ar&&(r=e[a]);for(var n=1<>=1;for(a=u;a0;)t[m++]=n}var o=this.getBits(3);if(1&o&&(this.eof=!0),0!=(o>>=1)){var l,c;if(1==o)l=a,c=n;else if(2==o){for(var u=this.getBits(5)+257,d=this.getBits(5)+1,p=this.getBits(4)+4,g=Array(e.length),m=0;m=x&&(x=(M=this.ensureBuffer(S+1)).length),M[S++]=R;else{if(256==R)return void(this.bufferLength=S);var E=(R=t[R-=257])>>16;E>0&&(E=this.getBits(E));f=(65535&R)+E;R=this.getCode(c),(E=(R=r[R])>>16)>0&&(E=this.getBits(E));var b=(65535&R)+E;S+f>=x&&(x=(M=this.ensureBuffer(S+f)).length);for(var C=0;C{const t=new Uint8Array(n.response||n.mozResponseArrayBuffer),s=new e(t);return"function"==typeof(r&&r.getContext)&&s.render(r),"function"==typeof a?a(s):void 0},n.send(null)}constructor(e){let t;this.data=e,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={};let r=null;for(;;){var a;let e=this.readUInt32(),d="";for(t=0;t<4;t++)d+=String.fromCharCode(this.data[this.pos++]);switch(d){case"IHDR":this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":r&&this.animation.frames.push(r),this.pos+=4,r={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()};var n=this.readUInt16(),s=this.readUInt16()||100;r.delay=1e3*n/s,r.disposeOp=this.data[this.pos++],r.blendOp=this.data[this.pos++],r.data=[];break;case"IDAT":case"fdAT":for("fdAT"===d&&(this.pos+=4,e-=4),a=r&&r.data||this.imgData,t=0;t0)for(t=0;tthis.data.length)throw new Error("Incomplete or corrupt PNG file")}}read(e){const t=new Array(e);for(let r=0;r{const i=t++%r,o=a[i];this.renderFrame(e,i),r>1&&t/rcreateOccupancyGridSpec(e,"occupancy_grid",t))),blockSizes:t}}function createDistanceGridsSpec(e){if(!e.useDistanceGrid)return{assetType:"distance_grids",gridSpecs:[],blockSizes:[]};return{assetType:"distance_grids",gridSpecs:[createOccupancyGridSpec(e,"distance_grid",8)],blockSizes:[8]}}function createSparseGridSpec(e){e.export_array_format;let t=getFieldOrDefault(e,"export_store_rgb_and_density_separately",!1),r={assetType:"sparse_grid",blockIndicesSpec:createSparseGridBlockIndicesSpec(e),separateRgbAndDensity:t};return t?(r.rgbSpec=createSparseGridAssetSpec(e,"sparse_grid_rgb",3),r.densitySpec=createSparseGridAssetSpec(e,"sparse_grid_density",2),r.featuresSpec=createSparseGridAssetSpec(e,"sparse_grid_features",3)):(r.rgbAndDensitySpec=createSparseGridAssetSpec(e,"sparse_grid_rgb_and_density",4),r.featuresSpec=createSparseGridAssetSpec(e,"sparse_grid_features",4)),r}function createSparseGridBlockIndicesSpec(e){const t=e.export_array_format||"png";let r=e.sparse_grid_resolution/e.data_block_size;return{assetType:"sparse_grid_block_indices",filename:`sparse_grid_block_indices.${t}`,shape:[r,r,r],numChannels:3}}function createSparseGridAssetSpec(e,t,r){const a=e.export_array_format||"png";let n=e.num_slices,s=e.atlas_width,i=e.atlas_height,o=e.atlas_depth,l=Math.ceil(o/n),c=[];for(let e=0;e256;let c=getFieldOrDefault(e,"export_pad_occupancy_and_distance_grids",!0)?4:1,u=[];if(e.legacyGrids||!l){let n=`${t}_${r}.${a}`;e.legacyGrids||(n=`${t}_${r}_000.${a}`),u.push({assetType:`${t}_slice`,shape:[i,i,i],numChannels:c,sliceIndex:0,numSlices:1,filename:n})}else{const e=Math.ceil(i/8);for(let n=0;n<8;++n){let s=`${t}_${r}_${digits(n,3)}.${a}`;u.push({assetType:`${t}_slice`,shape:[i,i,e],numChannels:c,sliceIndex:n,numSlices:8,filename:s})}}return{assetType:`${t}_slices`,shape:[i,i,i],numChannels:c,voxelSize:o,blockSize:r,sliceSpecs:u,numSlices:8,mergeSlices:getMergeSlices(e)}}function createTriplaneSpec(e){const t=e.triplane_resolution;let r={assetType:"triplane",shape:[t,t,3],numSlices:3,voxelSize:e.triplane_voxel_size,separateRgbAndDensity:getFieldOrDefault(e,"export_store_rgb_and_density_separately",!1),featuresSpec:createTriplaneSlicesSpec(e,"triplane_features",4)};return r.separateRgbAndDensity?(r.rgbSpec=createTriplaneSlicesSpec(e,"triplane_rgb",3),r.densitySpec=createTriplaneSlicesSpec(e,"triplane_density",1)):r.rgbAndDensitySpec=createTriplaneSlicesSpec(e,"triplane_rgb_and_density",4),r}function createTriplaneSlicesSpec(e,t,r){const a=e.triplane_resolution;return{assetType:`${t}_slices`,shape:[a,a,3],numChannels:r,numSlices:3,mergeSlices:getMergeSlices(e),sliceSpecs:range(3).map((a=>createPlaneSliceSpec(e,t,r,a)))}}function createPlaneSliceSpec(e,t,r,a){const n=e.export_array_format||"png",s=e.triplane_resolution;let i=t.replace(/^triplane_/,"plane_");return{assetType:`${t}_slice`,shape:[s,s,1],numChannels:r,sliceIndex:a,numSlices:3,filename:`${i}_${a}.${n}`}}function getMergeSlices(e){const t=getFieldOrDefault(e,"export_store_rgb_and_density_separately",!1),r=getFieldOrDefault(e,"merge_slices",!t);if(!t&&!r)throw new Error('Slices must be merged when using "rgb_and_density" images. Please re-export with export_store_rgb_and_density_separately=true and try again.');return r&&t}const baseGoogleApiUrl="https://firebasestorage.googleapis.com/v0/b/test3-2d896.appspot.com/o";let gcsToken=null;function fetchGcsToken(){return gcsToken||(gcsToken=fetch("http://localhost:3001/get-gcs-token").then((e=>{if(!e.ok)throw new Error(`Erreur lors de la récupération du jeton GCS: ${e.status}`);return e.json()})).then((e=>(gcsToken=e.token,setTimeout((()=>{gcsToken=null}),84e4),gcsToken))).catch((e=>{throw console.error("Erreur lors de la récupération du jeton GCS:",e),gcsToken=null,e})),gcsTokenPromise)}function fetchScene(e,t){return{...e,occupancyGridsAsset:fetchAsset(e.occupancyGridsSpec,t),distanceGridsAsset:fetchAsset(e.distanceGridsSpec,t),triplaneAsset:fetchAsset(e.triplaneSpec,t),sparseGridAsset:fetchAsset(e.sparseGridSpec,t)}}function fetchOccupancyGrids(e,t){let r=e.gridSpecs.map((e=>fetchAsset(e,t)));return{...e,gridAssets:r}}function fetchSlices(e,t){let r=e.sliceSpecs.map((e=>fetchAsset(e,t)));return{...e,sliceAssets:r}}function fetchTriplane(e,t){let r={...e,featuresAsset:fetchAsset(e.featuresSpec,t)};return e.separateRgbAndDensity?(r.rgbAsset=fetchAsset(e.rgbSpec,t),r.densityAsset=fetchAsset(e.densitySpec,t)):r.rgbAndDensityAsset=fetchAsset(e.rgbAndDensitySpec,t),r}function fetchArray(e,t){const r=t.dirUrl;if("string"!=typeof r)throw console.error("dirUrl is not a valid string:",r),new Error("dirUrl must be a valid string");if(!e.filename)throw console.error("Spec missing filename:",e),new Error("Spec must contain a valid filename");const a=cleanPath(r),n=e.filename.endsWith(".gz")?e.filename.slice(0,-3):e.filename,s=encodeURIComponent(a),i=`${baseGoogleApiUrl}/users%2Fvisite_3D%2F${s}%2F${n}?alt=media&token=${gcsToken}`;console.log("Fetching from URL:",i);const o=loadAsset(i).then(validateSize(e)).then(onImageLoaded);return{...e,asset:o}}function validateSize(e){return t=>{const r=product(e.shape)*e.numChannels;return console.assert(t.length===r,`Size mismatch for ${e.filename}`,e,t),t}}function cleanPath(e){const t=e.split("/"),r=[];for(let e=0;ecreateEmptyVolumeTexture(...e.shape,t,THREE.LinearFilter),r=e.separateRgbAndDensity?e.rgbSpec:e.rgbAndDensitySpec,a=e.separateRgbAndDensity?e.densitySpec:e.rgbAndDensitySpec,n=t(r,THREE.RGBFormat),s=t(a,THREE.LuminanceAlphaFormat),i=t(e.featuresSpec,THREE.RGBFormat);return{textureType:"sparse_grid",blockIndicesTexture:{textureType:"sparse_grid_block_indices",texture:createEmptyVolumeTexture(...e.blockIndicesSpec.shape,THREE.RGBFormat,THREE.NearestFilter)},rgbTexture:{textureType:"sparse_grid_rgb",texture:n},densityTexture:{textureType:"sparse_grid_density",texture:s},featuresTexture:{textureType:"sparse_grid_features",texture:i}}}const gCreateEmptyTextureRegistry={scene:createEmptySceneTexture,triplane:createEmptyTriplaneTexture,triplane_rgb_slices:createEmptyTriplaneSlicesTexture,triplane_density_slices:createEmptyTriplaneSlicesTexture,triplane_features_slices:createEmptyTriplaneSlicesTexture,distance_grids:createEmptyOccupancyGridsTexture,distance_grid_slices:createEmptyOccupancyGridTexture,occupancy_grids:createEmptyOccupancyGridsTexture,occupancy_grid_slices:createEmptyOccupancyGridTexture,sparse_grid:createEmptySparseGridTexture};function createEmptyTexture(e){let t=gCreateEmptyTextureRegistry[e.assetType];return null==t&&console.error(`Failed to find loadFn for assetType ${e.assetType}`,e),t(e)}function prepareScenePayload(e){return{textureType:"scene",occupancyGridsPayload:prepareTexturePayload(e.occupancyGridsAsset),distanceGridsPayload:prepareTexturePayload(e.distanceGridsAsset),triplanePayload:prepareTexturePayload(e.triplaneAsset),sparseGridPayload:prepareTexturePayload(e.sparseGridAsset)}}function prepareOccupancyGridsPayload(e){return{textureType:e.assetType,gridPayloads:e.gridAssets.map(prepareTexturePayload)}}function prepareOccupancyGridPayload(e){return e.mergeSlices?prepareOccupancyGridMergedPayload(e):prepareOccupancyGridSlicesPayload(e)}function prepareOccupancyGridMergedPayload(e){return console.assert(e.assetType.endsWith("_slices"),e),{textureType:e.assetType.replace(/_slices$/,""),shape:e.shape,numChannels:e.numChannels,payload:mergeSlices(e,{1:GridTextureSource.RED_FROM_RED,4:GridTextureSource.ALPHA_FROM_RGBA}[e.numChannels],GridTextureDestination.RED_IN_RED)}}function prepareOccupancyGridSlicesPayload(e){return console.assert(e.assetType.endsWith("_slices"),e),{textureType:e.assetType.replace(/_slices$/,""),shape:e.shape,numChannels:e.numChannels,slicePayloads:e.sliceAssets.map(prepareTexturePayload)}}function prepareOccupancyGridSlicePayload(e){console.assert(e.assetType.endsWith("_slice"),e);let t=null;if(1==e.numChannels)t=e.asset;else{if(4!=e.numChannels)throw new Error("Unrecognized number of input channels",e);t=mergeSlices({shape:e.shape,numSlices:1,sliceAssets:[{...e,sliceIndex:0,numSlices:1}]},GridTextureSource.ALPHA_FROM_RGBA,GridTextureDestination.RED_IN_RED)}return{textureType:e.assetType,shape:e.shape,numChannels:e.numChannels,sliceIndex:e.sliceIndex,numSlices:e.numSlices,payload:t}}function prepareTriplanePayload(e){let t={textureType:"triplane",featuresPayload:preparePlanePayload(e.featuresAsset,"triplane_features",GridTextureSource.RGBA_FROM_RGBA,GridTextureDestination.RGBA_IN_RGBA)};return e.separateRgbAndDensity?(t.rgbPayload=preparePlanePayload(e.rgbAsset,"triplane_rgb",GridTextureSource.RGB_FROM_RGB,GridTextureDestination.RGB_IN_RGB),t.densityPayload=preparePlanePayload(e.densityAsset,"triplane_density",GridTextureSource.RED_FROM_RED,GridTextureDestination.RED_IN_RED)):(t.rgbPayload=preparePlanePayload(e.rgbAndDensityAsset,"triplane_rgb",GridTextureSource.RGB_FROM_RGBA,GridTextureDestination.RGB_IN_RGB),t.densityPayload=preparePlanePayload(e.rgbAndDensityAsset,"triplane_density",GridTextureSource.ALPHA_FROM_RGBA,GridTextureDestination.RED_IN_RED)),t}function preparePlanePayload(e,t,r,a){let n={textureType:t,shape:e.shape,numChannels:e.numChannels};return e.mergeSlices?n.payload=mergeSlices(e,r,a):n.slicePayloads=e.sliceAssets.map((e=>preparePlaneSlicePayload(e,r,a))),n}function preparePlaneSlicePayload(e,t,r){let a=null;return a=t.format==r.format&&t.channels==r.channels?e.asset:mergeSlices({shape:e.shape,numSlices:1,sliceAssets:[{...e,sliceIndex:0,numSlices:1}]},t,r),{textureType:e.assetType,shape:e.shape,sliceIndex:e.sliceIndex,numSlices:e.numSlices,numChannels:e.numChannels,payload:a}}function prepareArrayPayload(e){return{textureType:e.assetType,payload:e.asset,shape:e.shape,numChannels:e.numChannels}}function prepareSparseGridPayload(e){let t={textureType:"sparse_grid",blockIndicesPayload:prepareTexturePayload(e.blockIndicesAsset),featuresPayload:prepareTexturePayload(e.featuresAsset)};return e.separateRgbAndDensity?(t.rgbPayload=prepareTexturePayload(e.rgbAsset),t.densityPayload=prepareTexturePayload(e.densityAsset)):(t.rgbPayload=prepareTexturePayload(e.rgbAndDensityAsset),t.densityPayload=prepareSparseGridDensityPayload(e)),t}function prepareSparseGridGenericPayload(e){return e.mergeSlices?prepareSparseGridGenericMergedPayload(e):prepareSparseGridGenericSlicesPayload(e)}function prepareSparseGridGenericMergedPayload(e){let t=e.assetType.replace(/_slices$/,"");t.includes("rgb_and_density")&&(t=t.replace(/rgb_and_density$/,"rgb"));let r={2:GridTextureSource.LA_FROM_LUMINANCE_ALPHA,3:GridTextureSource.RGB_FROM_RGB,4:GridTextureSource.RGB_FROM_RGBA},a={2:GridTextureDestination.LA_IN_LUMINANCE_ALPHA,3:GridTextureDestination.RGB_IN_RGB,4:GridTextureDestination.RGB_IN_RGB},n=mergeSlices(e,r[e.numChannels],a[e.numChannels]);return{textureType:t,shape:e.shape,numChannels:e.numChannels,payload:n}}function prepareSparseGridGenericSlicesPayload(e){let t=e.assetType.replace(/_slices$/,"");return t.includes("rgb_and_density")&&(t=t.replace(/rgb_and_density$/,"rgb")),{textureType:t,shape:e.shape,numChannels:e.numChannels,numSlices:e.numSlices,slicePayloads:e.sliceAssets.map(prepareTexturePayload)}}function prepareSparseGridGenericSlicePayload(e){let t=e.assetType,r=null;if("sparse_grid_rgb_slice"==t&&3==e.numChannels||"sparse_grid_density_slice"==t&&2==e.numChannels||"sparse_grid_features_slice"==t&&3==e.numChannels)r=e.asset;else{let t={2:GridTextureSource.LA_FROM_LUMINANCE_ALPHA,3:GridTextureSource.RGB_FROM_RGB,4:GridTextureSource.RGB_FROM_RGBA},a={2:GridTextureDestination.LA_IN_LUMINANCE_ALPHA,3:GridTextureDestination.RGB_IN_RGB,4:GridTextureDestination.RGB_IN_RGB};r=mergeSlices({shape:e.shape,numSlices:1,sliceAssets:[{...e,sliceIndex:0,numSlices:1}]},t[e.numChannels],a[e.numChannels])}let a=t;return a.includes("rgb_and_density")&&(a=a.replace(/_rgb_and_density$/,"rgb")),{textureType:a,shape:e.shape,numChannels:e.numChannels,sliceIndex:e.sliceIndex,numSlices:e.numSlices,payload:r}}function prepareSparseGridDensityPayload(e){return{textureType:"sparse_grid_density",shape:e.rgbAndDensityAsset.shape,numChannels:2,payload:mergeSparseGridDensity(e)}}const gPrepareTexturePayloadRegistry={scene:prepareScenePayload,triplane:prepareTriplanePayload,distance_grids:prepareOccupancyGridsPayload,distance_grid_slices:prepareOccupancyGridPayload,distance_grid_slice:prepareOccupancyGridSlicePayload,occupancy_grids:prepareOccupancyGridsPayload,occupancy_grid_slices:prepareOccupancyGridPayload,occupancy_grid_slice:prepareOccupancyGridSlicePayload,sparse_grid:prepareSparseGridPayload,sparse_grid_block_indices:prepareArrayPayload,sparse_grid_rgb_and_density_slices:prepareSparseGridGenericPayload,sparse_grid_rgb_and_density_slice:prepareSparseGridGenericSlicePayload,sparse_grid_rgb_slices:prepareSparseGridGenericPayload,sparse_grid_rgb_slice:prepareSparseGridGenericSlicePayload,sparse_grid_density_slices:prepareSparseGridGenericPayload,sparse_grid_density_slice:prepareSparseGridGenericSlicePayload,sparse_grid_features_slices:prepareSparseGridGenericPayload,sparse_grid_features_slice:prepareSparseGridGenericSlicePayload};function prepareTexturePayload(e){let t=gPrepareTexturePayloadRegistry[e.assetType];return null==t&&console.error(`Failed to find loadFn for assetType ${e.assetType}`,e),t(e)}function populateScene(e,t){let r=[populateTexture(e.occupancyGridsTexture,t.occupancyGridsPayload),populateTexture(e.distanceGridsTexture,t.distanceGridsPayload),populateTexture(e.triplaneTexture,t.triplanePayload),populateTexture(e.sparseGridTexture,t.sparseGridPayload)];return Promise.all(r)}function populateOccupancyGridsTexture(e,t){console.assert(e.gridTextures.length==t.gridPayloads.length,e,t);let r=range(e.gridTextures.length).map((r=>populateTexture(e.gridTextures[r],t.gridPayloads[r])));return Promise.all(r)}function populateSparseGridTexture(e,t){let r=[populateTexture(e.blockIndicesTexture,t.blockIndicesPayload),populateTexture(e.rgbTexture,t.rgbPayload),populateTexture(e.densityTexture,t.densityPayload),populateTexture(e.featuresTexture,t.featuresPayload)];return Promise.all(r)}function populateTriplaneTexture(e,t){return Promise.all([populateTexture(e.rgbTexture,t.rgbPayload),populateTexture(e.densityTexture,t.densityPayload),populateTexture(e.featuresTexture,t.featuresPayload)])}async function populateArrayTexture(e,t){if(null==t.payload)throw new Error("Unclear how to ingest payload",e,t);e.texture.image.data=await t.payload,e.texture.needsUpdate=!0}function populateArrayTextureWithWebGL(e,t){if(null!=t.payload)return populateArrayTextureMergedWithWebGL(e,t);if(null!=t.slicePayloads){let r=t.slicePayloads.map((t=>populateArrayTextureSliceWithWebGL(e,t)));return Promise.all(r)}throw new Error("Unclear how to ingest payload",e,t)}async function populateArrayTextureSliceWithWebGL(e,t){let r=gRenderer.getContext();const a=t.shape[0],n=t.shape[1],s=t.shape[2],i=t.sliceIndex;let o=e.texture.format,{glFormat:l,glInternalFormat:c,numChannels:u}=threeFormatToOpenGLFormat(r,o),d=await t.payload;let p,g,m=gRenderer.properties.get(e.texture).__webglTexture;console.assert(null!=m,e),e.texture instanceof THREE.DataTexture3D?(p=r.TEXTURE_BINDING_3D,g=r.TEXTURE_3D):e.texture instanceof THREE.DataTexture2DArray&&(p=r.TEXTURE_BINDING_2D_ARRAY,g=r.TEXTURE_2D_ARRAY);let h=r.getParameter(p);r.bindTexture(g,m);performance.mark(`${e.textureType}-start`);r.texSubImage3D(g,0,0,0,i*s,a,n,s,l,r.UNSIGNED_BYTE,d,0);performance.mark(`${e.textureType}-end`);performance.measure(`${e.textureType}-duration`,`${e.textureType}-start`,`${e.textureType}-end`),r.bindTexture(g,h)}async function populateArrayTextureMergedWithWebGL(e,t){return populateArrayTextureSliceWithWebGL(e,{...t,sliceIndex:0,numSlices:1})}function threeFormatToOpenGLFormat(e,t){if(t==THREE.RGBAFormat)return{numChannels:4,glFormat:e.RGBA,glInternalFormat:e.RGBA};if(t==THREE.RGBFormat)return{numChannels:3,glFormat:e.RGB,glInternalFormat:e.RGB};if(t==THREE.LuminanceAlphaFormat)return{numChannels:2,glFormat:e.LUMINANCE_ALPHA,glInternalFormat:e.LUMINANCE_ALPHA};if(t==THREE.RedFormat)return{numChannels:1,glFormat:e.RED,glInternalFormat:e.R8};throw new Error(`Unrecognized three format: ${t}`)}const gPopulateTextureRegistry={scene:populateScene,triplane:populateTriplaneTexture,triplane_rgb:populateArrayTextureWithWebGL,triplane_density:populateArrayTextureWithWebGL,triplane_features:populateArrayTextureWithWebGL,distance_grids:populateOccupancyGridsTexture,distance_grid:populateArrayTextureWithWebGL,occupancy_grids:populateOccupancyGridsTexture,occupancy_grid:populateArrayTextureWithWebGL,sparse_grid:populateSparseGridTexture,sparse_grid_block_indices:populateArrayTextureWithWebGL,sparse_grid_rgb:populateArrayTextureWithWebGL,sparse_grid_density:populateArrayTextureWithWebGL,sparse_grid_features:populateArrayTextureWithWebGL};function populateTexture(e,t){let r=gPopulateTextureRegistry[e.textureType];return null==r&&console.error(`Failed to find loadFn for assetType ${e.textureType}`,e),r(e,t)}const NEEDS_NEW_SUBMODEL=-1,LOADING=0,READY=1;let gSubmodelSceneContents={},gSubmodelCacheSize=10,gRayMarchTextureBuffers=[{si:0,state:-1,texture:null},{si:0,state:-1,texture:null}],gActiveRayMarchTextureBuffer=0,gRayMarchScene=null;function getRayMarchScene(){if(null==gRayMarchScene)throw new Error("gRayMarchScene has not been initialized yet!");return gRayMarchScene}function getActiveSubmodelIndex(){return gRayMarchTextureBuffers[gActiveRayMarchTextureBuffer].si}function getActiveSubmodelContent(){return getSubmodelContent(getActiveSubmodelIndex())}function getSubmodelScale(e){return getSubmodelContent(e).params.submodel_scale}function getSubmodelScaleFactor(e){let t=getSubmodelContent(e);return getSubmodelScale(e)/Math.cbrt(t.params.num_submodels)}function getSubmodelContent(e){return gSubmodelSceneContents[e]}function registerSubmodelContent(e,t){gSubmodelSceneContents[e]=t}function getDeferredMlp(){return console.assert(null!=gDeferredMlp),gDeferredMlp}function registerDeferredMlp(e){validateDeferredMlp(e),gDeferredMlp=e}function getCurrentTextureUsageInBytes(){let e=0;for(rmtb of gRayMarchTextureBuffers)e+=getTextureSizeInBytes(rmtb.texture);return e}function setCurrentRayMarchScene(e){let t=gActiveRayMarchTextureBuffer,r=gRayMarchTextureBuffers[t],a=(t+1)%2,n=gRayMarchTextureBuffers[a];if(null==getSubmodelContent(e))return Promise.resolve();if(getSubmodelContent(e).lastTouched=Date.now(),e==r.si&&r.state>=0)return Promise.resolve();if(e==n.si&&1==n.state){return console.log(`Switching to buffer ${a} for submodel #${e}`),setTextureUniforms(getSubmodelContent(e).params,n.texture),gActiveRayMarchTextureBuffer=a,Promise.resolve()}return n.state>=0&&n.state<1?Promise.resolve():(console.log(`Preparing texture buffer #${a} for submodel #${e}`),n.si=e,n.state=0,Promise.resolve().then((()=>{reinitializeSparseGridTextures(n);let e=getSubmodelContent(n.si);if(null==e.payload){console.log(`Fetching assets for submodel #${n.si}`);let t=prepareTexturePayload(fetchAsset(e.spec,e.router));e.payload=t}return console.log(`Populating textures for submodel #${n.si} into buffer #${a}`),populateTexture(n.texture,e.payload)})).then((()=>{n.state=1,console.log(`Submodel #${n.si} is ready for rendering`),hideLoading()})))}function garbageCollectSubmodelPayloads(){let e=[];for(let t of Object.keys(gSubmodelSceneContents)){let r=getSubmodelContent(t);null!=r.payload&&e.push({lastTouched:r.lastTouched||0,si:t})}e.sort(((e,t)=>e.lastTouched-t.lastTouched));for(let t=0;t{if(null==e)return 0;let t=e.texture.image;return t.height*t.width*t.depth},a=e.occupancyGridsTexture.gridTextures,n=a.length;for(let e=0;e0){t+=1*r(e.distanceGridsTexture.gridTextures[0])}let s=e.triplaneTexture;t+=3*r(s.rgbTexture),t+=1*r(s.densityTexture),t+=4*r(s.featuresTexture);let i=e.sparseGridTexture;return t+=1*r(i.blockIndicesTexture),t+=3*r(i.rgbTexture),t+=1*r(i.densityTexture),t+=4*r(i.featuresTexture),t}async function initializeRayMarchScene(e,t){let r=t.params,a=t.spec,n=kRayMarchFragmentShaderHeader;n+=await loadTextFile("viewdependency.glsl"),n+=await loadTextFile("fragment.glsl"),n=rewriteViewDependenceDefinitions(r,n);let s=new THREE.Matrix3;s.set(-1,0,0,0,0,1,0,1,0);let i=new THREE.Vector3(-2,-2,-2);n="#define kMinPosition vec3("+Number(i.x).toFixed(10)+", "+Number(i.y).toFixed(10)+", "+Number(i.z).toFixed(10)+")\n"+n,n="#define kSubmodelScale "+Number(getSubmodelScale(e)).toFixed(10)+"\n"+n,n="#define kStepMult "+gStepMult+"\n"+n,n="#define kRangeFeaturesMin "+Number(r.range_features[0]).toFixed(10)+"\n"+n,n="#define kRangeFeaturesMax "+Number(r.range_features[1]).toFixed(10)+"\n"+n,n="#define kRangeDensityMin "+Number(r.range_density[0]).toFixed(10)+"\n"+n,n="#define kRangeDensityMax "+Number(r.range_density[1]).toFixed(10)+"\n"+n;let o={bias_0:{value:null},bias_1:{value:null},bias_2:{value:null},weightsZero:{value:null},weightsOne:{value:null},weightsTwo:{value:null},displayMode:{value:gDisplayMode-0},minPosition:{value:i},world_T_cam:{value:new THREE.Matrix4},cam_T_clip:{value:new THREE.Matrix4},worldspaceROpengl:{value:s}};occupancyUniforms={};let l=a.occupancyGridsSpec.gridSpecs,c=l.length;for(let e=0;e{r.onmessage(e)},this.workers.push(e)}this.nextworker=0,this.callbacks={},this.i=0}submit(e,t){const r=this.i;this.callbacks[r]=t,this.i+=1;const a=this.nextworker,n=this.workers[a];this.nextworker=(a+1)%this.workers.length,n.postMessage({i:r,request:e})}onmessage(e){const t=e.data,r=t.i;(0,this.callbacks[r])(t.result),delete this.callbacks[r]}}let gStats=null,gUseSubmodel=!1,gSubmodelTransform=null,gDeferredMlp=null;const DisplayModeType={DISPLAY_NORMAL:0,DISPLAY_DIFFUSE:1,DISPLAY_FEATURES:2,DISPLAY_VIEW_DEPENDENT:3,DISPLAY_COARSE_GRID:4};let gDisplayMode=DisplayModeType.DISPLAY_NORMAL,gBenchmark=!1,gFrameMult=1,gLoadAssetsWorker=new WorkerPool(4,"loadpng.worker.js"),gCopySliceWorker=new WorkerPool(4,"copyslices.worker.js");const kRayMarchVertexShader="\nvarying vec3 vOrigin;\nvarying vec3 vDirection;\nuniform mat4 world_T_cam;\nuniform mat4 cam_T_clip;\n\nvoid main() {\n vec4 posClip = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n gl_Position = posClip;\n posClip /= posClip.w;\n\n vec4 originCam = vec4(0.0, 0.0, 0.0, 1.0);\n vec4 nearPointCam = cam_T_clip * vec4(posClip.x, posClip.y, -1.0, 1.0);\n nearPointCam /= -nearPointCam.z;\n\n vec4 originWorld = world_T_cam * originCam;\n vec4 nearPointWorld = world_T_cam * nearPointCam;\n vOrigin = originWorld.xyz / originWorld.w;\n vDirection = nearPointWorld.xyz / nearPointWorld.w - vOrigin;\n}\n",kRayMarchFragmentShaderHeader="\nprecision highp float;\n\nvarying vec3 vOrigin;\nvarying vec3 vDirection;\n\nuniform int displayMode;\n\nuniform mat3 worldspaceROpengl;\nuniform float nearPlane;\n\n#ifdef USE_DISTANCE_GRID\nuniform highp sampler3D distanceGrid;\nuniform highp sampler3D occupancyGrid_L0;\n#else\nuniform highp sampler3D occupancyGrid_L0;\nuniform highp sampler3D occupancyGrid_L1;\nuniform highp sampler3D occupancyGrid_L2;\n#ifndef USE_BITS\nuniform highp sampler3D occupancyGrid_L3;\nuniform highp sampler3D occupancyGrid_L4;\n#endif\n#endif\n\nuniform vec4 bias_0[NUM_CHANNELS_ONE/4];\nuniform vec4 bias_1[NUM_CHANNELS_TWO/4];\nuniform vec4 bias_2[NUM_CHANNELS_THREE/4];\n\nuniform highp sampler2D weightsZero;\nuniform highp sampler2D weightsOne;\nuniform highp sampler2D weightsTwo;\n\n#ifdef USE_EXPOSURE\nuniform float exposure;\n#endif\n\nuniform vec3 atlasSize;\n\nuniform highp sampler3D sparseGridBlockIndices;\nuniform highp sampler3D sparseGridDensity;\nuniform highp sampler3D sparseGridRgb;\nuniform highp sampler3D sparseGridFeatures;\n\n// need to use texture arrays, otherwise we exceed max texture unit limit\nuniform highp sampler2DArray planeDensity;\nuniform highp sampler2DArray planeRgb;\nuniform highp sampler2DArray planeFeatures;\n";let gRenderer=null,gSubmodelCount=1,gCamera=null,gViewportDims=[640,480],gNumTextures=0,gLoadedTextures=0,gSubmodelForceIndex=-1;function extend(e,t){for(let r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function error(e){const t=document.getElementById("error");t.textContent=e,t.style.display="block"}function create(e,t){const r=document.createElement(e);return t&&(r.className=t),r}function digits(e,t){const r=""+e;return r.length>=t?r:("00000"+r).substr(-t)}function setupViewport(e,t){gViewportDims=[e,t]}function range(e){return[...Array(e).keys()]}function product(e){result=1;for(let t of e)result*=t;return result}function sum(e){result=1;for(let t of e)result+=t;return result}function setDims(e,t,r){e.style.width=t.toFixed(2)+"px",e.style.height=r.toFixed(2)+"px"}function hideLoading(){document.getElementById("Loading").style.display="none",document.getElementById("loading-container").style.display="none"}function showLoading(){document.getElementById("Loading").style.display="none",document.getElementById("loading-container").style.display="none"}function isLoading(){return"none"!==document.getElementById("Loading").style.display}function onImageFetch(e){return gNumTextures++,updateLoadingProgress(),e}function onImageLoaded(e){return gLoadedTextures++,updateLoadingProgress(),e}function updateLoadingProgress(){let e=document.getElementById("image-progress");const t=gNumTextures>0?gNumTextures:"?";e.innerHTML="Loading images: "+gLoadedTextures+"/"+t}function isRendererUnsupported(){let e=document.getElementById("Loading"),t=document.getElementsByTagName("canvas")[0].getContext("webgl2");return t?!t.getExtension("WEBGL_debug_renderer_info")&&(e.innerHTML="Error: Could not fetch renderer info. Is your machine equipped with a discrete GPU?",!0):(e.innerHTML="Error: WebGL2 context not found. Is your machine equipped with a discrete GPU?",!0)}function sleep(e){return new Promise((t=>setTimeout(t,e)))}function submodelAssetPath(e,t){let r="";if(gUseSubmodel){return r=`../sm_${String(e).padStart(3,"0")}`,null==t?r:`${r}/${t}`}return t}function positionToSubmodel(e,t){if(0==gUseSubmodel)return 0;if(gSubmodelForceIndex>=0)return gSubmodelForceIndex;let r=new THREE.Vector3(-e.x,e.z,e.y),a=2/t.submodel_voxel_size,n=r.addScalar(1).divideScalar(2);n=n.multiplyScalar(a);let s=n.floor().clampScalar(0,a-1);const i=(s.x*a+s.y)*a+s.z;return t.sm_to_params[i]}function submodelCenter(e,t){if(0==gUseSubmodel)return new THREE.Vector3(0,0,0);let r=t.submodel_voxel_size,a=2/r,n=t.params_to_sm[e],s=n%a,i=(n-s)/a%a,o=(n-s-i*a)/a/a;return o=a-1-o,[i,s]=[s,i],new THREE.Vector3((o+.5)*r-1,(i+.5)*r-1,(s+.5)*r-1)}function submodelTransform(e,t){const r=submodelCenter(e,t),a=t.submodel_scale;let n=new THREE.Matrix4;n.makeScale(a,a,a);let s=new THREE.Matrix4;return s.makeTranslation(-r.x,-r.y,-r.z),submodel_matrix=new THREE.Matrix4,submodel_matrix.multiplyMatrices(n,s),submodel_matrix}async function fetchAndRetryIfNecessary(e){const t=await e();return 429===t.status?(await sleep(500),fetchAndRetryIfNecessary(e)):t}function loadAsset(e){return new Promise((t=>{gLoadAssetsWorker.submit({url:e},t)}))}function mergeSlices(e,t,r){let a=e.sliceAssets.map((e=>e.asset));return Promise.all(a).then((a=>{let n=range(a.length).map((t=>({...e.sliceAssets[t],asset:a[t]}))),s={asset:{...e,sliceAssets:n},src:t,dst:r,fn:"mergeSlices"};return new Promise((e=>{gCopySliceWorker.submit(s,e)}))}))}function mergeSparseGridDensity(e){let t=e=>Promise.all(e.sliceAssets.map((e=>e.asset))),r=[t(e.rgbAndDensityAsset),t(e.featuresAsset)];return Promise.all(r).then((t=>{let r=t[0],a=t[1],n=(e,t)=>{let r=range(t.length).map((r=>({...e.sliceAssets[r],asset:t[r]})));return{...e,sliceAssets:r}},s=n(e.rgbAndDensityAsset,r),i=n(e.featuresAsset,a),o={asset:{assetType:e.assetType,rgbAndDensityAsset:s,featuresAsset:i},fn:"mergeSparseGridDensity"};return new Promise((e=>{gCopySliceWorker.submit(o,e)}))}))}function getFieldOrDefault(e,t,r){let a=e[t];return null==a?r:a}async function loadTextFile(e){try{const t=cleanPath(e),r=await fetch("http://localhost:3001/generate-signed-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirUrl:t})});if(!r.ok)throw new Error(`Erreur lors de la génération de l'URL signée: ${r.status}`);const{url:a}=await r.json();console.log("Tentative de chargement du fichier texte depuis:",a);const n=await fetch(a);if(!n.ok)throw new Error(`Erreur lors du téléchargement du fichier: ${n.status}`);const s=await n.text();return console.log("Contenu du fichier texte chargé depuis",a,":",s),s}catch(t){throw console.error(`Erreur lors de la récupération du fichier texte depuis ${e}:`,t),t}}async function loadJSONFile(e){try{const t=cleanPath(e),r=await fetch("http://localhost:3001/generate-signed-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dirUrl:t})});if(console.log("Chemin avant génération de l'URL signée:",t),!r.ok)throw new Error(`Erreur lors de la génération de l'URL signée: ${r.status}`);const{url:a}=await r.json();console.log("Tentative de chargement du fichier JSON depuis:",a);const n=await fetch(a);if(!n.ok)throw new Error(`Erreur lors du téléchargement du fichier JSON: ${n.status}`);const s=await n.json();return console.log("Contenu du fichier JSON chargé depuis",a,":",s),s}catch(t){throw console.error(`Erreur lors de la récupération du fichier JSON depuis ${e}:`,t),t}}function cleanPath(e){const t=e.split("/"),r=[];for(let e=0;e0?s.x:n.x,o=t.y>0?s.y:n.y,l=t.z>0?s.z:n.z;i=Math.min(Math.max(i,0),r-1),o=Math.min(Math.max(o,0),r-1),l=Math.min(Math.max(l,0),r-1),i=r-1-i,[o,l]=[l,o];const c=(l*r+o)*r+i;let u=a.x-n.x,d=a.y-n.y,p=a.z-n.z;0==t.x&&(u=1-u),0==t.y&&(d=1-d),0==t.z&&(p=1-p);return[c,u*d*p]}function trilerpDeferredMlpKernel(e,t,r){let a,n,s;if(gDeferredMlp["ResampleDense_"+t+"/kernel"]){const i=gDeferredMlp["ResampleDense_"+t+"/kernel"],o=i.data,l=i.shape[1],c=i.shape[4],u=i.shape[5];a=makeMultipleOf(u,4),n=makeMultipleOf(c,4),s=new Float32Array(n*a);let d=(new THREE.Vector3).copy(r);d.divideScalar(getSubmodelScaleFactor(e));const p=e*l*l*l*c*u;for(let e=0;e<2;e++)for(let t=0;t<2;t++)for(let r=0;r<2;r++){const[i,g]=computeTrilerpLocationsAndWeights(d,new THREE.Vector3(e,t,r),l),m=p+c*u*i;for(let i=0;i{gBenchmark=!0}))}function clearBenchmarkStats(e){document.getElementById("benchmark-stats").innerHTML=""}function addBenchmarkRow(e){document.getElementById("benchmark-stats").innerHTML+=e+"\n"}function getBenchmarkStats(e){return document.getElementById("benchmark-stats").innerHTML}function loadBenchmarkCameras(e){const t=e.translate("test_frames.json"),r=loadJSONFile(t);r.catch((e=>{console.error("Could not load test frames from: "+t+", error: "+e)})),r.then((e=>{gBenchmarkCameras=e.test_frames}))}function setBenchmarkCameraPose(e,t){e.position.fromArray(gBenchmarkCameras[t].position),e.setRotationFromMatrix((new THREE.Matrix4).fromArray(gBenchmarkCameras[t].rotation)),e.projectionMatrix.fromArray(gBenchmarkCameras[t].projection)}function cooldownFrame(e){const t=.5*(1+Math.sin(e*Math.PI/1e3));let r=new THREE.Color("#FFFFFF");r.lerp(new THREE.Color("#A5C0E2"),t),gRenderer.setClearColor(r,1),gRenderer.clear(),gStats&&gStats.update(),gIsCoolingDown&&requestAnimationFrame(cooldownFrame)}function formatTimestampAsString(){const e=new Date,t=e.getHours().toString().padStart(2,"0"),r=e.getMinutes().toString().padStart(2,"0");return`${e.getFullYear()}_${e.getMonth()+1}_${e.getDate()}_${t}${r}`}function benchmarkPerformance(e){const t=Math.max(4,Math.ceil(100/gFrameMult)),r=Math.max(2,Math.ceil(.1*t));if(isLoading())return e;if(!gBenchmarkTimestamps&&!gIsCoolingDown){setBenchmarkCameraPose(gCamera,0),gBenchmarkTimestamps=[];let t=new THREE.Vector2;return gRenderer.getSize(t),clearBenchmarkStats(),addBenchmarkRow(`frame timestamps (ms) at ${t.x}x${t.y}`),addBenchmarkRow("cam_idx ; start ; end ; mean frame time"),e}if(gBenchmarkTimestamps.push(window.performance.now()),gBenchmarkTimestamps.length=gBenchmarkCameras.length){console.log(gFrameTimes.reduce(((e,t)=>e+t),0)/gFrameTimes.length),gBenchmark=!1;const t=new Blob([getBenchmarkStats()],{type:"text/plain;charset=utf-8"}),r="blockmerf_"+gBenchmarkSceneName+"_frameMult_"+gFrameMult+"_"+formatTimestampAsString()+".csv";return saveAs(t,r),e}return gBenchmarkTimestamps=[],setBenchmarkCameraPose(gCamera,gBenchmarkCameraIndex),e}let gSubmodelPanel=null,gVMemPanel=null,gStepMult=1,gExposure=null;function loadScene(e,t){let r;e&&e.includes(".json")?r=loadJSONFile(e):(r=Promise.resolve(null),console.error("dirUrl est null ou non valide. Le fichier Json est dans le dossier")),r.then((r=>{const a=new Router(e,r);console.log("router:",a);const n=a.translate("scene_params.json");console.log("sceneParamsUrl:",n);const s=loadJSONFile(n);return console.log("sceneParamsPromise:",s),t.loadBenchmarkCameras&&loadBenchmarkCameras(a),Promise.all([s,{router:a,filenameToLink:r}])})).then((e=>{const[t,r]=e;let a=0;gUseSubmodel=t.hasOwnProperty("num_local_submodels")&&t.num_local_submodels>1,gUseSubmodel&&(gSubmodelCount=t.num_local_submodels,a=t.sm_to_params[t.submodel_idx]);let n=[];for(let e=0;e{let[a,...n]=r;for(let r=0;rinitializePingPongBuffers(e))).then((()=>requestAnimationFrame(renderNextFrame)))}let disableCameraControls=!1;function initFromParameters(){const e=new URL(window.location.href).searchParams;console.log(e);const t="nyc/sm_004";console.log(t);let r=e.get("quality"),a=parseInt(e.get("downscale")||1,10);const n=e.get("stepMult");n&&(gStepMult=parseInt(n,10));const s=e.get("frameMult");s&&(gFrameMult=parseInt(s,10));const i=e.get("exposure");i&&(gExposure=parseFloat(i));let o={};const l=e.get("benchmark");if(l&&("time"===l.toLowerCase()||"quality"===l.toLowerCase())){o.loadBenchmarkCameras=!0,r="high";const e=t.split("/").slice(-2);setupBenchmarkStats(e[0]+"_"+e[1],"quality"===l.toLowerCase())}const c=e.get("deferredMode");c&&(o.deferred_rendering_mode=c);const u=e.get("combineMode");u&&"concat_and_sum"===u&&(o.merge_features_combine_op="coarse_sum");const d=e.get("useBits");d&&(o.useBits="true"===d.toLowerCase());const p=e.get("useDistanceGrid");p&&(o.useDistanceGrid="true"===p.toLowerCase());const g=e.get("legacyGrids");g&&(o.legacyGrids="true"===g.toLowerCase());const m=e.get("activation");m&&(o.activation=m);const h=e.get("featureGating");h&&(o.feature_gating="true"===h.toLowerCase());const f=e.get("submodelCacheSize");f&&(gSubmodelCacheSize=Number(f));const y=e.get("mergeSlices");y&&(o.merge_slices="true"==y);const _=e.get("backgroundColor");_&&(o.backgroundColor="#"+_);const T=document.createElement("div");T.classList.add("view");document.getElementById("viewspacecontainer").appendChild(T);const{width:x,height:S}=function(e){const t=getComputedStyle(e);return{width:parseInt(t.width,10),height:parseInt(t.height,10)}}(T);T.style.width=`${x}px`,T.style.height=`${S}px`,console.log("Width:",x,"Height:",S);const R=e.get("mouseMode")||"orbit";let E=.99;if(!e.get("downscale")&&r){let e=x*S;for("phone"==r?(e=135e3,E=.8):"low"==r?(e=15e4,E=.8):"medium"==r&&(e=768e3,E=.95);x*S/a>e;)a++;console.log("Automatically chose a downscaling factor of "+a)}o.useLargerStepsWhenOccluded=!1,o.step_size_visibility_delay=E;const b=parseFloat(e.get("near")||.01),C=parseFloat(e.get("vfovy")||40),w=document.querySelector(".viewspace");w.textContent="",w.appendChild(T);let A=document.createElement("canvas");T.appendChild(A),A.style.width="100%",A.style.height="100%",A.style.border=getComputedStyle(T).border,A.style.borderRadius=getComputedStyle(T).borderRadius,A.style.boxSizing=getComputedStyle(T).boxSizing,gStats=Stats(),gStats.dom.style.position="absolute",gStats.dom.style.display="none",w.appendChild(gStats.dom),gSubmodelPanel=gStats.addPanel(new Stats.Panel("SM","#0ff","#002")),gSubmodelPanel.update(getActiveSubmodelIndex()),gVMemPanel=gStats.addPanel(new Stats.Panel("MB VRAM","#0ff","#002")),gVMemPanel.update(0),gStats.showPanel(0);let v=A.getContext("webgl2",{powerPreference:"high-performance",alpha:!1,stencil:!0,precision:"highp",depth:!0,antialias:!1,desynchronized:!1,preserveDrawingBuffer:l&&"quality"===l.toLowerCase()});v.enable(v.DEPTH_TEST),v.depthFunc(v.LEQUAL),v.pixelStorei(v.UNPACK_ALIGNMENT,1),v.viewport(0,0,A.width,A.height),gRenderer=new THREE.WebGLRenderer({canvas:A,context:v}),gCamera=new THREE.PerspectiveCamera(C,Math.trunc(T.offsetWidth/a)/Math.trunc(T.offsetHeight/a),b,2e3),gCamera.updateProjectionMatrix(),window.sceneCamera=gCamera,setupProgressiveRendering(T,a),gRenderer.autoClear=!1,gRenderer.setSize(T.offsetWidth,T.offsetHeight),gRenderer.setClearColor(0,1),setupCameraControls(R,T),setupViewport(Math.trunc(T.offsetWidth/a),Math.trunc(T.offsetHeight/a)),loadScene(t,o)}let sphereAdded=!1;function renderNextFrame(e){garbageCollectSubmodelPayloads();let t=positionToSubmodel(gCamera.position,getActiveSubmodelContent().params);setCurrentRayMarchScene(t),t=getActiveSubmodelIndex();let r=getSubmodelContent(t).params;for(let e=0;e{requestAnimationFrame(renderNextFrame)};gBenchmark&&(a=benchmarkPerformance(a)),a()}function start(){initFromParameters(),addHandlers(),gCamera&&gRenderer?(addInteractionPlane(),setupNewPlaneGizmo(newPlane),setupMouseHover(),window.addEventListener("mousemove",onMouseMove,!1),window.addEventListener("mousedown",onMouseDown,!1),window.addEventListener("mouseup",onMouseUp,!1)):console.error("gCamera ou gRenderer non initialisés.")}window.onload=start;