cesium-heatbox 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import*as e from"cesium";var t={d:(e,i)=>{for(var o in i)t.o(i,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:i[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const i=(l={BoundingSphere:()=>e.BoundingSphere,Cartesian2:()=>e.Cartesian2,Cartesian3:()=>e.Cartesian3,Cartographic:()=>e.Cartographic,Color:()=>e.Color,Ellipsoid:()=>e.Ellipsoid,Entity:()=>e.Entity,HeadingPitchRange:()=>e.HeadingPitchRange,JulianDate:()=>e.JulianDate,LabelStyle:()=>e.LabelStyle,Math:()=>e.Math,Rectangle:()=>e.Rectangle,ScreenSpaceEventHandler:()=>e.ScreenSpaceEventHandler,ScreenSpaceEventType:()=>e.ScreenSpaceEventType,defined:()=>e.defined},d={},t.d(d,l),d),o={voxelSize:20,opacity:.8,emptyOpacity:.03,showOutline:!0,showEmptyVoxels:!1,wireframeOnly:!1,heightBased:!1,outlineWidth:2,minColor:[0,32,255],maxColor:[255,64,0],maxRenderVoxels:5e4,batchMode:"auto",debug:!1,autoVoxelSize:!1,colorMap:"custom",diverging:!1,divergingPivot:0,highlightTopN:null,highlightStyle:{outlineWidth:4,boostOpacity:.2},voxelGap:0,outlineOpacity:1,outlineWidthResolver:null,outlineEmulation:"off",outlineInset:0,outlineInsetMode:"all",enableThickFrames:!1,outlineRenderMode:"standard",emulationScope:"off",adaptiveOutlines:!1,outlineWidthPreset:"medium",boxOpacityResolver:null,outlineOpacityResolver:null,adaptiveParams:{neighborhoodRadius:30,densityThreshold:3,cameraDistanceFactor:.8,overlapRiskFactor:.4,minOutlineWidth:1,maxOutlineWidth:5,outlineWidthRange:null,boxOpacityRange:null,outlineOpacityRange:null,adaptiveOpacityEnabled:!1,zScaleCompensation:!0,overlapDetection:!1},renderLimitStrategy:"density",minCoverageRatio:.2,coverageBinsXY:"auto",autoVoxelSizeMode:"basic",autoVoxelTargetFill:.6,renderBudgetMode:"manual",autoView:!1,fitViewOptions:{paddingPercent:.1,pitchDegrees:-30,headingDegrees:0,altitudeStrategy:"auto"},spatialId:{enabled:!1,mode:"tile-grid",provider:"ouranos-gex",zoom:25,zoomControl:"auto",zoomTolerancePct:10},aggregation:{enabled:!1,byProperty:null,keyResolver:null,showInDescription:!0,topN:10}},n=5e4,a=1e3,r=40075016.68557849,s=(Math.PI,"対象エンティティがありません");var l,d;let c="undefined"!=typeof process&&process.env&&"true"===process.env.DEBUG?3:"undefined"!=typeof process&&process.env?1:3;const u={error(...e){c>=0&&console.error("[Heatbox ERROR]",...e)},warn(...e){c>=1&&console.warn("[Heatbox WARN]",...e)},info(...e){c>=2&&console.log("[Heatbox INFO]",...e)},debug(...e){c>=3&&console.log("[Heatbox DEBUG]",...e)},setLogLevel:e=>(e&&void 0!==e.debug&&("boolean"==typeof e.debug?c=e.debug?3:1:"object"==typeof e.debug&&null!==e.debug&&(c=3)),c)},h=(u.debug,u.warn,u.error,u.info,new Set);function p(e,t){h.has(e)||(h.add(e),u.warn(t))}const m={"mobile-fast":{maxRenderVoxels:5e3,outlineRenderMode:"emulation-only",adaptiveOutlines:!1,outlineWidthPreset:"thin",opacity:.7,renderLimitStrategy:"density",minCoverageRatio:.1,topNHighlight:10,description:"Mobile devices - prioritizes performance over visual quality"},"desktop-balanced":{maxRenderVoxels:15e3,outlineRenderMode:"standard",adaptiveOutlines:!0,outlineWidthPreset:"medium",opacity:.8,renderLimitStrategy:"hybrid",minCoverageRatio:.2,topNHighlight:20,adaptiveParams:{outlineWidthRange:[1,4],outlineOpacityRange:[.4,1],boxOpacityRange:[.2,.8]},description:"Desktop environments - balanced performance and quality"},"dense-data":{maxRenderVoxels:25e3,outlineRenderMode:"inset",adaptiveOutlines:!0,outlineWidthPreset:"thin",opacity:.6,renderLimitStrategy:"hybrid",minCoverageRatio:.3,topNHighlight:30,outlineInset:.5,highlightTopN:!0,highlightStyle:{boostOpacity:.3,boostOutlineWidth:1.5},description:"High-density datasets - optimized for cluttered environments"},"sparse-data":{maxRenderVoxels:8e3,outlineRenderMode:"standard",adaptiveOutlines:!1,outlineWidthPreset:"thick",opacity:.9,renderLimitStrategy:"coverage",minCoverageRatio:.8,topNHighlight:50,emptyOpacity:.05,showEmptyVoxels:!0,description:"Sparse datasets - emphasizes visibility and coverage"}};function g(){return Object.keys(m)}function y(e){return m[e]||null}function f(e,t={}){const i=y(e);if(!i)return t;const{description:o,...n}=i;return x(n,t)}function x(e,t){const i={...e};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]&&"object"==typeof t[e]&&!Array.isArray(t[e])?i[e]=x(i[e]||{},t[e]):i[e]=t[e]);return i}function v(e,t=!1){if(null==e)return t;if("boolean"==typeof e)return e;if("string"==typeof e){const i=e.trim().toLowerCase();return""===i?t:!!["true","1","yes","on"].includes(i)||!["false","0","no","off"].includes(i)&&Boolean(i)}return"number"==typeof e?Number.isFinite(e)?0!==e:t:Boolean(e)}function b(e){return!!Array.isArray(e)&&0!==e.length&&(e.length>5e3&&u.warn(`エンティティ数が推奨値(5000)を超えています: ${e.length}`),!0)}function M(e={}){let t=e;var i;e.profile&&"none"!==e.profile&&("string"==typeof(i=e.profile)&&Object.prototype.hasOwnProperty.call(m,i)?(u.debug(`Applying profile: ${e.profile}`),t=f(e.profile,e),delete t.profile):u.warn(`Invalid profile name: ${e.profile}. Available profiles: mobile-fast, desktop-balanced, dense-data, sparse-data`));const n={...t};if(n.batchMode&&n.debug&&u.warn("batchMode option is deprecated and will be removed in v1.0.0. It is currently ignored."),void 0!==n.voxelSize&&("number"!=typeof(r=n.voxelSize)||isNaN(r)||r<5||r>a))throw new Error(`ボクセルサイズが無効です: ${n.voxelSize}`);var r;if(void 0!==n.opacity&&(n.opacity=Math.max(0,Math.min(1,n.opacity))),void 0!==n.emptyOpacity&&(n.emptyOpacity=Math.max(0,Math.min(1,n.emptyOpacity))),n.minColor&&Array.isArray(n.minColor)&&3===n.minColor.length&&(n.minColor=n.minColor.map(e=>Math.max(0,Math.min(255,Math.floor(e))))),n.maxColor&&Array.isArray(n.maxColor)&&3===n.maxColor.length&&(n.maxColor=n.maxColor.map(e=>Math.max(0,Math.min(255,Math.floor(e))))),void 0!==n.colorMap&&(["custom","viridis","inferno"].includes(n.colorMap)||(u.warn(`Invalid colorMap: ${n.colorMap}. Using 'custom'.`),n.colorMap="custom")),void 0!==n.highlightTopN&&null!==n.highlightTopN&&("number"!=typeof n.highlightTopN||n.highlightTopN<=0)&&(u.warn(`Invalid highlightTopN: ${n.highlightTopN}. Must be a positive number.`),n.highlightTopN=null),void 0!==n.voxelGap&&(n.voxelGap=Math.max(0,Math.min(100,parseFloat(n.voxelGap)||0))),void 0!==n.outlineOpacity&&(n.outlineOpacity=Math.max(0,Math.min(1,parseFloat(n.outlineOpacity)||1))),void 0!==n.outlineWidth){const e=parseFloat(n.outlineWidth);n.outlineWidth=Number.isFinite(e)?Math.max(.5,Math.min(20,e)):o.outlineWidth}if(void 0!==n.wireframeOnly&&(n.wireframeOnly=v(n.wireframeOnly)),void 0!==n.heightBased&&(n.heightBased=v(n.heightBased)),void 0!==n.outlineWidthResolver&&null!==n.outlineWidthResolver&&(p("outlineWidthResolver","[Heatbox][DEPRECATION][v1.0.0] outlineWidthResolver is deprecated; prefer adaptiveOutlines with outlineWidthPreset and adaptiveParams."),"function"!=typeof n.outlineWidthResolver&&(u.warn("outlineWidthResolver must be a function. Ignoring."),n.outlineWidthResolver=null)),void 0!==n.outlineOpacityResolver&&null!==n.outlineOpacityResolver&&(p("outlineOpacityResolver","[Heatbox][DEPRECATION][v1.0.0] outlineOpacityResolver is deprecated; prefer adaptiveOutlines with adaptiveParams.outlineOpacityRange."),"function"!=typeof n.outlineOpacityResolver&&(u.warn("outlineOpacityResolver must be a function. Ignoring."),n.outlineOpacityResolver=null)),void 0!==n.boxOpacityResolver&&null!==n.boxOpacityResolver&&(p("boxOpacityResolver","[Heatbox][DEPRECATION][v1.0.0] boxOpacityResolver is deprecated; prefer adaptiveOutlines with adaptiveParams.boxOpacityRange."),"function"!=typeof n.boxOpacityResolver&&(u.warn("boxOpacityResolver must be a function. Ignoring."),n.boxOpacityResolver=null)),void 0!==n.outlineEmulation&&(void 0===n.outlineRenderMode||"standard"===n.outlineRenderMode)){p("outlineEmulation","[Heatbox][DEPRECATION][v1.0.0] outlineEmulation is deprecated; use outlineRenderMode and emulationScope instead.");const e=n.outlineEmulation;!1===e||"off"===e?(n.outlineRenderMode="standard",n.emulationScope="off"):!0===e||"all"===e?(n.outlineRenderMode="emulation-only",n.emulationScope="all"):"topn"===e?(n.outlineRenderMode="standard",n.emulationScope="topn"):"non-topn"===e?(n.outlineRenderMode="standard",n.emulationScope="non-topn"):(u.warn(`Invalid outlineEmulation: ${e}. Using 'standard' mode.`),n.outlineRenderMode="standard"),delete n.outlineEmulation}if(void 0!==n.outlineWidthPreset){const e=n.outlineWidthPreset,t={uniform:"medium","adaptive-density":"adaptive","topn-focus":"thick"};t[e]&&(p(`outlineWidthPreset.${e}`,`[Heatbox][DEPRECATION][v1.0.0] outlineWidthPreset "${e}" is deprecated; use "${t[e]}".`),n.outlineWidthPreset=t[e])}if(void 0!==n.outlineInset){const e=parseFloat(n.outlineInset);n.outlineInset=isNaN(e)||e<0?0:e}if(void 0!==n.outlineInsetMode){let e=n.outlineInsetMode;"off"===e&&(e="none"),["all","topn","none"].includes(e)?n.outlineInsetMode=e:(u.warn(`Invalid outlineInsetMode: ${n.outlineInsetMode}. Using 'all'.`),n.outlineInsetMode="all")}if(void 0!==n.outlineInset){const e=parseFloat(n.outlineInset);n.outlineInset=Math.max(0,Math.min(100,isNaN(e)?0:e))}if(void 0!==n.outlineInsetMode){let e=n.outlineInsetMode;"off"===e&&(e="none"),["all","topn","none"].includes(e)?n.outlineInsetMode=e:(u.warn(`Invalid outlineInsetMode: ${n.outlineInsetMode}. Using 'all'.`),n.outlineInsetMode="all")}if(void 0!==n.enableThickFrames&&(n.enableThickFrames=v(n.enableThickFrames)),void 0!==n.renderLimitStrategy&&(["density","coverage","hybrid"].includes(n.renderLimitStrategy)||(u.warn(`Invalid renderLimitStrategy: ${n.renderLimitStrategy}. Using 'density'.`),n.renderLimitStrategy="density")),void 0!==n.minCoverageRatio){const e=parseFloat(n.minCoverageRatio);n.minCoverageRatio=isNaN(e)?.2:Math.max(0,Math.min(1,e))}if(void 0!==n.coverageBinsXY){const e=n.coverageBinsXY;if("auto"!==e){const t=parseInt(e,10);!Number.isFinite(t)||t<=0?(u.warn(`Invalid coverageBinsXY: ${e}. Using 'auto'.`),n.coverageBinsXY="auto"):n.coverageBinsXY=t}}if(void 0!==n.autoVoxelSizeMode&&(["basic","occupancy"].includes(n.autoVoxelSizeMode)||(u.warn(`Invalid autoVoxelSizeMode: ${n.autoVoxelSizeMode}. Using 'basic'.`),n.autoVoxelSizeMode="basic")),void 0!==n.autoVoxelTargetFill){const e=parseFloat(n.autoVoxelTargetFill);n.autoVoxelTargetFill=isNaN(e)?.6:Math.max(0,Math.min(1,e))}if(void 0!==n.renderBudgetMode&&(["manual","auto"].includes(n.renderBudgetMode)||(u.warn(`Invalid renderBudgetMode: ${n.renderBudgetMode}. Using 'manual'.`),n.renderBudgetMode="manual")),void 0!==n.fitViewOptions){const e=n.fitViewOptions||{};void 0!==e.pitch&&void 0===e.pitchDegrees&&p("fitViewOptions.pitch","[Heatbox][DEPRECATION][v1.0.0] fitViewOptions.pitch is deprecated; use fitViewOptions.pitchDegrees."),void 0!==e.heading&&void 0===e.headingDegrees&&p("fitViewOptions.heading","[Heatbox][DEPRECATION][v1.0.0] fitViewOptions.heading is deprecated; use fitViewOptions.headingDegrees.");const t=parseFloat(e.paddingPercent),i=void 0!==e.pitchDegrees?parseFloat(e.pitchDegrees):parseFloat(e.pitch),o=void 0!==e.headingDegrees?parseFloat(e.headingDegrees):parseFloat(e.heading),a=e.altitudeStrategy;n.fitViewOptions={paddingPercent:Number.isFinite(t)?Math.max(0,Math.min(1,t)):.1,pitchDegrees:Number.isFinite(i)?Math.max(-90,Math.min(0,i)):-30,headingDegrees:Number.isFinite(o)?o:0,altitudeStrategy:"manual"===a?"manual":"auto"}}const s=n.adaptiveParams?{...n.adaptiveParams}:{};n.adaptiveParams={...o.adaptiveParams,...s};const l=n.adaptiveParams;if(void 0!==s.minOutlineWidth&&void 0!==s.maxOutlineWidth&&void 0===s.outlineWidthRange&&(l.outlineWidthRange=[Math.max(1,parseFloat(s.minOutlineWidth)||1),Math.max(1,parseFloat(s.maxOutlineWidth)||5)],u.debug("adaptiveParams: minOutlineWidth/maxOutlineWidth normalized to outlineWidthRange")),void 0!==l.outlineWidthRange&&Array.isArray(l.outlineWidthRange)){const[e,t]=l.outlineWidthRange;l.outlineWidthRange=[Math.max(1,parseFloat(e)||1),Math.max(1,parseFloat(t)||5)],l.outlineWidthRange[0]>l.outlineWidthRange[1]&&(l.outlineWidthRange=[l.outlineWidthRange[1],l.outlineWidthRange[0]],u.warn("adaptiveParams.outlineWidthRange: min > max detected, swapped values"))}if(void 0!==l.boxOpacityRange&&Array.isArray(l.boxOpacityRange)){const[e,t]=l.boxOpacityRange;l.boxOpacityRange=[Math.max(0,Math.min(1,parseFloat(e)||0)),Math.max(0,Math.min(1,parseFloat(t)||1))],l.boxOpacityRange[0]>l.boxOpacityRange[1]&&(l.boxOpacityRange=[l.boxOpacityRange[1],l.boxOpacityRange[0]],u.warn("adaptiveParams.boxOpacityRange: min > max detected, swapped values"))}if(void 0!==l.outlineOpacityRange&&Array.isArray(l.outlineOpacityRange)){const[e,t]=l.outlineOpacityRange;l.outlineOpacityRange=[Math.max(0,Math.min(1,parseFloat(e)||0)),Math.max(0,Math.min(1,parseFloat(t)||1))],l.outlineOpacityRange[0]>l.outlineOpacityRange[1]&&(l.outlineOpacityRange=[l.outlineOpacityRange[1],l.outlineOpacityRange[0]],u.warn("adaptiveParams.outlineOpacityRange: min > max detected, swapped values"))}if(void 0!==l.overlapDetection&&(l.overlapDetection=v(l.overlapDetection)),void 0!==l.zScaleCompensation&&(l.zScaleCompensation=v(l.zScaleCompensation)),void 0!==l.adaptiveOpacityEnabled&&(l.adaptiveOpacityEnabled=v(l.adaptiveOpacityEnabled)),void 0!==l.neighborhoodRadius){const e=parseFloat(l.neighborhoodRadius);l.neighborhoodRadius=Number.isFinite(e)&&e>0?e:30}if(void 0!==l.densityThreshold){const e=parseFloat(l.densityThreshold);l.densityThreshold=Number.isFinite(e)&&e>0?e:3}if(void 0!==l.cameraDistanceFactor){const e=parseFloat(l.cameraDistanceFactor);l.cameraDistanceFactor=Number.isFinite(e)&&e>0?e:.8}if(void 0!==l.overlapRiskFactor){const e=parseFloat(l.overlapRiskFactor);l.overlapRiskFactor=Number.isFinite(e)?Math.max(0,Math.min(1,e)):.4}if(n.adaptiveParams=l,n.performanceOverlay){const e={...n.performanceOverlay};if(e.enabled=v(e.enabled,!1),e.autoShow=v(e.autoShow,!1),e.autoUpdate=v(e.autoUpdate,!0),e.position=["top-left","top-right","bottom-left","bottom-right"].includes(e.position)?e.position:"top-right",void 0!==e.updateIntervalMs){const t=parseFloat(e.updateIntervalMs);e.updateIntervalMs=Number.isFinite(t)?Math.max(100,t):500}if(void 0!==e.fpsAveragingWindowMs){const t=parseFloat(e.fpsAveragingWindowMs);e.fpsAveragingWindowMs=Number.isFinite(t)?Math.max(200,t):1e3}n.performanceOverlay=e}if(void 0!==t.spatialId){const e="object"==typeof t.spatialId&&null!==t.spatialId?{...t.spatialId}:{};if(e.enabled=v(e.enabled,!1),void 0!==e.mode?"tile-grid"!==e.mode&&(u.warn(`Invalid spatialId.mode: ${e.mode}. Using 'tile-grid'.`),e.mode="tile-grid"):e.mode="tile-grid",void 0!==e.provider?"ouranos-gex"!==e.provider&&(u.warn(`Unknown spatialId.provider: ${e.provider}. Using 'ouranos-gex'.`),e.provider="ouranos-gex"):e.provider="ouranos-gex",void 0!==e.zoom)if("auto"===e.zoom)e.zoom="auto";else{const t=parseInt(e.zoom,10);Number.isNaN(t)||t<0||t>35?(u.warn(`Invalid spatialId.zoom: ${e.zoom}. Using 25.`),e.zoom=25):e.zoom=t}else e.zoom=25;if(void 0!==e.zoomControl?["auto","manual"].includes(e.zoomControl)||(u.warn(`Invalid spatialId.zoomControl: ${e.zoomControl}. Using 'auto'.`),e.zoomControl="auto"):e.zoomControl="auto",void 0!==e.zoomTolerancePct){const t=parseFloat(e.zoomTolerancePct);!Number.isFinite(t)||t<=0||t>100?(u.warn(`Invalid spatialId.zoomTolerancePct: ${e.zoomTolerancePct}. Using 10.`),e.zoomTolerancePct=10):e.zoomTolerancePct=t}else e.zoomTolerancePct=10;n.spatialId=e}else n.spatialId={...o.spatialId};return void 0!==n.aggregation?n.aggregation=function(e){const t={...o.aggregation};if(!e||"object"!=typeof e)return t;if(void 0!==e.enabled&&(t.enabled=v(e.enabled,!1)),void 0!==e.byProperty&&null!==e.byProperty&&("string"==typeof e.byProperty&&""!==e.byProperty.trim()?t.byProperty=e.byProperty.trim():(u.warn("[aggregation] byProperty must be a non-empty string, ignoring"),t.byProperty=null)),void 0!==e.keyResolver&&null!==e.keyResolver&&("function"==typeof e.keyResolver?t.keyResolver=e.keyResolver:(u.warn("[aggregation] keyResolver must be a function, ignoring"),t.keyResolver=null)),void 0!==e.showInDescription&&(t.showInDescription=v(e.showInDescription,!0)),void 0!==e.topN){const i=Number(e.topN);Number.isInteger(i)&&i>0&&i<=100?t.topN=i:(u.warn("[aggregation] topN must be a positive integer <= 100, using default (10)"),t.topN=o.aggregation.topN)}return!t.enabled||t.byProperty||t.keyResolver||u.warn('[aggregation] enabled=true but neither byProperty nor keyResolver is set. Will use default key "default".'),t}(n.aggregation):n.aggregation={...o.aggregation},n}function w(e,t){const i=S(e),o=i.x*i.y*Math.max(i.z,10),n=t/o;let r;return r=n>.001?Math.max(10,Math.min(20,20/Math.sqrt(1e3*n))):n>1e-4?Math.max(20,Math.min(50,50/Math.sqrt(1e4*n))):Math.max(50,Math.min(100,100/Math.sqrt(1e5*n))),r=Math.max(5,Math.min(a,r)),u.debug(`Basic voxel size estimated: ${r}m (density: ${n}, volume: ${o})`),Math.round(r)}function S(e){try{const t={minLat:Number.isFinite(e.minLat)?Math.max(-90,Math.min(90,e.minLat)):0,maxLat:Number.isFinite(e.maxLat)?Math.max(-90,Math.min(90,e.maxLat)):.1,minLon:Number.isFinite(e.minLon)?Math.max(-180,Math.min(180,e.minLon)):0,maxLon:Number.isFinite(e.maxLon)?Math.max(-180,Math.min(180,e.maxLon)):.1,minAlt:Number.isFinite(e.minAlt)?e.minAlt:0,maxAlt:Number.isFinite(e.maxAlt)?e.maxAlt:100};t.maxLat<=t.minLat&&(t.maxLat=t.minLat+.001),t.maxLon<=t.minLon&&(t.maxLon=t.minLon+.001),t.maxAlt<=t.minAlt&&(t.maxAlt=t.minAlt+1);const i=(t.minLat+t.maxLat)/2,o=Math.cos(Math.max(-Math.PI/2,Math.min(Math.PI/2,i*Math.PI/180))),n=111e3*Math.abs(t.maxLon-t.minLon)*Math.abs(o),a=111e3*Math.abs(t.maxLat-t.minLat),r=Math.abs(t.maxAlt-t.minAlt);return{x:Math.max(1,Math.min(1e6,n)),y:Math.max(1,Math.min(1e6,a)),z:Math.max(1,Math.min(1e4,r))}}catch(e){return u.warn("Data range calculation failed:",e),{x:1e3,y:1e3,z:100}}}const R={low:{min:4e3,max:8e3},mid:{min:8e3,max:15e3},high:{min:15e3,max:25e3}};class z{static calculateBounds(e){if(!Array.isArray(e)||0===e.length)throw new Error("エンティティが提供されていません");let t=1/0,o=-1/0,n=1/0,a=-1/0,r=1/0,s=-1/0,l=0;const d=i.JulianDate.now();if(e.forEach((e,c)=>{try{let c,u,h,p;if(e.position&&(c="function"==typeof e.position.getValue?e.position.getValue(d):e.position),!c)return;if("number"==typeof c?.x&&"number"==typeof c?.y&&Math.abs(c.x)<=360&&Math.abs(c.y)<=90)u=c.x,h=c.y,p="number"==typeof c.z?c.z:0;else{const e=i.Cartographic.fromCartesian(c);if(!e)return;u=i.Math.toDegrees(e.longitude),h=i.Math.toDegrees(e.latitude),p=e.height}t=Math.min(t,u),o=Math.max(o,u),n=Math.min(n,h),a=Math.max(a,h),r=Math.min(r,p),s=Math.max(s,p),l++}catch(e){u.warn(`エンティティ ${c} の処理に失敗:`,e)}}),0===l)throw new Error("有効な位置情報を持つエンティティが見つかりません");return u.debug("座標範囲計算完了:",{validCount:l,bounds:{minLon:t,maxLon:o,minLat:n,maxLat:a,minAlt:r,maxAlt:s}}),{minLon:t,maxLon:o,minLat:n,maxLat:a,minAlt:r,maxAlt:s,centerLon:(t+o)/2,centerLat:(n+a)/2,centerAlt:(r+s)/2}}static voxelIndexToCoordinate(e,t,i,o,n){const{minLon:a,maxLon:r,minLat:s,maxLat:l,minAlt:d,maxAlt:c}=o,{numVoxelsX:u,numVoxelsY:h,numVoxelsZ:p}=n;return{lon:a+(e+.5)/u*(r-a),lat:s+(t+.5)/h*(l-s),alt:d+(i+.5)/p*(c-d)}}static coordinateToCartesian3(e,t,o){return i.Cartesian3.fromDegrees(e,t,o)}}class _{static createGrid(e,t){const i=(e.minLat+e.maxLat)/2,o=111e3*(e.maxLon-e.minLon)*Math.cos(i*Math.PI/180),n=111e3*(e.maxLat-e.minLat),a=e.maxAlt-e.minAlt,r=Math.max(1,Math.ceil(o/t)),s=Math.max(1,Math.ceil(n/t)),l=Math.max(1,Math.ceil(a/t)),d=r>0?o/r:t,c=s>0?n/s:t,h=l>0?Math.max(a/l,1):Math.max(t,1),p=r*s*l;return u.debug("VoxelGrid created:",{numVoxelsX:r,numVoxelsY:s,numVoxelsZ:l,totalVoxels:p,voxelSizeMeters:t,cellSizeX:d,cellSizeY:c,cellSizeZ:h,lonRangeMeters:o,latRangeMeters:n,altRangeMeters:a}),{numVoxelsX:r,numVoxelsY:s,numVoxelsZ:l,totalVoxels:p,voxelSizeMeters:t,cellSizeX:d,cellSizeY:c,cellSizeZ:h,lonRangeMeters:o,latRangeMeters:n,altRangeMeters:a}}static getVoxelKey(e,t,i){return`${e},${t},${i}`}static parseVoxelKey(e){const[t,i,o]=e.split(",").map(Number);return{x:t,y:i,z:o}}static iterateAllVoxels(e,t){const{numVoxelsX:i,numVoxelsY:o,numVoxelsZ:n}=e;for(let e=0;e<i;e++)for(let i=0;i<o;i++)for(let o=0;o<n;o++)t(e,i,o,this.getVoxelKey(e,i,o))}}class O{static convert(e,t,i,o){e=O._normalizeLongitude(e),t=O._clampLatitude(t),o=Math.max(0,Math.min(35,Math.floor(o)));const n=Math.pow(2,o),a=Math.floor((e+180)/360*n),r=t*Math.PI/180,s=Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*n),l=O._getAltitudePerBin(o,t),d=Math.floor(i/l);return{zfxy:{z:o,f:d,x:a,y:s},zfxyStr:`/${o}/${d}/${a}/${s}`,vertices:O._calculateVertices(e,t,i,o,a,s,d,l)}}static _normalizeLongitude(e){if(180===e)return-180;for(;e>180;)e-=360;for(;e<-180;)e+=360;return e}static _clampLatitude(e){const t=85.0511287798;return Math.max(-t,Math.min(t,e))}static _getAltitudePerBin(e,t){const i=r,o=Math.max(0,Math.min(35,Math.floor(e))),n=Number.isFinite(t)?t*Math.PI/180:0,a=i*Math.max(Math.cos(n),1e-5)/Math.pow(2,o)*1;return Math.min(5e3,Math.max(.5,a))}static _calculateVertices(e,t,i,o,n,a,r,s){const l=Math.pow(2,o),d=n/l*360-180,c=(n+1)/l*360-180,u=Math.atan(Math.sinh(Math.PI*(1-2*(a+1)/l))),h=Math.atan(Math.sinh(Math.PI*(1-2*a/l))),p=180*u/Math.PI,m=180*h/Math.PI,g=r*s,y=(r+1)*s;return[{lng:d,lat:p,alt:g},{lng:c,lat:p,alt:g},{lng:c,lat:m,alt:g},{lng:d,lat:m,alt:g},{lng:d,lat:p,alt:y},{lng:c,lat:p,alt:y},{lng:c,lat:m,alt:y},{lng:d,lat:m,alt:y}]}static validateZFXY(e){if(!e||"object"!=typeof e)return!1;const{z:t,f:i,x:o,y:n}=e;if(!(Number.isInteger(t)&&Number.isInteger(i)&&Number.isInteger(o)&&Number.isInteger(n)))return!1;if(t<0||t>35)return!1;const a=Math.pow(2,t);return!(o<0||o>=a||n<0||n>=a)}static parseZFXYStr(e){if("string"!=typeof e)return null;const t=e.split("/").filter(e=>e.length>0);if(4!==t.length)return null;const[i,o,n,a]=t.map(e=>parseInt(e,10));if(Number.isNaN(i)||Number.isNaN(o)||Number.isNaN(n)||Number.isNaN(a))return null;const r={z:i,f:o,x:n,y:a};return O.validateZFXY(r)?r:null}}class C{constructor(e={}){this.provider=e.provider||"ouranos-gex",this.Space=null,this.fallbackMode=!1,this.loaded=!1}async loadProvider(){if(this.loaded)return!this.fallbackMode;if("ouranos-gex"!==this.provider)return u.warn(`SpatialIdAdapter: Unknown provider '${this.provider}', using built-in fallback`),this.fallbackMode=!0,this.loaded=!0,!1;try{const e=await Promise.resolve().then(function(){var e=new Error("Cannot find module 'ouranos-gex-lib-for-javascript'");throw e.code="MODULE_NOT_FOUND",e});return this.Space=e.Space,this.fallbackMode=!1,this.loaded=!0,u.info("SpatialIdAdapter: ouranos-gex loaded successfully"),!0}catch(e){return u.warn("SpatialIdAdapter: ouranos-gex not available, using built-in fallback",e.message),this.fallbackMode=!0,this.loaded=!0,!1}}getVoxelBounds(e,t,i,o){if(!this.loaded)throw new Error("SpatialIdAdapter: loadProvider() must be called before getVoxelBounds()");if(!this.Space||this.fallbackMode){const n=O.convert(e,t,i,o);return n.vertices=C._normalizeVertices(n.vertices),n}try{const n=new this.Space({lng:e,lat:t,alt:i},o),a="function"==typeof n.vertices3d?n.vertices3d():[],r=C._normalizeVertices(a);return{zfxy:n.zfxy,zfxyStr:n.zfxyStr,vertices:r}}catch(n){return u.warn("SpatialIdAdapter: ouranos-gex error, falling back to built-in converter",n.message),O.convert(e,t,i,o)}}calculateOptimalZoom(e,t,i=10){let o=25,n=1/0,a=null,r=1/0;for(let s=15;s<=30;s++){const l=this._calculateCellSizeAtZoom(s,t),d=Math.abs(l-e)/e;d<n&&(o=s,n=d),d<=i/100&&d<r&&(a=s,r=d)}const s=null!==a?a:o,l=this._calculateCellSizeAtZoom(s,t),d=Math.abs(l-e)/e*100;return u.debug(`SpatialIdAdapter: Optimal zoom ${s} for target size ${e}m (cell size: ${l.toFixed(1)}m, error: ${d.toFixed(1)}%)${null===a?" [closest, exceeds tolerance]":""}`),s}static _normalizeVertices(e){return Array.isArray(e)?e.map((e,t)=>{if(Array.isArray(e)){const[t,i,o]=e;return{lng:C._toNumber(t),lat:C._toNumber(i),alt:C._toNumber(o)}}if(e&&"object"==typeof e){const t=e.lng??e.lon??e.longitude,i=e.lat??e.latitude,o=e.alt??e.altitude??e.height;return{lng:C._toNumber(t),lat:C._toNumber(i),alt:C._toNumber(o)}}return u.warn("SpatialIdAdapter: Unexpected vertex format from provider",{index:t,vertex:e}),{lng:0,lat:0,alt:0}}):[]}static _toNumber(e){const t=Number(e);return Number.isFinite(t)?t:0}_calculateCellSizeAtZoom(e,t){const i=r,o=t*Math.PI/180;return i*Math.cos(o)/Math.pow(2,e)}getStatus(){return{provider:this.provider,loaded:this.loaded,fallbackMode:this.fallbackMode}}}function V(e,t=i.JulianDate.now()){if(null==e)return e;try{if("function"==typeof e.getValue)return e.getValue(t);if("function"==typeof e.get)return e.get(t)}catch(e){return}return e}class I{static async classifyEntitiesIntoVoxels(e,t,o,n={}){if(n.spatialId?.enabled)return await I._classifyBySpatialId(e,t,o,n);const a=new Map;let r=0,s=0;const l=n.aggregation||{},d=Boolean(l.enabled),c=i.JulianDate.now(),h="string"==typeof l.byProperty&&""!==l.byProperty.trim()?l.byProperty.trim():null,p="function"==typeof l.keyResolver?l.keyResolver:null;let m=null;if(d&&(p||h?m=(e,t)=>{let i;if(p){try{i=p(e)}catch(e){return u.warn(`[aggregation] keyResolver threw error for entity ${t}, using "unknown"`,e),"unknown"}i=V(i,c)}else if(h){let t;try{const i=e.properties?.getValue?.(c);i&&"object"==typeof i&&h in i&&(t=i[h])}catch(e){u.warn(`[aggregation] Failed to resolve PropertyBag for ${h}, fallback to direct property`,e)}if(void 0===t){const i=e.properties?.[h];t=V(i,c)}i=t}if(null==i||"number"==typeof i&&Number.isNaN(i))return"unknown";const o=String(i);return""===o.trim()?"unknown":o}:(u.warn('[aggregation] enabled but no byProperty or keyResolver specified, using "default" key'),m=()=>"default")),u.debug(`Processing ${e.length} entities for classification`),e.forEach((e,n)=>{try{let l,u,h,p;if(e.position&&(l="function"==typeof e.position.getValue?e.position.getValue(c):e.position),!l)return void s++;if("number"==typeof l?.x&&"number"==typeof l?.y&&Math.abs(l.x)<=360&&Math.abs(l.y)<=90)u=l.x,h=l.y,p="number"==typeof l.z?l.z:0;else if(i.Cartographic&&"function"==typeof i.Cartographic.fromCartesian){const e=i.Cartographic.fromCartesian(l);if(!e)return void s++;u=i.Math.toDegrees(e.longitude),h=i.Math.toDegrees(e.latitude),p=e.height}else{if("number"!=typeof l.x||"number"!=typeof l.y)return void s++;u=l.x,h=l.y,p="number"==typeof l.z?l.z:0}if(u<t.minLon-.001||u>t.maxLon+.001||h<t.minLat-.001||h>t.maxLat+.001||p<t.minAlt-1||p>t.maxAlt+1)return void s++;const{x:g,y,z:f}=I._normalizeGridIndices(u,h,p,t,o);if(g>=0&&g<o.numVoxelsX&&y>=0&&y<o.numVoxelsY&&f>=0&&f<o.numVoxelsZ){const t=_.getVoxelKey(g,y,f);if(!a.has(t)){const e={x:g,y,z:f,entities:[],count:0};d&&(e.layerStats=new Map),a.set(t,e)}const i=a.get(t);if(i.entities.push(e),i.count++,d&&m){const t=m(e,n)||"unknown",o=i.layerStats.get(t)||0;i.layerStats.set(t,o+1)}r++}else s++}catch(e){u.warn(`エンティティ ${n} の処理に失敗:`,e),s++}}),d){for(const e of a.values())if(e.layerStats&&e.layerStats.size>0){let t=0,i=null;for(const[o,n]of e.layerStats)n>t&&(t=n,i=o);e.layerTop=i}u.debug(`[aggregation] Calculated layerTop for ${a.size} voxels`)}return u.info(`${r}個のエンティティを${a.size}個のボクセルに分類(${s}個はスキップ)`),a}static calculateStatistics(e,t){if(0===e.size)return{totalVoxels:t.totalVoxels,renderedVoxels:0,nonEmptyVoxels:0,emptyVoxels:t.totalVoxels,totalEntities:0,minCount:0,maxCount:0,averageCount:0,autoAdjusted:!1,originalVoxelSize:null,finalVoxelSize:null,adjustmentReason:null};const i=Array.from(e.values()).map(e=>e.count),o=i.reduce((e,t)=>e+t,0),n=Math.max(0,t.totalVoxels-e.size),a={totalVoxels:t.totalVoxels,renderedVoxels:0,nonEmptyVoxels:e.size,emptyVoxels:n,totalEntities:o,minCount:Math.min(...i),maxCount:Math.max(...i),averageCount:o/e.size,autoAdjusted:!1,originalVoxelSize:null,finalVoxelSize:null,adjustmentReason:null};return u.debug("統計情報計算完了:",a),a}static _normalizeGridIndices(e,t,i,o,n){const a=(e,t,i,o)=>{const n=Number.isFinite(i-t)?i-t:0,a=Number.isFinite(e)?e:t,r=(e=>{const t=Number.isFinite(e)?Math.floor(e):0;return t>0?t:1})(o);if(0===n)return 0;const s=(a-t)/n,l=Math.floor(s*r),d=r-1,c=Number.isFinite(l)?l:0;return Math.max(0,Math.min(d,c))};return{x:a(e,o.minLon,o.maxLon,n.numVoxelsX),y:a(t,o.minLat,o.maxLat,n.numVoxelsY),z:a(i,o.minAlt,o.maxAlt,n.numVoxelsZ)}}static getTopNVoxels(e,t){if(0===e.size||t<=0)return[];const i=Array.from(e.values()).sort((e,t)=>t.count-e.count);return i.slice(0,Math.min(t,i.length))}static async _classifyBySpatialId(e,t,o,n){u.debug(`Spatial ID mode enabled: ${n.spatialId.mode}`);const a=new C({provider:n.spatialId.provider||"ouranos-gex"});let r;await a.loadProvider();const s=(t.minLat+t.maxLat)/2;if("auto"===n.spatialId.zoomControl){const e=n.voxelSize||30,t=n.spatialId.zoomTolerancePct||10;r=a.calculateOptimalZoom(e,s,t),u.info(`Auto-selected zoom level ${r} for target size ${e}m (lat: ${s.toFixed(4)}°)`)}else{const e=n.spatialId.zoom;"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=35?r=Math.floor(e):(r=25,u.warn(`Invalid zoom value in manual mode (${e}), using default zoom level ${r}`)),u.info(`Using manual zoom level ${r}`)}n._resolvedZoom=r,n._spatialIdProvider=a.fallbackMode?null:n.spatialId.provider;const l=n.aggregation||{},d=Boolean(l.enabled),c=i.JulianDate.now(),h="string"==typeof l.byProperty&&""!==l.byProperty.trim()?l.byProperty.trim():null,p="function"==typeof l.keyResolver?l.keyResolver:null;let m=null;d&&(p||h?m=(e,t)=>{let i;if(p){try{i=p(e)}catch(e){return u.warn(`[aggregation] keyResolver threw error for entity ${t}, using "unknown"`,e),"unknown"}i=V(i,c)}else if(h){let t;try{const i=e.properties?.getValue?.(c);i&&"object"==typeof i&&h in i&&(t=i[h])}catch(e){u.warn(`[aggregation] Failed to resolve PropertyBag for ${h}, fallback to direct property`,e)}if(void 0===t){const i=e.properties?.[h];t=V(i,c)}i=t}if(null==i||"number"==typeof i&&Number.isNaN(i))return"unknown";const o=String(i);return""===o.trim()?"unknown":o}:(u.warn('[aggregation] enabled but no byProperty or keyResolver specified, using "default" key'),m=()=>"default"));const g=new Map;let y=0,f=0,x=0;for(const n of e){try{let e,s,l,u;if(n.position&&(e="function"==typeof n.position.getValue?n.position.getValue(c):n.position),!e){f++;continue}if("number"==typeof e?.x&&"number"==typeof e?.y&&Math.abs(e.x)<=360&&Math.abs(e.y)<=90)s=e.x,l=e.y,u="number"==typeof e.z?e.z:0;else if(i.Cartographic&&"function"==typeof i.Cartographic.fromCartesian){const t=i.Cartographic.fromCartesian(e);if(!t){f++;continue}s=i.Math.toDegrees(t.longitude),l=i.Math.toDegrees(t.latitude),u=t.height}else{if("number"!=typeof e.x||"number"!=typeof e.y){f++;continue}s=e.x,l=e.y,u="number"==typeof e.z?e.z:0}const{zfxy:h,zfxyStr:p,vertices:v}=a.getVoxelBounds(s,l,u,r);if(!g.has(p)){const e=v.reduce((e,t)=>e+t.lng,0)/8,i=v.reduce((e,t)=>e+t.lat,0)/8,n=v.reduce((e,t)=>e+t.alt,0)/8,{x:a,y:r,z:s}=I._normalizeGridIndices(e,i,n,t,o),l={key:p,x:a,y:r,z:s,bounds:v,spatialId:{...h,id:p},entities:[],count:0};d&&(l.layerStats=new Map),g.set(p,l)}const b=g.get(p);if(b.entities.push(n),b.count++,d&&m){const e=m(n,x)||"unknown",t=b.layerStats.get(e)||0;b.layerStats.set(e,t+1)}y++}catch(e){u.warn("Failed to process entity for spatial ID:",e),f++}x++}if(d){for(const e of g.values())if(e.layerStats&&e.layerStats.size>0){let t=0,i=null;for(const[o,n]of e.layerStats)n>t&&(t=n,i=o);e.layerTop=i}u.debug(`[aggregation] Calculated layerTop for ${g.size} voxels (Spatial ID mode)`)}return u.info(`Spatial ID: ${y} entities classified into ${g.size} voxels (${f} skipped)`),g}}const A=Object.freeze({viridis:Object.freeze([[68,1,84],[72,40,120],[62,74,137],[49,104,142],[38,130,142],[31,158,137],[53,183,121],[109,205,89],[180,222,44],[253,231,37]]),inferno:Object.freeze([[0,0,4],[31,12,72],[85,15,109],[136,34,106],[186,54,85],[227,89,51],[249,142,8],[252,187,17],[245,219,76],[252,255,164]]),diverging:Object.freeze([[0,0,255],[32,64,255],[64,128,255],[96,160,255],[128,192,255],[160,224,255],[192,240,255],[224,248,255],[255,255,255],[255,248,224],[255,240,192],[255,224,160],[255,192,128],[255,160,96],[255,128,64],[255,64,32],[255,0,0]])});class L{static calculateColor(e,t=null,o={}){try{Number.isFinite(e)||(u.warn(`Invalid normalizedDensity: ${e}. Using 0.5 as fallback.`),e=.5);const{minColor:i=[0,0,255],maxColor:n=[255,0,0],colorMap:a,diverging:r=!1,divergingPivot:s=0}=o;if(r&&null!==t){const e="number"==typeof s?s:0;return L.calculateDivergingColor(t,{divergingPivot:e})}return a&&"custom"!==a?L.interpolateFromColorMap(e,a):L.interpolateLinear(e,i,n)}catch(e){return u.warn(`Color calculation failed: ${e.message}. Falling back to gray.`),i.Color.GRAY}}static interpolateLinear(e,t,o){const n=Math.max(0,Math.min(1,e)),[a,r,s]=t,[l,d,c]=o,u=Math.round(a+(l-a)*n),h=Math.round(r+(d-r)*n),p=Math.round(s+(c-s)*n);return i.Color.fromBytes(u,h,p)}static interpolateFromColorMap(e,t){const o=A[t];if(!o)return u.warn(`Unknown color map: ${t}. Falling back to linear interpolation.`),L.interpolateLinear(e,[0,0,255],[255,0,0]);const n=Math.max(0,Math.min(1,e))*(o.length-1),a=Math.floor(n),r=Math.min(a+1,o.length-1),s=n-a,[l,d,c]=o[a],[h,p,m]=o[r],g=Math.round(l+(h-l)*s),y=Math.round(d+(p-d)*s),f=Math.round(c+(m-c)*s);return i.Color.fromBytes(g,y,f)}static calculateDivergingColor(e,t={}){const{divergingPivot:i=0}=t,o=i;let n;return 0===o?e<0?(n=1/(1-e)*.5,n=Math.max(0,Math.min(.5,n))):e>0?(n=.5+e/(1+e)*.5,n=Math.max(.5,Math.min(1,n))):n=.5:e<=o?(n=e/o*.5,n=Math.max(0,Math.min(.5,n))):(n=.5+(e-o)/o*.5,n=Math.max(.5,Math.min(1,n))),L.interpolateFromColorMap(n,"diverging")}static getAvailableColorMaps(){return Object.keys(A)}static isValidColorMap(e){return Object.hasOwn(A,e)}}class N{constructor(e={}){this.options={renderLimitStrategy:"density",highlightTopN:0,coverageBinsXY:"auto",minCoverageRatio:.2,...e},this._lastSelectionStats=null,u.debug(`VoxelSelector initialized with strategy: ${this.options.renderLimitStrategy}`)}selectVoxels(e,t,i={}){try{if(!Array.isArray(e)||0===e.length)return u.warn("VoxelSelector: Empty or invalid voxel array provided"),this._createEmptyResult();if(t<=0)return u.warn(`VoxelSelector: Invalid maxCount: ${t}`),this._createEmptyResult();if(e.length<=t)return this._createResult(e,this.options.renderLimitStrategy,e.length,0);const{grid:o}=i,n=this.options.renderLimitStrategy||"density",a=this._identifyTopNVoxels(e);let r;switch(n){case"coverage":r=this._selectByCoverageStrategy(e,t,o,a);break;case"hybrid":r=this._selectByHybridStrategy(e,t,o,a);break;default:r=this._selectByDensityStrategy(e,t,a)}return this._lastSelectionStats={strategy:r.strategy,clippedNonEmpty:r.clippedNonEmpty,coverageRatio:r.coverageRatio||null,selectedCount:r.selectedVoxels.length,totalCount:e.length},u.debug(`VoxelSelector: Applied ${r.strategy} strategy - selected ${r.selectedVoxels.length}/${e.length} voxels`),r}catch(i){return u.error(`VoxelSelector: Selection failed: ${i.message}. Falling back to density strategy.`),this._fallbackToDensitySelection(e,t)}}getLastSelectionStats(){return this._lastSelectionStats}_identifyTopNVoxels(e){const t=new Set;if(this.options.highlightTopN&&this.options.highlightTopN>0){const i=[...e].sort((e,t)=>t.info.count-e.info.count).slice(0,this.options.highlightTopN);i.forEach(e=>t.add(e.key)),u.debug(`VoxelSelector: Identified ${i.length} TopN voxels for forced inclusion`)}return t}_selectByDensityStrategy(e,t,i=new Set){const o=[...e].sort((e,t)=>t.info.count-e.info.count),n=[],a=new Set;o.forEach(e=>{i.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))}),o.forEach(e=>{!a.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))});const r=e.length-n.length;return this._createResult(n,"density",n.length,r)}_selectByCoverageStrategy(e,t,i,o=new Set){const n=[],a=new Set;e.forEach(e=>{o.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))});const r="auto"===this.options.coverageBinsXY?Math.ceil(Math.sqrt(t/4)):this.options.coverageBinsXY,s=new Map;e.filter(e=>!a.has(e.key)).forEach(e=>{const t=`${Math.max(0,Math.min(r-1,Math.floor(e.info.x/Math.max(1,i.numVoxelsX)*r)))},${Math.max(0,Math.min(r-1,Math.floor(e.info.y/Math.max(1,i.numVoxelsY)*r)))}`;s.has(t)||s.set(t,[]),s.get(t).push(e)});const l=Array.from(s.keys());let d=0;for(;n.length<t&&d<10*l.length;){const e=l[d%l.length],t=s.get(e);if(t&&t.length>0){t.sort((e,t)=>t.info.count-e.info.count);const i=t.shift();a.has(i.key)||(n.push(i),a.add(i.key)),0===t.length&&(s.delete(e),l.splice(l.indexOf(e),1))}d++}const c=e.length-n.length;return this._createResult(n,"coverage",n.length,c)}_selectByHybridStrategy(e,t,i,o=new Set){const n=this.options.minCoverageRatio||.2,a=[],r=new Set;e.forEach(e=>{o.has(e.key)&&a.length<t&&(a.push(e),r.add(e.key))});const s=t-a.length,l=Math.floor(s*n),d=s-l;l>0&&this._selectByCoverageStrategy(e.filter(e=>!r.has(e.key)),l,i,new Set).selectedVoxels.forEach(e=>{a.length<t&&!r.has(e.key)&&(a.push(e),r.add(e.key))}),d>0&&this._selectByDensityStrategy(e.filter(e=>!r.has(e.key)),d,new Set).selectedVoxels.forEach(e=>{a.length<t&&!r.has(e.key)&&(a.push(e),r.add(e.key))});const c=l>0?(a.length-o.size-d)/(a.length-o.size):0,u=e.length-a.length;return this._createResult(a,"hybrid",a.length,u,c)}_fallbackToDensitySelection(e,t){try{const i=new Set,o=this._selectByDensityStrategy(e,t,i);return o.strategy="density-fallback",this._lastSelectionStats={strategy:o.strategy,clippedNonEmpty:o.clippedNonEmpty,coverageRatio:null,selectedCount:o.selectedVoxels.length,totalCount:e.length,error:!0},o}catch(e){return u.error(`VoxelSelector: Even fallback failed: ${e.message}`),this._createEmptyResult()}}_createResult(e,t,i,o,n=null){return{selectedVoxels:e,strategy:t,clippedNonEmpty:o,coverageRatio:n}}_createEmptyResult(){return{selectedVoxels:[],strategy:"none",clippedNonEmpty:0,coverageRatio:null}}}const F=o.adaptiveParams||{};class ${constructor(e={}){const t={...F,...e.adaptiveParams||{}};this.options={...e,adaptiveParams:t},u.debug("AdaptiveController initialized with options:",this.options)}calculateNeighborhoodDensity(e,t,i=null,o=null){if(!t||"function"!=typeof t.get)return{isDenseArea:!1,neighborhoodDensity:0,neighborCount:0};const{x:n,y:a,z:r}=e,s={...F,...this.options?.adaptiveParams||{},...o?.adaptiveParams||{}},l=s.neighborhoodRadius??F.neighborhoodRadius??30,d=null!==i?i:Math.max(1,Math.floor(l/20));let c=0,u=0;for(let e=-d;e<=d;e++)for(let i=-d;i<=d;i++)for(let o=-d;o<=d;o++){if(0===e&&0===i&&0===o)continue;const s=`${n+e},${a+i},${r+o}`,l=t.get(s);l&&(c+=l.count,u++)}const h=u>0?c/u:0;return{totalDensity:c,neighborCount:u,avgDensity:h,isDenseArea:h>(s.densityThreshold??F.densityThreshold??5),searchRadius:d}}_calculateZScaleCompensation(e,t){const i=this.options.adaptiveParams||F;if(!t||!i.zScaleCompensation)return 1;const{cellSizeX:o,cellSizeY:n,cellSizeZ:a}=t;if(!o||!n||!a)return 1;const r=a/((o+n)/2);return r<.1?Math.max(.7,Math.min(1.3,1+2*(.1-r))):1}_countAdjacentVoxels(e,t){if(!e||!t||"function"!=typeof t.get)return 0;const{x:i,y:o,z:n}=e,a=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];let r=0;for(const[e,s,l]of a){const a=`${i+e},${o+s},${n+l}`;t.get(a)&&r++}return r}_detectOverlapAndRecommendMode(e,t,i=null){const o=i||this.options||{},n={...F,...this.options?.adaptiveParams||{},...i?.adaptiveParams||{}},a=o.outlineRenderMode||"standard",r=o.outlineInset||0;if(!n.overlapDetection)return{recommendedMode:a,recommendedInset:r};const s=this._countAdjacentVoxels(e,t)/6;return s>.5&&"emulation-only"!==a?{recommendedMode:"inset",recommendedInset:Math.max(.3,.8-.4*s),reason:`High overlap risk (${(100*s).toFixed(0)}%)`}:{recommendedMode:a,recommendedInset:r}}applyPresetLogic(e,t,i,o,n){let a,r,s;switch(e){case"thin":a=Math.max(1,.8*n.outlineWidth),r=n.opacity,s=n.outlineOpacity||.8;break;case"medium":case"uniform":default:a=n.outlineWidth,r=n.opacity,s=n.outlineOpacity||1;break;case"thick":a=Math.max(1,1.5*n.outlineWidth),r=n.opacity,s=n.outlineOpacity||1;break;case"adaptive":case"adaptive-density":{const e=o?Math.max(.6,.8+.3*(i-.5)):1;a=Math.max(1,Math.min(3*n.outlineWidth,n.outlineWidth*e)),r=o?.8*n.opacity:n.opacity,s=o?.6:1;break}case"topn-focus":a=t?Math.max(1,Math.min(3*n.outlineWidth,n.outlineWidth*(1.5+.5*i))):Math.max(1,.8*n.outlineWidth),r=t?n.opacity:.6*n.opacity,s=t?1:.4}return{adaptiveWidth:a,adaptiveBoxOpacity:r,adaptiveOutlineOpacity:s}}calculateAdaptiveParams(e,t,i,o,n,a=null){if(!e||!o||!n)return{outlineWidth:null,boxOpacity:null,outlineOpacity:null,shouldUseEmulation:!1};if(!n.adaptiveOutlines)return{outlineWidth:null,boxOpacity:null,outlineOpacity:null,shouldUseEmulation:!1};const{count:r}=e,s=o.maxCount>o.minCount?(r-o.minCount)/(o.maxCount-o.minCount):0,l=this.calculateNeighborhoodDensity(e,i,null,n),{isDenseArea:d}=l,c=this._calculateZScaleCompensation(e,a),u=this._detectOverlapAndRecommendMode(e,i,n),h={...F,...this.options?.adaptiveParams||{},...n?.adaptiveParams||{}},p=h.cameraDistanceFactor??1,m=h.overlapRiskFactor??0,g=Math.min(1,1)*p,y=d?m:0,f=this.applyPresetLogic(n.outlineWidthPreset,t,s,d,n),x=f.adaptiveWidth*g*c,v=Math.max(.2,f.adaptiveOutlineOpacity*(1-y)),b=n&&n.adaptiveParams||h||{},M=(e,t,i,o)=>{let n=e;if(Array.isArray(t)&&2===t.length){const[e,a]=t,r=null!=e?e:i,s=null!=a?a:o;n=Math.min(s??n,Math.max(r??n,n))}return null!=i&&(n=Math.max(i,n)),null!=o&&(n=Math.min(o,n)),n};return{outlineWidth:M(Math.max(1,x),b.outlineWidthRange,h.minOutlineWidth??1,h.maxOutlineWidth??null),boxOpacity:M(Math.max(0,Math.min(1,f.adaptiveBoxOpacity)),b.boxOpacityRange,0,1),outlineOpacity:M(Math.max(.2,Math.min(1,v)),b.outlineOpacityRange,0,1),shouldUseEmulation:d||x>2&&"standard"!==n.outlineRenderMode,_debug:{normalizedDensity:s,neighborhoodResult:l,cameraFactor:g,overlapRisk:y,zScaleFactor:c,overlapRecommendation:u,preset:n.outlineWidthPreset}}}updateOptions(e){this.options={...this.options,...e,adaptiveParams:{...this.options.adaptiveParams,...e.adaptiveParams||{}}},u.debug("AdaptiveController options updated:",this.options)}getConfiguration(){return{...this.options,version:"0.1.11",phase:"ADR-0009 Phase 3"}}}const P={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"},D=/[&<>"'`]/g;function k(e){return"string"!=typeof e?null==e?"":String(e):e.replace(D,e=>P[e]||e)}class E{constructor(e,t={}){this.viewer=e,this.options={wireframeOnly:!1,showOutline:!0,outlineWidth:2,outlineInset:0,outlineInsetMode:"all",outlineRenderMode:"standard",enableThickFrames:!1,...t},this.entities=[],u.debug("GeometryRenderer initialized with viewer and options:",this.options)}createVoxelBox(e){const{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s,color:l,opacity:d,shouldShowOutline:c,outlineColor:h,outlineWidth:p,voxelInfo:m,voxelKey:g,emulateThick:y=!1}=e,f=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,x=Number.isFinite(o)?Math.max(-90,Math.min(90,o)):0,v=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,b=Number.isFinite(a)&&a>0?Math.min(a,1e6):1,M=Number.isFinite(r)&&r>0?Math.min(r,1e6):1,w=Number.isFinite(s)&&s>0?Math.min(s,1e6):1;f===t&&x===o&&v===n&&b===a&&M===r&&w===s||u.warn(`Clamped invalid geometry values for voxel ${g}:`,{original:{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s},clamped:{safeCenterLon:f,safeCenterLat:x,safeCenterAlt:v,safeCellSizeX:b,safeCellSizeY:M,safeBoxHeight:w}});const S=Boolean(c&&!y),R={dimensions:new i.Cartesian3(b,M,w),outline:S};S&&(R.outlineColor=h,R.outlineWidth=Math.max(p||1,1));const z={position:i.Cartesian3.fromDegrees(f,x,v),box:R,properties:{type:"voxel",key:g,count:m.count,x:m.x,y:m.y,z:m.z},description:this.createVoxelDescription(m,g)};if(m.spatialId&&(z.properties.spatialId=m.spatialId),m.layerTop&&(z.properties.layerTop=m.layerTop),m.layerStats){const e={};for(const[t,i]of m.layerStats)e[t]=i;z.properties.layerStats=e}this.options.wireframeOnly||"emulation-only"===this.options.outlineRenderMode?(z.box.material=i.Color.TRANSPARENT,z.box.fill=!1):(z.box.material=l.withAlpha(d),z.box.fill=!0);const _=this.viewer.entities.add(z);return this.entities.push(_),_}createInsetOutline(e){const{centerLon:t,centerLat:o,centerAlt:n,baseSizeX:a,baseSizeY:r,baseSizeZ:s,outlineColor:l,outlineWidth:d,voxelKey:c,insetAmount:h=null}=e,p=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,m=Number.isFinite(o)?Math.max(-90,Math.min(90,o)):0,g=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,y=Number.isFinite(a)&&a>0?Math.min(a,1e6):1,f=Number.isFinite(r)&&r>0?Math.min(r,1e6):1,x=Number.isFinite(s)&&s>0?Math.min(s,1e6):1,v=.2*y,b=.2*f,M=.2*x,w=null!==h?h:this.options.outlineInset,S=Math.min(w,v),R=Math.min(w,b),z=Math.min(w,M),_=Math.max(y-2*S,.1*y),O=Math.max(f-2*R,.1*f),C=Math.max(x-2*z,.1*x),V=this.viewer.entities.add({position:i.Cartesian3.fromDegrees(p,m,g),box:{dimensions:new i.Cartesian3(_,O,C),fill:!1,outline:!0,outlineColor:l,outlineWidth:Math.max(d||1,1)},properties:{type:"voxel-inset-outline",parentKey:c,insetSize:{x:_,y:O,z:C}}});return this.entities.push(V),this.options.enableThickFrames&&(S>.1||R>.1||z>.1)&&this.createThickOutlineFrames({centerLon:p,centerLat:m,centerAlt:g,outerX:y,outerY:f,outerZ:x,innerX:_,innerY:O,innerZ:C,frameColor:l,voxelKey:c}),u.debug(`Inset outline created for voxel ${c}:`,{originalSize:{x:a,y:r,z:s},insetSize:{x:_,y:O,z:C},effectiveInset:{x:S,y:R,z}}),V}createThickOutlineFrames(e){const{centerLon:t,centerLat:o,centerAlt:n,outerX:a,outerY:r,outerZ:s,innerX:l,innerY:d,innerZ:c,frameColor:h,voxelKey:p}=e;let m=(a-l)/2,g=(r-d)/2,y=(s-c)/2;const f=.05;if(m<=0||g<=0||y<=0)return u.warn(`Invalid frame thickness for voxel ${p}, skipping thick frames`),[];m=Math.max(m,f),g=Math.max(g,f),y=Math.max(y,f);const x=a/2,v=r/2,b=s/2,M=[],w=[{x,z:b,sizeX:m,sizeZ:y},{x:-x,z:b,sizeX:m,sizeZ:y},{x,z:-b,sizeX:m,sizeZ:y},{x:-x,z:-b,sizeX:m,sizeZ:y}],S=[{x,y:v,sizeX:m,sizeY:g},{x:-x,y:v,sizeX:m,sizeY:g},{x,y:-v,sizeX:m,sizeY:g},{x:-x,y:-v,sizeX:m,sizeY:g}];return[{y:v,z:b,sizeY:g,sizeZ:y},{y:-v,z:b,sizeY:g,sizeZ:y},{y:v,z:-b,sizeY:g,sizeZ:y},{y:-v,z:-b,sizeY:g,sizeZ:y}].forEach((e,r)=>{const s=i.Cartesian3.fromDegrees(t,o+e.y/111320,n+e.z),l=this.viewer.entities.add({position:s,box:{dimensions:new i.Cartesian3(a,e.sizeY,e.sizeZ),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-x",parentKey:p,frameIndex:r}});this.entities.push(l),M.push(l)}),w.forEach((e,a)=>{const s=i.Cartesian3.fromDegrees(t+e.x/(111320*Math.cos(o*Math.PI/180)),o,n+e.z),l=this.viewer.entities.add({position:s,box:{dimensions:new i.Cartesian3(e.sizeX,r,e.sizeZ),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-y",parentKey:p,frameIndex:a}});this.entities.push(l),M.push(l)}),S.forEach((e,a)=>{const r=i.Cartesian3.fromDegrees(t+e.x/(111320*Math.cos(o*Math.PI/180)),o+e.y/111320,n),l=this.viewer.entities.add({position:r,box:{dimensions:new i.Cartesian3(e.sizeX,e.sizeY,s),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-z",parentKey:p,frameIndex:a}});this.entities.push(l),M.push(l)}),u.debug(`Created ${M.length} thick frame entities for voxel ${p}`),M}createEdgePolylines(e){const{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s,outlineColor:l,outlineWidth:d,voxelKey:c}=e,h=[],p=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,m=Number.isFinite(o)?Math.max(-85,Math.min(85,o)):0,g=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,y=Number.isFinite(a)&&a>0?Math.min(a,1e5):1,f=Number.isFinite(r)&&r>0?Math.min(r,1e5):1,x=Number.isFinite(s)&&s>0?Math.min(s,1e5):1;if(y<.001||f<.001||x<.001)return u.warn(`Dimensions too small for voxel ${c}, skipping edge polylines`),h;const v=y/2,b=f/2,M=x/2,w=Math.cos(m*Math.PI/180),S=v/(111320*Math.max(.1,Math.abs(w))),R=b/111320;if(!Number.isFinite(S)||!Number.isFinite(R)||Math.abs(S)>.1||Math.abs(R)>.1)return u.warn(`Coordinate offsets out of range for voxel ${c}, skipping edge polylines`),h;const z=[[p-S,m-R,g-M],[p+S,m-R,g-M],[p+S,m+R,g-M],[p-S,m+R,g-M],[p-S,m-R,g+M],[p+S,m-R,g+M],[p+S,m+R,g+M],[p-S,m+R,g+M]];if(!z.every(([e,t,i])=>Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(i)&&e>=-180&&e<=180&&t>=-85&&t<=85&&i>=-5e4&&i<=5e5))return u.warn(`Invalid vertex coordinates for voxel ${c}, skipping edge polylines`),h;let _;try{_=z.map(([e,t,o])=>i.Cartesian3.fromDegrees(e,t,o))}catch(e){return u.warn(`Failed to create Cartesian3 vertices for voxel ${c}:`,e),h}return _.every(e=>e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z))?([[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]].forEach((e,t)=>{try{const i=_[e[0]],o=_[e[1]];if(!i||!o)return void u.warn(`Missing vertices for edge ${t} in voxel ${c}`);const n=[i,o];if(2!==n.length)return void u.warn(`Invalid positions array length for edge ${t} in voxel ${c}`);const a=this.viewer.entities.add({polyline:{positions:n,width:Math.max(Math.min(d,20),1),material:l,clampToGround:!1},properties:{type:"voxel-edge-polyline",parentKey:c,edgeIndex:t}});this.entities.push(a),h.push(a)}catch(e){u.warn(`Failed to create polyline for edge ${t} in voxel ${c}:`,e)}}),u.debug(`Created ${h.length} edge polylines for voxel ${c}`),h):(u.warn(`Generated vertices contain invalid values for voxel ${c}, skipping edge polylines`),h)}createVoxelDescription(e,t){const i=e.spatialId?`\n <tr><td><b>空間ID:</b></td><td>${k(e.spatialId.id)}</td></tr>\n <tr><td><b>ズームレベル:</b></td><td>Z=${k(String(e.spatialId.z))}, F=${k(String(e.spatialId.f))}</td></tr>\n <tr><td><b>タイル座標:</b></td><td>X=${k(String(e.spatialId.x))}, Y=${k(String(e.spatialId.y))}</td></tr>\n `:"";let o="";if(this.options.aggregation?.enabled&&!1!==this.options.aggregation?.showInDescription&&e.layerStats&&e.layerStats.size>0){const t=Array.from(e.layerStats.entries()).sort((e,t)=>t[1]-e[1]).map(([t,i])=>{const o=e.count>0?(i/e.count*100).toFixed(1):"0.0";return`\n <tr><td style="padding-left: 10px;">${k(t)}</td><td>${i} (${o}%)</td></tr>\n `}).join("");o=`\n ${e.layerTop?`\n <tr><td><b>支配的レイヤ:</b></td><td>${k(e.layerTop)}</td></tr>\n `:""}\n <tr><td colspan="2"><b>レイヤ内訳:</b></td></tr>\n ${t}\n `}return`\n <div style="padding: 10px; font-family: Arial, sans-serif;">\n <h3 style="margin-top: 0;">ボクセル [${e.x}, ${e.y}, ${e.z}]</h3>\n <table style="width: 100%;">\n <tr><td><b>エンティティ数:</b></td><td>${e.count}</td></tr>\n <tr><td><b>ボクセルキー:</b></td><td>${k(t)}</td></tr>\n <tr><td><b>座標:</b></td><td>X=${e.x}, Y=${e.y}, Z=${e.z}</td></tr>${i}${o}\n </table>\n <p style="margin-bottom: 0;">\n <small>v0.1.18 GeometryRenderer (Layer aggregation support)</small>\n </p>\n </div>\n `}shouldApplyInsetOutline(e){switch(this.options.outlineInsetMode||"all"){case"topn":return e;case"all":default:return!0;case"none":return!1}}clear(){u.debug("GeometryRenderer.clear - Removing",this.entities.length,"entities"),this.entities.forEach(e=>{try{const t=!(!e||"function"!=typeof e.isDestroyed)&&e.isDestroyed();e&&!t&&this.viewer.entities.remove(e)}catch(e){u.warn("Entity removal error:",e)}}),this.entities=[]}renderBoundingBox(e){if(e)try{const t=(e.minLon+e.maxLon)/2,o=(e.minLat+e.maxLat)/2,n=(e.minAlt+e.maxAlt)/2,a=111e3*(e.maxLon-e.minLon)*Math.cos(o*Math.PI/180),r=111e3*(e.maxLat-e.minLat),s=e.maxAlt-e.minAlt,l=this.viewer.entities.add({position:i.Cartesian3.fromDegrees(t,o,n),box:{dimensions:new i.Cartesian3(a,r,s),material:i.Color.YELLOW.withAlpha(.1),outline:!0,outlineColor:i.Color.YELLOW.withAlpha(.3),outlineWidth:2},description:`Bounding Box<br>Size: ${a.toFixed(1)} x ${r.toFixed(1)} x ${s.toFixed(1)} m`});this.entities.push(l),u.debug("Debug bounding box added:",{center:{lon:t,lat:o,alt:n},size:{width:a,depth:r,height:s}})}catch(e){u.warn("Failed to render bounding box:",e)}}getEntityCount(){return this.entities.length}updateOptions(e){this.options={...this.options,...e},u.debug("GeometryRenderer options updated:",this.options)}getConfiguration(){return{...this.options,entityCount:this.entities.length,version:"0.1.11",phase:"ADR-0009 Phase 4"}}}class T{constructor(e,t={}){this.viewer=e,this.options={minColor:[0,0,255],maxColor:[255,0,0],opacity:.8,emptyOpacity:.03,showOutline:!0,showEmptyVoxels:!1,wireframeOnly:!1,heightBased:!1,outlineWidth:2,outlineInset:0,outlineInsetMode:"all",outlineRenderMode:"standard",emulationScope:"off",adaptiveOutlines:!1,outlineWidthPreset:"medium",...t},this.voxelSelector=new N(this.options),this._selectionStats=null,this.adaptiveController=new $(this.options),this.geometryRenderer=new E(this.viewer,this.options),Object.defineProperty(this,"voxelEntities",{get:()=>this.geometryRenderer.entities,enumerable:!0,configurable:!0}),this._currentVoxelData=null,u.debug("VoxelRenderer initialized with options:",this.options)}_calculateAdaptiveParams(e,t,i,o,n){return this.adaptiveController.calculateAdaptiveParams(e,t,i,o,this.options,n)}_shouldApplyInsetOutline(e){return this.geometryRenderer.shouldApplyInsetOutline(e)}render(e,t,i,o){this.geometryRenderer.clear(),u.debug("VoxelRenderer.render - Starting render with simplified approach",{voxelDataSize:e.size,bounds:t,grid:i,statistics:o}),this._currentVoxelData=e,this._shouldShowBounds()&&this.geometryRenderer.renderBoundingBox(t);let n=[];const a=new Set;if(this.options.showEmptyVoxels){const t=Math.min(i.totalVoxels,this.options.maxRenderVoxels||1e4);u.debug(`Generating grid for up to ${t} voxels`);for(let o=0;o<i.numVoxelsX;o++){for(let a=0;a<i.numVoxelsY;a++){for(let r=0;r<i.numVoxelsZ;r++){const i=`${o},${a},${r}`,s=e.get(i)||{x:o,y:a,z:r,count:0};if(n.push({key:i,info:s}),n.length>=t){u.debug(`Reached maximum voxel limit of ${t}`);break}}if(n.length>=t)break}if(n.length>=t)break}}else if(n=Array.from(e.entries()).map(([e,t])=>({key:e,info:t})),this.options.maxRenderVoxels&&n.length>this.options.maxRenderVoxels){const e=this._selectVoxelsForRendering(n,this.options.maxRenderVoxels,t,i);n=e.selectedVoxels,this._selectionStats={strategy:e.strategy,clippedNonEmpty:e.clippedNonEmpty,coverageRatio:e.coverageRatio||0},u.debug(`Applied ${e.strategy} strategy: ${n.length} voxels selected, ${e.clippedNonEmpty} clipped`)}this.options.highlightTopN&&this.options.highlightTopN>0&&([...n].sort((e,t)=>t.info.count-e.info.count).slice(0,this.options.highlightTopN).forEach(e=>a.add(e.key)),u.debug(`TopN highlight enabled: ${a.size} voxels will be highlighted`)),u.debug(`Rendering ${n.length} voxels`);let r=0;const s={x:0,y:0,z:0,count:0},l={voxel:s,isTopN:!1,normalizedDensity:0,statistics:o,adaptiveParams:null},d={voxel:s,isTopN:!1,normalizedDensity:0,statistics:o,adaptiveParams:null};return n.forEach(({key:e,info:n})=>{try{r+=this._renderSingleVoxel(e,n,t,i,o,a,s,l,d)}catch(e){u.warn("Error rendering voxel:",e)}}),u.info(`Successfully rendered ${r} voxels`),this._currentVoxelData=null,r}_renderSingleVoxel(e,t,i,o,n,a,r,s,l){const d=a.has(e),c=this._calculateVoxelRenderingParams(t,i,o,n,d,r,s,l);return c?(this._delegateVoxelRendering(e,c),1):0}_calculateVoxelRenderingParams(e,t,o,n,a,r,s,l){if(!(e&&t&&o&&n))return null;let d,c,u,h,p,m;if(e.bounds&&Array.isArray(e.bounds)&&8===e.bounds.length){const t=e.bounds;d=t.reduce((e,t)=>e+t.lng,0)/8,c=t.reduce((e,t)=>e+t.lat,0)/8,u=t.reduce((e,t)=>e+t.alt,0)/8;const o=i.Cartesian3.fromDegrees(t[0].lng,t[0].lat,t[0].alt),n=i.Cartesian3.fromDegrees(t[1].lng,t[1].lat,t[1].alt),a=i.Cartesian3.fromDegrees(t[3].lng,t[3].lat,t[3].alt),r=i.Cartesian3.fromDegrees(t[4].lng,t[4].lat,t[4].alt);h=i.Cartesian3.distance(o,n),p=i.Cartesian3.distance(o,a),m=i.Cartesian3.distance(o,r)}else{const{x:i,y:n,z:a}=e;d=t.minLon+(i+.5)*(t.maxLon-t.minLon)/o.numVoxelsX,c=t.minLat+(n+.5)*(t.maxLat-t.minLat)/o.numVoxelsY,u=t.minAlt+(a+.5)*(t.maxAlt-t.minAlt)/o.numVoxelsZ,h=o.cellSizeX||(o.lonRangeMeters?o.lonRangeMeters/o.numVoxelsX:o.voxelSizeMeters),p=o.cellSizeY||(o.latRangeMeters?o.latRangeMeters/o.numVoxelsY:o.voxelSizeMeters),m=o.cellSizeZ||(o.altRangeMeters?Math.max(o.altRangeMeters/Math.max(o.numVoxelsZ,1),1):Math.max(o.voxelSizeMeters,1))}const g=n.maxCount>n.minCount?(e.count-n.minCount)/(n.maxCount-n.minCount):0,y=this._calculateAdaptiveParams(e,a,this._currentVoxelData,n,o),{color:f,opacity:x}=this._calculateColorAndOpacity(e,g,a,y,n,r,l);let v,b,M;if(e.bounds){v=h,b=p;let e=m;this.options.voxelGap>0&&(v=Math.max(h-this.options.voxelGap,.1*h),b=Math.max(p-this.options.voxelGap,.1*p),e=Math.max(m-this.options.voxelGap,.1*m)),M=e,this.options.heightBased&&(M=e*(.1+.9*g))}else{const e=this._calculateDimensions(o,g);v=e.cellSizeX,b=e.cellSizeY,M=e.boxHeight}return{centerLon:d,centerLat:c,centerAlt:u,cellSizeX:v,cellSizeY:b,boxHeight:M,color:f,opacity:x,...this._calculateOutlineProperties(e,a,g,y,n,f,r,s),voxelInfo:e,isTopN:a,adaptiveParams:y}}_calculateColorAndOpacity(e,t,o,n,a,r,s){let l,d;if(0===e.count)l=i.Color.LIGHTGRAY,d=this.options.emptyOpacity;else{if(l=L.calculateColor(t,e.count,this.options),this.options.boxOpacityResolver&&"function"==typeof this.options.boxOpacityResolver){r.x=e.x,r.y=e.y,r.z=e.z,r.count=e.count,s.isTopN=o,s.normalizedDensity=t,s.adaptiveParams=n;try{const e=this.options.boxOpacityResolver(s);d=isNaN(e)?this.options.opacity:Math.max(0,Math.min(1,e))}catch(e){u.warn("boxOpacityResolver error, using fallback:",e),d=n.boxOpacity||this.options.opacity}}else d=n.boxOpacity||this.options.opacity;this.options.highlightTopN&&!o&&(d*=1-(this.options.highlightStyle?.boostOpacity||.2))}return{color:l,opacity:d}}_calculateDimensions(e,t){let i=e.cellSizeX||(e.lonRangeMeters?e.lonRangeMeters/e.numVoxelsX:e.voxelSizeMeters),o=e.cellSizeY||(e.latRangeMeters?e.latRangeMeters/e.numVoxelsY:e.voxelSizeMeters),n=e.cellSizeZ||(e.altRangeMeters?Math.max(e.altRangeMeters/Math.max(e.numVoxelsZ,1),1):Math.max(e.voxelSizeMeters,1));this.options.voxelGap>0&&(i=Math.max(i-this.options.voxelGap,.1*i),o=Math.max(o-this.options.voxelGap,.1*o),n=Math.max(n-this.options.voxelGap,.1*n));let a=n;return this.options.heightBased&&(a=n*(.1+.9*t)),{cellSizeX:i,cellSizeY:o,boxHeight:a}}_calculateOutlineProperties(e,t,i,o,n,a,r,s){let l;if(this.options.outlineWidthResolver&&"function"==typeof this.options.outlineWidthResolver){r.x=e.x,r.y=e.y,r.z=e.z,r.count=e.count,s.isTopN=t,s.normalizedDensity=i,s.adaptiveParams=o;try{l=this.options.outlineWidthResolver(s),isNaN(l)&&(l=o.outlineWidth||this.options.outlineWidth)}catch(e){u.warn("outlineWidthResolver error, using fallback:",e),l=o.outlineWidth||this.options.outlineWidth}}else l=this.options.adaptiveOutlines&&null!==o.outlineWidth?o.outlineWidth:t&&this.options.highlightTopN&&this.options.highlightStyle?.outlineWidth||this.options.outlineWidth;const d=o.outlineOpacity||(this.options.outlineOpacity??1),c=a.withAlpha(d),h=this._determineRenderModeConfig();let p=h.shouldUseEmulationOnly;if(!h.shouldUseEmulationOnly){const e=this.options.emulationScope||"off";"topn"===e?p=t&&(l||1)>1:"non-topn"===e?p=!t&&(l||1)>1:"all"===e?p=(l||1)>1:this.options.adaptiveOutlines&&o.shouldUseEmulation&&(p="off"!==e)}return{shouldShowOutline:h.shouldShowStandardOutline,outlineColor:c,outlineWidth:l||1,shouldShowInsetOutline:h.shouldShowInsetOutline,emulateThick:p}}_determineRenderModeConfig(){let e=!0,t=!1,i=!1;switch(this.options.outlineRenderMode){case"standard":e=this.options.showOutline,t=this.options.outlineInset>0;break;case"inset":e=!1,t=!0;break;case"emulation-only":e=!1,t=!1,i=!0}return{shouldShowStandardOutline:e,shouldShowInsetOutline:t,shouldUseEmulationOnly:i}}_delegateVoxelRendering(e,t){if(this.geometryRenderer.createVoxelBox({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,cellSizeX:t.cellSizeX,cellSizeY:t.cellSizeY,boxHeight:t.boxHeight,color:t.color,opacity:t.opacity,shouldShowOutline:t.shouldShowOutline,outlineColor:t.outlineColor,outlineWidth:t.outlineWidth,voxelInfo:t.voxelInfo,voxelKey:e,emulateThick:t.emulateThick}),t.shouldShowInsetOutline&&this.geometryRenderer.shouldApplyInsetOutline(t.isTopN))try{const i=this.options.outlineInset>0?this.options.outlineInset:1;this.geometryRenderer.createInsetOutline({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,baseSizeX:t.cellSizeX,baseSizeY:t.cellSizeY,baseSizeZ:t.boxHeight,outlineColor:t.outlineColor,outlineWidth:Math.max(t.outlineWidth,1),voxelKey:e,insetAmount:i})}catch(e){u.warn("Failed to create inset outline:",e)}if(("emulation-only"===this.options.outlineRenderMode||this.options.emulationScope&&"off"!==this.options.emulationScope)&&t.emulateThick)try{this.geometryRenderer.createEdgePolylines({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,cellSizeX:t.cellSizeX,cellSizeY:t.cellSizeY,boxHeight:t.boxHeight,outlineColor:t.outlineColor,outlineWidth:Math.max(t.outlineWidth,1),voxelKey:e})}catch(e){u.warn("Failed to add emulated thick outline polylines:",e)}}interpolateColor(e,t=null){return L.calculateColor(e,t,this.options)}clear(){this.geometryRenderer.clear()}_shouldShowBounds(){return!!this.options.debug&&("boolean"==typeof this.options.debug?this.options.debug:"object"==typeof this.options.debug&&null!==this.options.debug&&!0===this.options.debug.showBounds)}setVisible(e){u.debug("VoxelRenderer.setVisible:",e),this.voxelEntities.forEach(t=>{!t||t.isDestroyed&&t.isDestroyed()||(t.show=e)})}_selectVoxelsForRendering(e,t,i,o){const n=this.voxelSelector.selectVoxels(e,t,{grid:o,bounds:i});return this._selectionStats=this.voxelSelector.getLastSelectionStats(),n}getSelectionStats(){return this._selectionStats||null}}class W{constructor(e={}){this.options={position:"top-right",fpsAveragingWindowMs:1e3,autoUpdate:!0,...e},this.element=null,this.isVisible=!1,this.updateInterval=null,this.frameTimeHistory=[],this.lastUpdateTime=Date.now(),this._createOverlay()}_createOverlay(){this.element=document.createElement("div"),this.element.id="cesium-heatbox-perf-overlay",this.element.style.cssText=`\n position: absolute;\n ${this._getPositionStyles()}\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n padding: 10px;\n border-radius: 5px;\n font-family: 'Courier New', monospace;\n font-size: 12px;\n line-height: 1.4;\n z-index: 1000;\n min-width: 200px;\n user-select: none;\n pointer-events: auto;\n display: none;\n `;const e=document.createElement("button");e.textContent="×",e.style.cssText="\n position: absolute;\n top: 2px;\n right: 5px;\n background: none;\n border: none;\n color: #fff;\n font-size: 16px;\n cursor: pointer;\n padding: 0;\n width: 20px;\n height: 20px;\n ",e.onclick=()=>this.hide(),this.element.appendChild(e),this.contentElement=document.createElement("div"),this.contentElement.style.marginTop="15px",this.element.appendChild(this.contentElement),document.body.appendChild(this.element)}_getPositionStyles(){const e={"top-left":"top: 10px; left: 10px;","top-right":"top: 10px; right: 10px;","bottom-left":"bottom: 10px; left: 10px;","bottom-right":"bottom: 10px; right: 10px;"};return e[this.options.position]||e["top-right"]}show(){this.element&&(this.element.style.display="block",this.isVisible=!0,this.options.autoUpdate&&this.startAutoUpdate())}hide(){this.element&&(this.element.style.display="none",this.isVisible=!1,this.stopAutoUpdate())}toggle(){this.isVisible?this.hide():this.show()}update(e,t){if(!this.contentElement||!this.isVisible)return;void 0!==t&&this._trackFrameTime(t);const i=this._calculateFPS(),o=this._formatStats(e,i,t);this.contentElement.innerHTML=o}_trackFrameTime(e){const t=Date.now();this.frameTimeHistory.push({time:t,frameTime:e});const i=t-this.options.fpsAveragingWindowMs;this.frameTimeHistory=this.frameTimeHistory.filter(e=>e.time>i)}_calculateFPS(){if(this.frameTimeHistory.length<2)return 0;const e=this.frameTimeHistory.reduce((e,t)=>e+t.frameTime,0)/this.frameTimeHistory.length;return e>0?Math.round(1e3/e):0}_formatStats(e,t,i){const o=[];if(o.push('<div style="font-weight: bold; color: #4CAF50;">🚀 Performance Stats</div>'),o.push(""),t>0){const e=t>=30?"#4CAF50":t>=15?"#FF9800":"#F44336";o.push(`<div style="color: ${e};">FPS: ${t}</div>`)}if(void 0!==i){const e=i<=33?"#4CAF50":i<=66?"#FF9800":"#F44336";o.push(`<div style="color: ${e};">Frame: ${i.toFixed(1)}ms</div>`)}if(o.push(""),e){if(o.push('<div style="font-weight: bold;">Voxels:</div>'),o.push(` Total: ${e.totalVoxels||0}`),o.push(` Rendered: ${e.renderedVoxels||0}`),e.totalVoxels>0){const t=((e.renderedVoxels||0)/e.totalVoxels*100).toFixed(1);o.push(` Ratio: ${t}%`)}if(e.topNCount&&o.push(` TopN: ${e.topNCount}`),o.push(""),e.selectionStrategy&&(o.push('<div style="font-weight: bold;">Strategy:</div>'),o.push(` Selection: ${e.selectionStrategy}`),void 0!==e.coverageRatio&&o.push(` Coverage: ${(100*e.coverageRatio).toFixed(1)}%`),e.renderBudgetTier&&o.push(` Budget Tier: ${e.renderBudgetTier}`),o.push("")),e.adaptive){if(o.push('<div style="font-weight: bold; color: #2196F3;">📊 Adaptive Control:</div>'),void 0!==e.adaptive.denseModeCount){const t=e.renderedVoxels>0?(e.adaptive.denseModeCount/e.renderedVoxels*100).toFixed(1):"0.0";o.push(` Dense Areas: ${e.adaptive.denseModeCount} (${t}%)`)}if(void 0!==e.adaptive.emulationModeCount){const t=e.renderedVoxels>0?(e.adaptive.emulationModeCount/e.renderedVoxels*100).toFixed(1):"0.0";o.push(` Emulation: ${e.adaptive.emulationModeCount} (${t}%)`)}if(void 0!==e.adaptive.avgOutlineWidth){const t=e.adaptive.avgOutlineWidth>=1&&e.adaptive.avgOutlineWidth<=3?"#4CAF50":"#FF9800";o.push(` <span style="color: ${t};">Avg Width: ${e.adaptive.avgOutlineWidth.toFixed(2)}px</span>`)}if(void 0!==e.adaptive.overlapDetections){const t=e.renderedVoxels>0?(e.adaptive.overlapDetections/e.renderedVoxels*100).toFixed(1):"0.0",i=e.adaptive.overlapDetections>0?"#FF9800":"#4CAF50";o.push(` <span style="color: ${i};">Overlaps: ${e.adaptive.overlapDetections} (${t}%)</span>`)}void 0!==e.adaptive.zScaleAdjustments&&e.adaptive.zScaleAdjustments>0&&o.push(` Z-Scale Adj: ${e.adaptive.zScaleAdjustments}`),o.push("")}if(void 0!==e.renderTimeMs){const t=e.renderTimeMs<=50?"#4CAF50":e.renderTimeMs<=100?"#FF9800":"#F44336";o.push(`<div style="color: ${t};">Render Time: ${e.renderTimeMs.toFixed(1)}ms</div>`)}if(void 0!==e.memoryUsageMB){const t=e.memoryUsageMB<=50?"#4CAF50":e.memoryUsageMB<=100?"#FF9800":"#F44336";o.push(`<div style="color: ${t};">Memory: ${e.memoryUsageMB.toFixed(1)}MB</div>`)}}return o.join("<br>")}startAutoUpdate(){this.stopAutoUpdate(),this.updateInterval=setInterval(()=>{},100)}stopAutoUpdate(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){this.stopAutoUpdate(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.contentElement=null}}class B{constructor(e,t={}){if(!function(e){if(!e)return!1;if(!e.scene||!e.entities||!e.scene.canvas)return!1;const t=e.scene.canvas;return!!(t.getContext("webgl2")||t.getContext("webgl")||t.getContext("experimental-webgl"))}(e))throw new Error("CesiumJS Viewerが無効です");this.viewer=e;let i={...t||{}};i.profile&&g().includes(i.profile)&&(i=f(i.profile,i),delete i.profile);const a={...o,...i};this.options=M(function(e){if("auto"!==e.renderBudgetMode&&"auto"!==e.maxRenderVoxels)return e;const t=function(){try{const e=function(){try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return{webgl2:!1,maxTextureSize:0,maxRenderbufferSize:0};const i={webgl2:!!e.getContext("webgl2"),maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:t.getParameter(t.MAX_RENDERBUFFER_SIZE)};return e.remove(),i}catch(e){return u.warn("WebGL info detection failed:",e),{webgl2:!1,maxTextureSize:0,maxRenderbufferSize:0}}}(),t=function(){try{return{deviceMemory:navigator.deviceMemory||null,hardwareConcurrency:navigator.hardwareConcurrency||null,devicePixelRatio:window.devicePixelRatio||1,screenPixels:screen.width*screen.height*Math.pow(window.devicePixelRatio||1,2),userAgent:navigator.userAgent}}catch(e){return u.warn("Device info detection failed:",e),{deviceMemory:null,hardwareConcurrency:null,devicePixelRatio:1,screenPixels:2073600,userAgent:""}}}();let i="mid",o="fallback";if(null!==t.deviceMemory)i=t.deviceMemory<=4?"low":t.deviceMemory<=8?"mid":"high",o="deviceMemory";else if(null!==t.hardwareConcurrency){const e=t.hardwareConcurrency*Math.min(t.screenPixels/2073600,2);i=e<=4?"low":e<=8?"mid":"high",o="hardwareConcurrency+resolution"}(e.maxTextureSize<4096||!e.webgl2)&&(i="high"===i?"mid":"low",o+="+webglLimits");const a=R[i];let r=Math.min(Math.floor((a.min+a.max)/2),n);try{const e=navigator&&navigator.userAgent?navigator.userAgent:"",t=/iPhone|iPad|iPod|Android/i.test(e),i=/Safari\//.test(e)&&!/Chrome\//.test(e);(t||i)&&(r=Math.min(r,12e3))}catch(e){}return u.debug(`Device tier detected: ${i} (${o}), maxRenderVoxels: ${r}`),{tier:i,maxRenderVoxels:r,detectionMethod:o,deviceInfo:t,webglInfo:e}}catch(e){return u.warn("Device tier detection failed, using default mid tier:",e),{tier:"mid",maxRenderVoxels:Math.min(25e3,n),detectionMethod:"error-fallback",deviceInfo:null,webglInfo:null}}}(),i={...e,maxRenderVoxels:t.maxRenderVoxels,_autoRenderBudget:{tier:t.tier,detectionMethod:t.detectionMethod,autoMaxRenderVoxels:t.maxRenderVoxels}};return u.info(`Auto Render Budget applied: ${t.tier} tier, maxRenderVoxels: ${t.maxRenderVoxels}`),i}(a)),u.setLogLevel(this.options),this.renderer=new T(this.viewer,this.options),this._bounds=null,this._grid=null,this._voxelData=null,this._statistics=null,this._eventHandler=null,this._performanceOverlay=null,this._lastRenderTime=null,this._overlayLastUpdate=0,this._postRenderListener=null,this._prevFrameTimestamp=null,this._initializeEventListeners(),this.options.performanceOverlay&&this.options.performanceOverlay.enabled&&this._initializePerformanceOverlay()}getEffectiveOptions(){try{return JSON.parse(JSON.stringify(this.options))}catch(e){return{...this.options}}}static listProfiles(){return g()}static getProfileDetails(e){return y(e)}_initializePerformanceOverlay(){if("undefined"==typeof window)return void u.warn("Performance overlay requires browser environment");const e={position:"top-right",fpsAveragingWindowMs:1e3,autoUpdate:!0,updateIntervalMs:500,...this.options.performanceOverlay};this._performanceOverlay=new W(e),e.autoShow&&this._performanceOverlay.show(),u.debug("Performance overlay initialized"),this._hookPerformanceOverlayUpdates()}togglePerformanceOverlay(){return this._performanceOverlay?(this._performanceOverlay.toggle(),this._performanceOverlay.isVisible):(u.warn("Performance overlay not initialized. Set performanceOverlay.enabled: true in options."),!1)}showPerformanceOverlay(){this._performanceOverlay&&this._performanceOverlay.show()}hidePerformanceOverlay(){this._performanceOverlay&&this._performanceOverlay.hide()}setPerformanceOverlayEnabled(e,t={}){if(e)return this._performanceOverlay?(t&&Object.keys(t).length>0&&(this._performanceOverlay.options={...this._performanceOverlay.options,...t}),this._performanceOverlay.show()):(this.options.performanceOverlay={enabled:!0,...this.options.performanceOverlay||{},...t},this._initializePerformanceOverlay()),!0;if(this._performanceOverlay&&this._performanceOverlay.hide(),this._postRenderListener){try{this.viewer.scene.postRender.removeEventListener(this._postRenderListener)}catch(e){u.debug("postRender listener removal failed (non-fatal)")}this._postRenderListener=null}return!1}_estimateMemoryUsage(){try{const e=this.renderer?.geometryRenderer?.entities?.length||this.renderer?.voxelEntities?.length||0;let t=0;this._voxelData&&(this._voxelData instanceof Map||"number"==typeof this._voxelData.size?t=this._voxelData.size:Array.isArray(this._voxelData)?t=this._voxelData.length:"object"==typeof this._voxelData&&(t=Object.keys(this._voxelData).length));const i=(1024*e+100*t)/1048576;return Math.max(.1,i)}catch(e){return 0}}async setData(e){if(b(e))try{if(u.debug("Heatbox.setData - 処理開始:",e.length,"個のエンティティ"),u.debug("Step 1: 境界計算"),this._bounds=z.calculateBounds(e),!this._bounds)return u.error("境界計算に失敗"),void this.clear();u.debug("境界計算完了:",this._bounds);let t=this.options.voxelSize||o.voxelSize,i=null;if(this.options.autoVoxelSize&&!this.options.voxelSize)try{u.debug("自動ボクセルサイズ調整開始");const o={autoVoxelSizeMode:this.options.autoVoxelSizeMode,autoVoxelTargetFill:this.options.autoVoxelTargetFill,maxRenderVoxels:this.options.maxRenderVoxels},r=function(e,t,i={}){try{return"occupancy"===(i.autoVoxelSizeMode||"basic")?function(e,t,i){const o=S(e),n=i.maxRenderVoxels||5e4,r=i.autoVoxelTargetFill||.6;let s=w(e,t);u.debug(`Starting occupancy-based estimation: N=${t}, target=${r}, maxVoxels=${n}`);for(let i=0;i<10;i++){(!Number.isFinite(s)||s<=0)&&(u.warn(`Invalid currentSize detected: ${s}, using fallback`),s=w(e,t),(!Number.isFinite(s)||s<=0)&&(s=5));const l=Math.max(1,Math.ceil(Math.max(0,o.x)/s))*Math.max(1,Math.ceil(Math.max(0,o.y)/s))*Math.max(1,Math.ceil(Math.max(0,o.z)/s));if(!Number.isFinite(l)||l<=0||l>1e9){u.warn(`Invalid totalVoxels calculated: ${l}, breaking iteration`);break}const d=l*(1-Math.exp(-t/l)),c=Math.min(d/n,1);if(u.debug(`Iteration ${i}: size=${s.toFixed(1)}m, totalVoxels=${l}, expectedOccupied=${d.toFixed(0)}, fill=${c.toFixed(3)}`),Math.abs(c-r)<.05){u.debug(`Converged at iteration ${i}: size=${s.toFixed(1)}m, fill=${c.toFixed(3)}`);break}const h=Math.max(.1,Math.min(10,c/r));s*=Math.pow(h,.3),s=Math.max(5,Math.min(a,s))}const l=Math.round(s);return u.info(`Occupancy-based voxel size: ${l}m (target fill: ${r})`),l}(e,t,i):w(e,t)}catch(e){return u.warn("Initial voxel size estimation failed:",e),20}}(this._bounds,e.length,o),s=_.createGrid(this._bounds,r),l=function(e,t){const i={valid:!0,warning:!1,error:null,recommendedSize:null};if(e>n){i.valid=!1,i.error="ボクセル数が上限を超えています";const o=e/n,r=t*Math.pow(Math.max(1,Math.min(1e3,o)),1/3);i.recommendedSize=Math.ceil(Math.max(5,Math.min(a,r)))}else e>3e4&&(i.warning=!0,i.error="推定メモリ使用量が警告値を超えています");return i}(s.totalVoxels,r);!l.valid&&l.recommendedSize?(t=l.recommendedSize,i={enabled:!0,mode:this.options.autoVoxelSizeMode,originalSize:r,finalSize:t,adjusted:!0,reason:`Performance limit exceeded: ${s.totalVoxels} > 50000`},u.info(`Auto-adjusted voxelSize: ${r}m → ${t}m (${s.totalVoxels} voxels)`)):(t=r,i={enabled:!0,mode:this.options.autoVoxelSizeMode,originalSize:r,finalSize:t,adjusted:!1,reason:null},u.info(`Auto-determined voxelSize: ${t}m`))}catch(e){u.warn("Auto voxel size adjustment failed, using default:",e),t=o.voxelSize,i={enabled:!0,adjusted:!1,reason:"Estimation failed, using default size",originalSize:null,finalSize:t}}u.debug("Step 2: グリッド生成 (サイズ:",t,"m)"),this._grid=_.createGrid(this._bounds,t),u.debug("グリッド生成完了:",this._grid),u.debug("Step 3: エンティティ分類");const r={...this.options,voxelSize:t};this._voxelData=await I.classifyEntitiesIntoVoxels(e,this._bounds,this._grid,r),u.debug("エンティティ分類完了:",this._voxelData.size,"個のボクセル"),u.debug("Step 4: 統計計算"),this._statistics=I.calculateStatistics(this._voxelData,this._grid),u.debug("統計情報:",this._statistics),i&&(this._statistics.autoAdjusted=i.adjusted,this._statistics.originalVoxelSize=i.originalSize,this._statistics.finalVoxelSize=i.finalSize,this._statistics.adjustmentReason=i.reason),r.spatialId?.enabled?(this._statistics.spatialIdEnabled=!0,this._statistics.spatialIdMode=r.spatialId.mode,this._statistics.spatialIdProvider=r._spatialIdProvider||null,this._statistics.spatialIdZoom=r._resolvedZoom||null,this._statistics.zoomControl=r.spatialId.zoomControl):this._statistics.spatialIdEnabled=!1,u.debug("Step 5: 描画");const s="undefined"!=typeof performance&&performance.now?performance.now():Date.now(),l=this.renderer.render(this._voxelData,this._bounds,this._grid,this._statistics),d="undefined"!=typeof performance&&performance.now?performance.now():Date.now();if(this._lastRenderTime=Math.max(0,d-s),this._statistics.renderedVoxels=l,this._statistics.renderTimeMs=this._lastRenderTime,u.info("描画完了 - 実際の描画数:",l),this.options.autoView)try{u.debug("Auto view adjustment triggered"),await this.fitView(),u.debug("Auto view adjustment completed")}catch(e){u.warn("Auto view adjustment failed:",e)}if(u.debug("Heatbox.setData - 処理完了"),this._performanceOverlay&&this._performanceOverlay.isVisible){const e=this.getStatistics()||{};e.renderTimeMs=this._lastRenderTime,e.memoryUsageMB=this._estimateMemoryUsage(),this._performanceOverlay.update(e,void 0)}}catch(e){throw u.error("ヒートマップ作成エラー:",e),this.clear(),e}else this.clear()}async createFromEntities(e){if(!b(e))throw new Error(s);return await this.setData(e),this.getStatistics()}setVisible(e){this.renderer.setVisible(e)}clear(){this.renderer.clear(),this._bounds=null,this._grid=null,this._voxelData=null,this._statistics=null}destroy(){if(this.clear(),this._eventHandler&&!this._eventHandler.isDestroyed()&&this._eventHandler.destroy(),this._postRenderListener){try{this.viewer.scene.postRender.removeEventListener(this._postRenderListener)}catch(e){u.debug("postRender listener removal failed (non-fatal)")}this._postRenderListener=null}if(this._performanceOverlay){try{this._performanceOverlay.destroy()}catch(e){u.debug("overlay destroy failed (non-fatal)")}this._performanceOverlay=null}this._eventHandler=null}dispose(){this.destroy()}getOptions(){return{...this.options}}updateOptions(e){if(this.options=M({...this.options,...e}),this.renderer.options=this.options,this.renderer.adaptiveController&&"function"==typeof this.renderer.adaptiveController.updateOptions&&this.renderer.adaptiveController.updateOptions(this.options),this.renderer.geometryRenderer&&"function"==typeof this.renderer.geometryRenderer.updateOptions&&this.renderer.geometryRenderer.updateOptions(this.options),this._voxelData){const e=this.renderer.render(this._voxelData,this._bounds,this._grid,this._statistics);this._statistics.renderedVoxels=e}}_initializeEventListeners(){this._eventHandler=new i.ScreenSpaceEventHandler(this.viewer.scene.canvas),this._eventHandler.setInputAction(e=>{const t=this.viewer.scene.pick(e.position);if(i.defined(t)&&t.id&&t.id.properties&&"voxel"===t.id.properties.type){const e=t.id.properties.key,o={x:t.id.properties.x,y:t.id.properties.y,z:t.id.properties.z,count:t.id.properties.count},n=new i.Entity({id:`voxel-${e}`,description:this.renderer.createVoxelDescription(o,e)});this.viewer.selectedEntity=n}},i.ScreenSpaceEventType.LEFT_CLICK)}getStatistics(){if(!this._statistics)return null;const e={...this._statistics},t=this.renderer.getSelectionStats();if(t&&(e.selectionStrategy=t.strategy,e.clippedNonEmpty=t.clippedNonEmpty,e.coverageRatio=t.coverageRatio??0),this.options._autoRenderBudget&&(e.renderBudgetTier=this.options._autoRenderBudget.tier,e.autoMaxRenderVoxels=this.options._autoRenderBudget.autoMaxRenderVoxels),"number"==typeof this.options.maxRenderVoxels&&this.options.maxRenderVoxels>0?e.occupancyRatio=Math.min(1,Math.max(0,(e.renderedVoxels||0)/this.options.maxRenderVoxels)):e.occupancyRatio=null,this.options.aggregation?.enabled&&this._voxelData){const t=new Map;for(const e of this._voxelData.values())if(e.layerStats)for(const[i,o]of e.layerStats)t.set(i,(t.get(i)||0)+o);const i=this.options.aggregation?.topN??10,o=Array.from(t.entries()).sort((e,t)=>t[1]-e[1]).slice(0,i);e.layers=o.map(([e,t])=>({key:e,total:t})),u.debug(`[aggregation] Aggregated ${t.size} unique layers, returning top ${e.layers.length}`)}return e}getBounds(){return this._bounds}getDebugInfo(){const e={options:{...this.options},bounds:this._bounds,grid:this._grid,statistics:this._statistics};return this.options.autoVoxelSize&&(e.autoVoxelSizeInfo={enabled:this.options.autoVoxelSize,originalSize:this._statistics?.originalVoxelSize,finalSize:this._statistics?.finalVoxelSize,adjusted:this._statistics?.autoAdjusted||!1,reason:this._statistics?.adjustmentReason,dataRange:this._bounds?S(this._bounds):null,estimatedDensity:this._bounds&&this._statistics?this._statistics.totalEntities/(S(this._bounds).x*S(this._bounds).y*S(this._bounds).z):null}),e}_hookPerformanceOverlayUpdates(){if(!this._performanceOverlay||this._postRenderListener)return;const e=this._performanceOverlay.options?.updateIntervalMs??500;this._postRenderListener=()=>{if(!this._performanceOverlay||!this._performanceOverlay.isVisible)return;const t="undefined"!=typeof performance&&performance.now?performance.now():Date.now();let i;if(null!=this._prevFrameTimestamp&&(i=Math.max(0,t-this._prevFrameTimestamp)),this._prevFrameTimestamp=t,t-this._overlayLastUpdate<e)return;this._overlayLastUpdate=t;const o=this.getStatistics()||{};null!=this._lastRenderTime&&(o.renderTimeMs=this._lastRenderTime),o.memoryUsageMB=this._estimateMemoryUsage();try{this._performanceOverlay.update(o,i)}catch(e){}};try{this.viewer.scene.postRender.addEventListener(this._postRenderListener)}catch(e){}}async fitView(e=null,t={}){try{const i=e||this._bounds;if(!i)return void u.warn("No bounds available for fitView");if(!this._isValidBounds(i))return void u.warn("Invalid bounds provided to fitView:",i);const o={...this.options.fitViewOptions,...t};u.debug("fitView called with bounds:",i,"options:",o);const n={...o};return Number.isFinite(n.pitchDegrees)||(n.pitchDegrees=-35),Number.isFinite(n.headingDegrees)||(n.headingDegrees=0),await new Promise(e=>{let t=!1;const o=async()=>{if(!t){t=!0;try{await this._fitByBoundingSphere(i,n)}catch(e){u.warn("fitView (postRender) failed, trying fallback:",e);try{await this.viewer.zoomTo(this.viewer.entities)}catch(e){u.warn("zoomTo fallback failed:",e)}}finally{try{this.viewer.scene.postRender.removeEventListener(o)}catch(e){u.debug("postRender removeEventListener failed (non-fatal):",e)}e()}}};try{this.viewer.scene.postRender.addEventListener(o)}catch(t){u.warn("postRender addEventListener failed:",t),e()}})}catch(e){throw u.error("fitView failed:",e),e}}async _fitByBoundingSphere(e,t){const o=i.Rectangle.fromDegrees(e.minLon,e.minLat,e.maxLon,e.maxLat),n=i.BoundingSphere.fromRectangle3D(o,i.Ellipsoid.WGS84,Math.max(0,e.minAlt||0)),a=i.Math.toRadians(t.headingDegrees??0),r=Math.max(-85,Math.min(-10,t.pitchDegrees??-35)),s=i.Math.toRadians(r),l=Math.max(2.2*n.radius,1e3);await this.viewer.camera.flyToBoundingSphere(n,{duration:1.2,offset:new i.HeadingPitchRange(a,s,l)})}_isValidBounds(e){return e&&"number"==typeof e.minLon&&!isNaN(e.minLon)&&"number"==typeof e.maxLon&&!isNaN(e.maxLon)&&"number"==typeof e.minLat&&!isNaN(e.minLat)&&"number"==typeof e.maxLat&&!isNaN(e.maxLat)&&"number"==typeof e.minAlt&&!isNaN(e.minAlt)&&"number"==typeof e.maxAlt&&!isNaN(e.maxAlt)&&e.minLon<=e.maxLon&&e.minLat<=e.maxLat&&e.minAlt<=e.maxAlt}async _handleMinimalDataRange(e,t,o,n){u.debug("Handling minimal data range");const a=i.Cartesian3.fromDegrees(e,t,o+2e3),r=i.Math.toRadians(n.headingDegrees||n.heading),s=i.Math.toRadians(n.pitchDegrees||n.pitch);return this.viewer.camera.flyTo({destination:a,orientation:{heading:r,pitch:s,roll:0},duration:1.5})}async _handleLargeDataRange(e,t){u.debug("Handling large data range with bounding sphere");const o=(e.minLon+e.maxLon)/2,n=(e.minLat+e.maxLat)/2,a=(e.minAlt+e.maxAlt)/2,r=S(e),s=Math.max(r.x,r.y,r.z),l=new i.BoundingSphere(i.Cartesian3.fromDegrees(o,n,a),s/2),d=i.Math.toRadians(t.headingDegrees||t.heading),c=i.Math.toRadians(t.pitchDegrees||t.pitch);return this.viewer.camera.flyToBoundingSphere(l,{duration:2.5,offset:new i.HeadingPitchRange(d,c,0)})}_calculateOptimalCameraHeight(e,t,o){if("auto"!==o.altitudeStrategy)return o.altitude||5e3;try{const n=i.Math.toRadians(o.pitchDegrees||o.pitch),a=this.viewer.camera.frustum.fovy||i.Math.toRadians(60),r=(e+t)/(2*Math.tan(a/2)),s=Math.abs(n);let l=r*Math.max(.5,Math.sin(Math.PI/2-s)+.3);const d=e/Math.min(e,100);d>5&&(l*=Math.log10(d)+1);const c=Math.max(500,.1*e),h=Math.min(1e5,10*e);return l=Math.max(c,Math.min(h,l)),u.debug(`Camera height calculated: ${l.toFixed(0)}m (range: ${e.toFixed(0)}m, pitch: ${o.pitchDegrees||o.pitch}°)`),l}catch(t){return u.warn("Camera height calculation failed, using fallback:",t),Math.max(2e3,2*e)}}async _executeCameraMovement(e,t,o,n,a,r,s){try{const l=i.Cartesian3.fromDegrees(e,t,o+n),d=i.Math.toRadians(a.headingDegrees||a.heading),c=i.Math.toRadians(a.pitchDegrees||a.pitch),h={heading:d,pitch:c,roll:0};u.debug(`Camera target: position=${e.toFixed(6)},${t.toFixed(6)},${(o+n).toFixed(0)}, heading=${a.headingDegrees||a.heading}°, pitch=${a.pitchDegrees||a.pitch}°`);const p=Math.max(1,Math.min(3,.8*Math.log10(r))),m=this.viewer.camera.flyTo({destination:l,orientation:h,duration:p,complete:()=>{u.debug("fitView camera movement completed")},cancel:()=>{u.debug("fitView camera movement cancelled")}});if(m)await m;else{u.debug("Using fallback: flyToBoundingSphere");const n=new i.BoundingSphere(i.Cartesian3.fromDegrees(e,t,o),r/2+s);await this.viewer.camera.flyToBoundingSphere(n,{duration:p,offset:new i.HeadingPitchRange(d,c,0)})}u.info("fitView completed successfully")}catch(e){throw u.error("Camera movement execution failed:",e),e}}static filterEntities(e,t){return Array.isArray(e)&&"function"==typeof t?e.filter(t):[]}}function H(e,t,o=500){if(!e)throw new Error("viewer is required");if(!(t&&"minLon"in t&&"maxLon"in t&&"minLat"in t&&"maxLat"in t))throw new Error("bounds must include minLon, maxLon, minLat, maxLat");const n=[],a=t.minAlt||0,r=t.maxAlt||100;for(let s=0;s<o;s++){const o=t.minLon+(t.maxLon-t.minLon)*Math.random(),l=t.minLat+(t.maxLat-t.minLat)*Math.random(),d=a+(r-a)*Math.random(),c=e.entities.add({id:`test-entity-${s}`,position:i.Cartesian3.fromDegrees(o,l,d),point:{pixelSize:5,color:i.Color.YELLOW,outlineColor:i.Color.BLACK,outlineWidth:1},label:{text:`Test ${s}`,font:"10pt sans-serif",pixelOffset:new i.Cartesian2(0,-30),fillColor:i.Color.WHITE,outlineColor:i.Color.BLACK,outlineWidth:1,style:i.LabelStyle.FILL_AND_OUTLINE}});n.push(c)}return n}function Y(e){if(!e||!e.entities)throw new Error("Invalid viewer");return e.entities.values}const X=B,U="0.1.18",j="hiro-nyon",Z="https://github.com/hiro-nyon/cesium-heatbox";function G(e,t){return new B(e,t)}function K(){let e=!1;try{if("undefined"!=typeof WebGLRenderingContext){const t=document.createElement("canvas");e=!(!t.getContext("webgl")&&!t.getContext("experimental-webgl"))}}catch(t){e=!1}return{version:U,cesiumVersion:"undefined"!=typeof Cesium?Cesium.VERSION:"N/A",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"N/A",webglSupport:e,timestamp:(new Date).toISOString()}}u.info(`CesiumJS Heatbox v${U} loaded`);export{j as AUTHOR,B as CesiumHeatbox,B as Heatbox,Z as REPOSITORY,U as VERSION,G as createHeatbox,X as default,H as generateTestEntities,Y as getAllEntities,K as getEnvironmentInfo};
1
+ import*as e from"cesium";var t={d:(e,i)=>{for(var o in i)t.o(i,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:i[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};const i=(l={BoundingSphere:()=>e.BoundingSphere,Cartesian2:()=>e.Cartesian2,Cartesian3:()=>e.Cartesian3,Cartographic:()=>e.Cartographic,Color:()=>e.Color,Ellipsoid:()=>e.Ellipsoid,Entity:()=>e.Entity,HeadingPitchRange:()=>e.HeadingPitchRange,JulianDate:()=>e.JulianDate,LabelStyle:()=>e.LabelStyle,Math:()=>e.Math,Rectangle:()=>e.Rectangle,ScreenSpaceEventHandler:()=>e.ScreenSpaceEventHandler,ScreenSpaceEventType:()=>e.ScreenSpaceEventType,defined:()=>e.defined},d={},t.d(d,l),d),o={voxelSize:20,opacity:.8,emptyOpacity:.03,showOutline:!0,showEmptyVoxels:!1,wireframeOnly:!1,heightBased:!1,outlineWidth:2,minColor:[0,32,255],maxColor:[255,64,0],maxRenderVoxels:5e4,batchMode:"auto",debug:!1,autoVoxelSize:!1,colorMap:"custom",diverging:!1,divergingPivot:0,highlightTopN:null,highlightStyle:{outlineWidth:4,boostOpacity:.2},voxelGap:0,outlineOpacity:1,outlineWidthResolver:null,outlineEmulation:"off",outlineInset:0,outlineInsetMode:"all",enableThickFrames:!1,outlineRenderMode:"standard",emulationScope:"off",adaptiveOutlines:!1,outlineWidthPreset:"medium",boxOpacityResolver:null,outlineOpacityResolver:null,adaptiveParams:{neighborhoodRadius:30,densityThreshold:3,cameraDistanceFactor:.8,overlapRiskFactor:.4,minOutlineWidth:1,maxOutlineWidth:5,outlineWidthRange:null,boxOpacityRange:null,outlineOpacityRange:null,adaptiveOpacityEnabled:!1,zScaleCompensation:!0,overlapDetection:!1},renderLimitStrategy:"density",minCoverageRatio:.2,coverageBinsXY:"auto",autoVoxelSizeMode:"basic",autoVoxelTargetFill:.6,renderBudgetMode:"manual",autoView:!1,fitViewOptions:{paddingPercent:.1,pitchDegrees:-30,headingDegrees:0,altitudeStrategy:"auto"},spatialId:{enabled:!1,mode:"tile-grid",provider:"ouranos-gex",zoom:25,zoomControl:"auto",zoomTolerancePct:10},aggregation:{enabled:!1,byProperty:null,keyResolver:null,showInDescription:!0,topN:10}},n=5e4,a=1e3,r=40075016.68557849,s=(Math.PI,"対象エンティティがありません");var l,d;let c="undefined"!=typeof process&&process.env&&"true"===process.env.DEBUG?3:"undefined"!=typeof process&&process.env?1:3;const u={error(...e){c>=0&&console.error("[Heatbox ERROR]",...e)},warn(...e){c>=1&&console.warn("[Heatbox WARN]",...e)},info(...e){c>=2&&console.log("[Heatbox INFO]",...e)},debug(...e){c>=3&&console.log("[Heatbox DEBUG]",...e)},setLogLevel:e=>(e&&void 0!==e.debug&&("boolean"==typeof e.debug?c=e.debug?3:1:"object"==typeof e.debug&&null!==e.debug&&(c=3)),c)},h=(u.debug,u.warn,u.error,u.info,new Set);function p(e,t){h.has(e)||(h.add(e),u.warn(t))}const m={"mobile-fast":{maxRenderVoxels:5e3,outlineRenderMode:"emulation-only",adaptiveOutlines:!1,outlineWidthPreset:"thin",opacity:.7,renderLimitStrategy:"density",minCoverageRatio:.1,topNHighlight:10,description:"Mobile devices - prioritizes performance over visual quality"},"desktop-balanced":{maxRenderVoxels:15e3,outlineRenderMode:"standard",adaptiveOutlines:!0,outlineWidthPreset:"medium",opacity:.8,renderLimitStrategy:"hybrid",minCoverageRatio:.2,topNHighlight:20,adaptiveParams:{outlineWidthRange:[1,4],outlineOpacityRange:[.4,1],boxOpacityRange:[.2,.8]},description:"Desktop environments - balanced performance and quality"},"dense-data":{maxRenderVoxels:25e3,outlineRenderMode:"inset",adaptiveOutlines:!0,outlineWidthPreset:"thin",opacity:.6,renderLimitStrategy:"hybrid",minCoverageRatio:.3,topNHighlight:30,outlineInset:.5,highlightTopN:!0,highlightStyle:{boostOpacity:.3,boostOutlineWidth:1.5},description:"High-density datasets - optimized for cluttered environments"},"sparse-data":{maxRenderVoxels:8e3,outlineRenderMode:"standard",adaptiveOutlines:!1,outlineWidthPreset:"thick",opacity:.9,renderLimitStrategy:"coverage",minCoverageRatio:.8,topNHighlight:50,emptyOpacity:.05,showEmptyVoxels:!0,description:"Sparse datasets - emphasizes visibility and coverage"}};function g(){return Object.keys(m)}function y(e){return m[e]||null}function f(e,t={}){const i=y(e);if(!i)return t;const{description:o,...n}=i;return x(n,t)}function x(e,t){const i={...e};for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]&&"object"==typeof t[e]&&!Array.isArray(t[e])?i[e]=x(i[e]||{},t[e]):i[e]=t[e]);return i}function v(e,t=!1){if(null==e)return t;if("boolean"==typeof e)return e;if("string"==typeof e){const i=e.trim().toLowerCase();return""===i?t:!!["true","1","yes","on"].includes(i)||!["false","0","no","off"].includes(i)&&Boolean(i)}return"number"==typeof e?Number.isFinite(e)?0!==e:t:Boolean(e)}function b(e){return!!Array.isArray(e)&&0!==e.length&&(e.length>5e3&&u.warn(`エンティティ数が推奨値(5000)を超えています: ${e.length}`),!0)}function M(e={}){let t=e;var i;e.profile&&"none"!==e.profile&&("string"==typeof(i=e.profile)&&Object.prototype.hasOwnProperty.call(m,i)?(u.debug(`Applying profile: ${e.profile}`),t=f(e.profile,e),delete t.profile):u.warn(`Invalid profile name: ${e.profile}. Available profiles: mobile-fast, desktop-balanced, dense-data, sparse-data`));const n={...t};if(n.batchMode&&n.debug&&u.warn("batchMode option is deprecated and will be removed in v1.0.0. It is currently ignored."),void 0!==n.voxelSize&&("number"!=typeof(r=n.voxelSize)||isNaN(r)||r<5||r>a))throw new Error(`ボクセルサイズが無効です: ${n.voxelSize}`);var r;if(void 0!==n.opacity&&(n.opacity=Math.max(0,Math.min(1,n.opacity))),void 0!==n.emptyOpacity&&(n.emptyOpacity=Math.max(0,Math.min(1,n.emptyOpacity))),n.minColor&&Array.isArray(n.minColor)&&3===n.minColor.length&&(n.minColor=n.minColor.map(e=>Math.max(0,Math.min(255,Math.floor(e))))),n.maxColor&&Array.isArray(n.maxColor)&&3===n.maxColor.length&&(n.maxColor=n.maxColor.map(e=>Math.max(0,Math.min(255,Math.floor(e))))),void 0!==n.colorMap&&(["custom","viridis","inferno"].includes(n.colorMap)||(u.warn(`Invalid colorMap: ${n.colorMap}. Using 'custom'.`),n.colorMap="custom")),void 0!==n.highlightTopN&&null!==n.highlightTopN&&("number"!=typeof n.highlightTopN||n.highlightTopN<=0)&&(u.warn(`Invalid highlightTopN: ${n.highlightTopN}. Must be a positive number.`),n.highlightTopN=null),void 0!==n.voxelGap&&(n.voxelGap=Math.max(0,Math.min(100,parseFloat(n.voxelGap)||0))),void 0!==n.outlineOpacity&&(n.outlineOpacity=Math.max(0,Math.min(1,parseFloat(n.outlineOpacity)||1))),void 0!==n.outlineWidth){const e=parseFloat(n.outlineWidth);n.outlineWidth=Number.isFinite(e)?Math.max(.5,Math.min(20,e)):o.outlineWidth}if(void 0!==n.wireframeOnly&&(n.wireframeOnly=v(n.wireframeOnly)),void 0!==n.heightBased&&(n.heightBased=v(n.heightBased)),void 0!==n.outlineWidthResolver&&null!==n.outlineWidthResolver&&(p("outlineWidthResolver","[Heatbox][DEPRECATION][v1.0.0] outlineWidthResolver is deprecated; prefer adaptiveOutlines with outlineWidthPreset and adaptiveParams."),"function"!=typeof n.outlineWidthResolver&&(u.warn("outlineWidthResolver must be a function. Ignoring."),n.outlineWidthResolver=null)),void 0!==n.outlineOpacityResolver&&null!==n.outlineOpacityResolver&&(p("outlineOpacityResolver","[Heatbox][DEPRECATION][v1.0.0] outlineOpacityResolver is deprecated; prefer adaptiveOutlines with adaptiveParams.outlineOpacityRange."),"function"!=typeof n.outlineOpacityResolver&&(u.warn("outlineOpacityResolver must be a function. Ignoring."),n.outlineOpacityResolver=null)),void 0!==n.boxOpacityResolver&&null!==n.boxOpacityResolver&&(p("boxOpacityResolver","[Heatbox][DEPRECATION][v1.0.0] boxOpacityResolver is deprecated; prefer adaptiveOutlines with adaptiveParams.boxOpacityRange."),"function"!=typeof n.boxOpacityResolver&&(u.warn("boxOpacityResolver must be a function. Ignoring."),n.boxOpacityResolver=null)),void 0!==n.outlineEmulation&&(void 0===n.outlineRenderMode||"standard"===n.outlineRenderMode)){p("outlineEmulation","[Heatbox][DEPRECATION][v1.0.0] outlineEmulation is deprecated; use outlineRenderMode and emulationScope instead.");const e=n.outlineEmulation;!1===e||"off"===e?(n.outlineRenderMode="standard",n.emulationScope="off"):!0===e||"all"===e?(n.outlineRenderMode="emulation-only",n.emulationScope="all"):"topn"===e?(n.outlineRenderMode="standard",n.emulationScope="topn"):"non-topn"===e?(n.outlineRenderMode="standard",n.emulationScope="non-topn"):(u.warn(`Invalid outlineEmulation: ${e}. Using 'standard' mode.`),n.outlineRenderMode="standard"),delete n.outlineEmulation}if(void 0!==n.outlineWidthPreset){const e=n.outlineWidthPreset,t={uniform:"medium","adaptive-density":"adaptive","topn-focus":"thick"};t[e]&&(p(`outlineWidthPreset.${e}`,`[Heatbox][DEPRECATION][v1.0.0] outlineWidthPreset "${e}" is deprecated; use "${t[e]}".`),n.outlineWidthPreset=t[e])}if(void 0!==n.outlineInset){const e=parseFloat(n.outlineInset);n.outlineInset=isNaN(e)||e<0?0:e}if(void 0!==n.outlineInsetMode){let e=n.outlineInsetMode;"off"===e&&(e="none"),["all","topn","none"].includes(e)?n.outlineInsetMode=e:(u.warn(`Invalid outlineInsetMode: ${n.outlineInsetMode}. Using 'all'.`),n.outlineInsetMode="all")}if(void 0!==n.outlineInset){const e=parseFloat(n.outlineInset);n.outlineInset=Math.max(0,Math.min(100,isNaN(e)?0:e))}if(void 0!==n.outlineInsetMode){let e=n.outlineInsetMode;"off"===e&&(e="none"),["all","topn","none"].includes(e)?n.outlineInsetMode=e:(u.warn(`Invalid outlineInsetMode: ${n.outlineInsetMode}. Using 'all'.`),n.outlineInsetMode="all")}if(void 0!==n.enableThickFrames&&(n.enableThickFrames=v(n.enableThickFrames)),void 0!==n.renderLimitStrategy&&(["density","coverage","hybrid"].includes(n.renderLimitStrategy)||(u.warn(`Invalid renderLimitStrategy: ${n.renderLimitStrategy}. Using 'density'.`),n.renderLimitStrategy="density")),void 0!==n.minCoverageRatio){const e=parseFloat(n.minCoverageRatio);n.minCoverageRatio=isNaN(e)?.2:Math.max(0,Math.min(1,e))}if(void 0!==n.coverageBinsXY){const e=n.coverageBinsXY;if("auto"!==e){const t=parseInt(e,10);!Number.isFinite(t)||t<=0?(u.warn(`Invalid coverageBinsXY: ${e}. Using 'auto'.`),n.coverageBinsXY="auto"):n.coverageBinsXY=t}}if(void 0!==n.autoVoxelSizeMode&&(["basic","occupancy"].includes(n.autoVoxelSizeMode)||(u.warn(`Invalid autoVoxelSizeMode: ${n.autoVoxelSizeMode}. Using 'basic'.`),n.autoVoxelSizeMode="basic")),void 0!==n.autoVoxelTargetFill){const e=parseFloat(n.autoVoxelTargetFill);n.autoVoxelTargetFill=isNaN(e)?.6:Math.max(0,Math.min(1,e))}if(void 0!==n.renderBudgetMode&&(["manual","auto"].includes(n.renderBudgetMode)||(u.warn(`Invalid renderBudgetMode: ${n.renderBudgetMode}. Using 'manual'.`),n.renderBudgetMode="manual")),void 0!==n.fitViewOptions){const e=n.fitViewOptions||{};void 0!==e.pitch&&void 0===e.pitchDegrees&&p("fitViewOptions.pitch","[Heatbox][DEPRECATION][v1.0.0] fitViewOptions.pitch is deprecated; use fitViewOptions.pitchDegrees."),void 0!==e.heading&&void 0===e.headingDegrees&&p("fitViewOptions.heading","[Heatbox][DEPRECATION][v1.0.0] fitViewOptions.heading is deprecated; use fitViewOptions.headingDegrees.");const t=parseFloat(e.paddingPercent),i=void 0!==e.pitchDegrees?parseFloat(e.pitchDegrees):parseFloat(e.pitch),o=void 0!==e.headingDegrees?parseFloat(e.headingDegrees):parseFloat(e.heading),a=e.altitudeStrategy;n.fitViewOptions={paddingPercent:Number.isFinite(t)?Math.max(0,Math.min(1,t)):.1,pitchDegrees:Number.isFinite(i)?Math.max(-90,Math.min(0,i)):-30,headingDegrees:Number.isFinite(o)?o:0,altitudeStrategy:"manual"===a?"manual":"auto"}}const s=n.adaptiveParams?{...n.adaptiveParams}:{};n.adaptiveParams={...o.adaptiveParams,...s};const l=n.adaptiveParams;if(void 0!==s.minOutlineWidth&&void 0!==s.maxOutlineWidth&&void 0===s.outlineWidthRange&&(l.outlineWidthRange=[Math.max(1,parseFloat(s.minOutlineWidth)||1),Math.max(1,parseFloat(s.maxOutlineWidth)||5)],u.debug("adaptiveParams: minOutlineWidth/maxOutlineWidth normalized to outlineWidthRange")),void 0!==l.outlineWidthRange&&Array.isArray(l.outlineWidthRange)){const[e,t]=l.outlineWidthRange;l.outlineWidthRange=[Math.max(1,parseFloat(e)||1),Math.max(1,parseFloat(t)||5)],l.outlineWidthRange[0]>l.outlineWidthRange[1]&&(l.outlineWidthRange=[l.outlineWidthRange[1],l.outlineWidthRange[0]],u.warn("adaptiveParams.outlineWidthRange: min > max detected, swapped values"))}if(void 0!==l.boxOpacityRange&&Array.isArray(l.boxOpacityRange)){const[e,t]=l.boxOpacityRange;l.boxOpacityRange=[Math.max(0,Math.min(1,parseFloat(e)||0)),Math.max(0,Math.min(1,parseFloat(t)||1))],l.boxOpacityRange[0]>l.boxOpacityRange[1]&&(l.boxOpacityRange=[l.boxOpacityRange[1],l.boxOpacityRange[0]],u.warn("adaptiveParams.boxOpacityRange: min > max detected, swapped values"))}if(void 0!==l.outlineOpacityRange&&Array.isArray(l.outlineOpacityRange)){const[e,t]=l.outlineOpacityRange;l.outlineOpacityRange=[Math.max(0,Math.min(1,parseFloat(e)||0)),Math.max(0,Math.min(1,parseFloat(t)||1))],l.outlineOpacityRange[0]>l.outlineOpacityRange[1]&&(l.outlineOpacityRange=[l.outlineOpacityRange[1],l.outlineOpacityRange[0]],u.warn("adaptiveParams.outlineOpacityRange: min > max detected, swapped values"))}if(void 0!==l.overlapDetection&&(l.overlapDetection=v(l.overlapDetection)),void 0!==l.zScaleCompensation&&(l.zScaleCompensation=v(l.zScaleCompensation)),void 0!==l.adaptiveOpacityEnabled&&(l.adaptiveOpacityEnabled=v(l.adaptiveOpacityEnabled)),void 0!==l.neighborhoodRadius){const e=parseFloat(l.neighborhoodRadius);l.neighborhoodRadius=Number.isFinite(e)&&e>0?e:30}if(void 0!==l.densityThreshold){const e=parseFloat(l.densityThreshold);l.densityThreshold=Number.isFinite(e)&&e>0?e:3}if(void 0!==l.cameraDistanceFactor){const e=parseFloat(l.cameraDistanceFactor);l.cameraDistanceFactor=Number.isFinite(e)&&e>0?e:.8}if(void 0!==l.overlapRiskFactor){const e=parseFloat(l.overlapRiskFactor);l.overlapRiskFactor=Number.isFinite(e)?Math.max(0,Math.min(1,e)):.4}if(n.adaptiveParams=l,n.performanceOverlay){const e={...n.performanceOverlay};if(e.enabled=v(e.enabled,!1),e.autoShow=v(e.autoShow,!1),e.autoUpdate=v(e.autoUpdate,!0),e.position=["top-left","top-right","bottom-left","bottom-right"].includes(e.position)?e.position:"top-right",void 0!==e.updateIntervalMs){const t=parseFloat(e.updateIntervalMs);e.updateIntervalMs=Number.isFinite(t)?Math.max(100,t):500}if(void 0!==e.fpsAveragingWindowMs){const t=parseFloat(e.fpsAveragingWindowMs);e.fpsAveragingWindowMs=Number.isFinite(t)?Math.max(200,t):1e3}n.performanceOverlay=e}if(void 0!==t.spatialId){const e="object"==typeof t.spatialId&&null!==t.spatialId?{...t.spatialId}:{};if(e.enabled=v(e.enabled,!1),void 0!==e.mode?"tile-grid"!==e.mode&&(u.warn(`Invalid spatialId.mode: ${e.mode}. Using 'tile-grid'.`),e.mode="tile-grid"):e.mode="tile-grid",void 0!==e.provider?"ouranos-gex"!==e.provider&&(u.warn(`Unknown spatialId.provider: ${e.provider}. Using 'ouranos-gex'.`),e.provider="ouranos-gex"):e.provider="ouranos-gex",void 0!==e.zoom)if("auto"===e.zoom)e.zoom="auto";else{const t=parseInt(e.zoom,10);Number.isNaN(t)||t<0||t>35?(u.warn(`Invalid spatialId.zoom: ${e.zoom}. Using 25.`),e.zoom=25):e.zoom=t}else e.zoom=25;if(void 0!==e.zoomControl?["auto","manual"].includes(e.zoomControl)||(u.warn(`Invalid spatialId.zoomControl: ${e.zoomControl}. Using 'auto'.`),e.zoomControl="auto"):e.zoomControl="auto",void 0!==e.zoomTolerancePct){const t=parseFloat(e.zoomTolerancePct);!Number.isFinite(t)||t<=0||t>100?(u.warn(`Invalid spatialId.zoomTolerancePct: ${e.zoomTolerancePct}. Using 10.`),e.zoomTolerancePct=10):e.zoomTolerancePct=t}else e.zoomTolerancePct=10;n.spatialId=e}else n.spatialId={...o.spatialId};return void 0!==n.aggregation?n.aggregation=function(e){const t={...o.aggregation};if(!e||"object"!=typeof e)return t;if(void 0!==e.enabled&&(t.enabled=v(e.enabled,!1)),void 0!==e.byProperty&&null!==e.byProperty&&("string"==typeof e.byProperty&&""!==e.byProperty.trim()?t.byProperty=e.byProperty.trim():(u.warn("[aggregation] byProperty must be a non-empty string, ignoring"),t.byProperty=null)),void 0!==e.keyResolver&&null!==e.keyResolver&&("function"==typeof e.keyResolver?t.keyResolver=e.keyResolver:(u.warn("[aggregation] keyResolver must be a function, ignoring"),t.keyResolver=null)),void 0!==e.showInDescription&&(t.showInDescription=v(e.showInDescription,!0)),void 0!==e.topN){const i=Number(e.topN);Number.isInteger(i)&&i>0&&i<=100?t.topN=i:(u.warn("[aggregation] topN must be a positive integer <= 100, using default (10)"),t.topN=o.aggregation.topN)}return!t.enabled||t.byProperty||t.keyResolver||u.warn('[aggregation] enabled=true but neither byProperty nor keyResolver is set. Will use default key "default".'),t}(n.aggregation):n.aggregation={...o.aggregation},n}function w(e,t){const i=S(e),o=i.x*i.y*Math.max(i.z,10),n=t/o;let r;return r=n>.001?Math.max(10,Math.min(20,20/Math.sqrt(1e3*n))):n>1e-4?Math.max(20,Math.min(50,50/Math.sqrt(1e4*n))):Math.max(50,Math.min(100,100/Math.sqrt(1e5*n))),r=Math.max(5,Math.min(a,r)),u.debug(`Basic voxel size estimated: ${r}m (density: ${n}, volume: ${o})`),Math.round(r)}function S(e){try{const t={minLat:Number.isFinite(e.minLat)?Math.max(-90,Math.min(90,e.minLat)):0,maxLat:Number.isFinite(e.maxLat)?Math.max(-90,Math.min(90,e.maxLat)):.1,minLon:Number.isFinite(e.minLon)?Math.max(-180,Math.min(180,e.minLon)):0,maxLon:Number.isFinite(e.maxLon)?Math.max(-180,Math.min(180,e.maxLon)):.1,minAlt:Number.isFinite(e.minAlt)?e.minAlt:0,maxAlt:Number.isFinite(e.maxAlt)?e.maxAlt:100};t.maxLat<=t.minLat&&(t.maxLat=t.minLat+.001),t.maxLon<=t.minLon&&(t.maxLon=t.minLon+.001),t.maxAlt<=t.minAlt&&(t.maxAlt=t.minAlt+1);const i=(t.minLat+t.maxLat)/2,o=Math.cos(Math.max(-Math.PI/2,Math.min(Math.PI/2,i*Math.PI/180))),n=111e3*Math.abs(t.maxLon-t.minLon)*Math.abs(o),a=111e3*Math.abs(t.maxLat-t.minLat),r=Math.abs(t.maxAlt-t.minAlt);return{x:Math.max(1,Math.min(1e6,n)),y:Math.max(1,Math.min(1e6,a)),z:Math.max(1,Math.min(1e4,r))}}catch(e){return u.warn("Data range calculation failed:",e),{x:1e3,y:1e3,z:100}}}const z={low:{min:4e3,max:8e3},mid:{min:8e3,max:15e3},high:{min:15e3,max:25e3}};class R{static calculateBounds(e){if(!Array.isArray(e)||0===e.length)throw new Error("エンティティが提供されていません");let t=1/0,o=-1/0,n=1/0,a=-1/0,r=1/0,s=-1/0,l=0;const d=i.JulianDate.now();if(e.forEach((e,c)=>{try{let c,u,h,p;if(e.position&&(c="function"==typeof e.position.getValue?e.position.getValue(d):e.position),!c)return;if("number"==typeof c?.x&&"number"==typeof c?.y&&Math.abs(c.x)<=360&&Math.abs(c.y)<=90)u=c.x,h=c.y,p="number"==typeof c.z?c.z:0;else{const e=i.Cartographic.fromCartesian(c);if(!e)return;u=i.Math.toDegrees(e.longitude),h=i.Math.toDegrees(e.latitude),p=e.height}t=Math.min(t,u),o=Math.max(o,u),n=Math.min(n,h),a=Math.max(a,h),r=Math.min(r,p),s=Math.max(s,p),l++}catch(e){u.warn(`エンティティ ${c} の処理に失敗:`,e)}}),0===l)throw new Error("有効な位置情報を持つエンティティが見つかりません");return u.debug("座標範囲計算完了:",{validCount:l,bounds:{minLon:t,maxLon:o,minLat:n,maxLat:a,minAlt:r,maxAlt:s}}),{minLon:t,maxLon:o,minLat:n,maxLat:a,minAlt:r,maxAlt:s,centerLon:(t+o)/2,centerLat:(n+a)/2,centerAlt:(r+s)/2}}static voxelIndexToCoordinate(e,t,i,o,n){const{minLon:a,maxLon:r,minLat:s,maxLat:l,minAlt:d,maxAlt:c}=o,{numVoxelsX:u,numVoxelsY:h,numVoxelsZ:p}=n;return{lon:a+(e+.5)/u*(r-a),lat:s+(t+.5)/h*(l-s),alt:d+(i+.5)/p*(c-d)}}static coordinateToCartesian3(e,t,o){return i.Cartesian3.fromDegrees(e,t,o)}}class _{static createGrid(e,t){const i=(e.minLat+e.maxLat)/2,o=111e3*(e.maxLon-e.minLon)*Math.cos(i*Math.PI/180),n=111e3*(e.maxLat-e.minLat),a=e.maxAlt-e.minAlt,r=Math.max(1,Math.ceil(o/t)),s=Math.max(1,Math.ceil(n/t)),l=Math.max(1,Math.ceil(a/t)),d=r>0?o/r:t,c=s>0?n/s:t,h=l>0?Math.max(a/l,1):Math.max(t,1),p=r*s*l;return u.debug("VoxelGrid created:",{numVoxelsX:r,numVoxelsY:s,numVoxelsZ:l,totalVoxels:p,voxelSizeMeters:t,cellSizeX:d,cellSizeY:c,cellSizeZ:h,lonRangeMeters:o,latRangeMeters:n,altRangeMeters:a}),{numVoxelsX:r,numVoxelsY:s,numVoxelsZ:l,totalVoxels:p,voxelSizeMeters:t,cellSizeX:d,cellSizeY:c,cellSizeZ:h,lonRangeMeters:o,latRangeMeters:n,altRangeMeters:a}}static getVoxelKey(e,t,i){return`${e},${t},${i}`}static parseVoxelKey(e){const[t,i,o]=e.split(",").map(Number);return{x:t,y:i,z:o}}static iterateAllVoxels(e,t){const{numVoxelsX:i,numVoxelsY:o,numVoxelsZ:n}=e;for(let e=0;e<i;e++)for(let i=0;i<o;i++)for(let o=0;o<n;o++)t(e,i,o,this.getVoxelKey(e,i,o))}}class O{static convert(e,t,i,o){e=O._normalizeLongitude(e),t=O._clampLatitude(t),o=Math.max(0,Math.min(35,Math.floor(o)));const n=Math.pow(2,o),a=Math.floor((e+180)/360*n),r=t*Math.PI/180,s=Math.floor((1-Math.log(Math.tan(r)+1/Math.cos(r))/Math.PI)/2*n),l=O._getAltitudePerBin(o,t),d=Math.floor(i/l);return{zfxy:{z:o,f:d,x:a,y:s},zfxyStr:`/${o}/${d}/${a}/${s}`,vertices:O._calculateVertices(e,t,i,o,a,s,d,l)}}static _normalizeLongitude(e){if(180===e)return-180;for(;e>180;)e-=360;for(;e<-180;)e+=360;return e}static _clampLatitude(e){const t=85.0511287798;return Math.max(-t,Math.min(t,e))}static _getAltitudePerBin(e,t){const i=r,o=Math.max(0,Math.min(35,Math.floor(e))),n=Number.isFinite(t)?t*Math.PI/180:0,a=i*Math.max(Math.cos(n),1e-5)/Math.pow(2,o)*1;return Math.min(5e3,Math.max(.5,a))}static _calculateVertices(e,t,i,o,n,a,r,s){const l=Math.pow(2,o),d=n/l*360-180,c=(n+1)/l*360-180,u=Math.atan(Math.sinh(Math.PI*(1-2*(a+1)/l))),h=Math.atan(Math.sinh(Math.PI*(1-2*a/l))),p=180*u/Math.PI,m=180*h/Math.PI,g=r*s,y=(r+1)*s;return[{lng:d,lat:p,alt:g},{lng:c,lat:p,alt:g},{lng:c,lat:m,alt:g},{lng:d,lat:m,alt:g},{lng:d,lat:p,alt:y},{lng:c,lat:p,alt:y},{lng:c,lat:m,alt:y},{lng:d,lat:m,alt:y}]}static validateZFXY(e){if(!e||"object"!=typeof e)return!1;const{z:t,f:i,x:o,y:n}=e;if(!(Number.isInteger(t)&&Number.isInteger(i)&&Number.isInteger(o)&&Number.isInteger(n)))return!1;if(t<0||t>35)return!1;const a=Math.pow(2,t);return!(o<0||o>=a||n<0||n>=a)}static parseZFXYStr(e){if("string"!=typeof e)return null;const t=e.split("/").filter(e=>e.length>0);if(4!==t.length)return null;const[i,o,n,a]=t.map(e=>parseInt(e,10));if(Number.isNaN(i)||Number.isNaN(o)||Number.isNaN(n)||Number.isNaN(a))return null;const r={z:i,f:o,x:n,y:a};return O.validateZFXY(r)?r:null}}class C{constructor(e={}){this.provider=e.provider||"ouranos-gex",this.Space=null,this.fallbackMode=!1,this.loaded=!1}async loadProvider(){if(this.loaded)return!this.fallbackMode;if("ouranos-gex"!==this.provider)return u.warn(`SpatialIdAdapter: Unknown provider '${this.provider}', using built-in fallback`),this.fallbackMode=!0,this.loaded=!0,!1;try{const e=await Promise.resolve().then(function(){var e=new Error("Cannot find module 'ouranos-gex-lib-for-javascript'");throw e.code="MODULE_NOT_FOUND",e});return this.Space=e.Space,this.fallbackMode=!1,this.loaded=!0,u.info("SpatialIdAdapter: ouranos-gex loaded successfully"),!0}catch(e){return u.warn("SpatialIdAdapter: ouranos-gex not available, using built-in fallback",e.message),this.fallbackMode=!0,this.loaded=!0,!1}}neighbors(e){const{z:t,f:i,x:o,y:n}=e,a=Math.pow(2,t),r=[];for(let e=-1;e<=1;e++)for(let s=-1;s<=1;s++){if(0===s&&0===e)continue;const l=n+e;if(l<0||l>=a)continue;const d=(o+s+a)%a;r.push({z:t,f:i,x:d,y:l})}return r}children(e){const{z:t,f:i,x:o,y:n}=e,a=t+1,r=2*o,s=2*n,l=Math.pow(2,a),d=[];for(let e=0;e<=1;e++)for(let t=0;t<=1;t++){const o=(r+t)%l,n=s+e;n<0||n>=l||d.push({z:a,f:i,x:o,y:n})}return d}parent(e){const{z:t,f:i,x:o,y:n}=e;return t<=0?null:{z:t-1,f:i,x:Math.floor(o/2),y:Math.floor(n/2)}}getVoxelBounds(e,t,i,o){if(!this.loaded)throw new Error("SpatialIdAdapter: loadProvider() must be called before getVoxelBounds()");if(!this.Space||this.fallbackMode){const n=O.convert(e,t,i,o);return n.vertices=C._normalizeVertices(n.vertices),n}try{const n=new this.Space({lng:e,lat:t,alt:i},o),a="function"==typeof n.vertices3d?n.vertices3d():[],r=C._normalizeVertices(a);return{zfxy:n.zfxy,zfxyStr:n.zfxyStr,vertices:r}}catch(n){return u.warn("SpatialIdAdapter: ouranos-gex error, falling back to built-in converter",n.message),O.convert(e,t,i,o)}}calculateOptimalZoom(e,t,i=10){let o=25,n=1/0,a=null,r=1/0;for(let s=15;s<=30;s++){const l=this._calculateCellSizeAtZoom(s,t),d=Math.abs(l-e)/e;d<n&&(o=s,n=d),d<=i/100&&d<r&&(a=s,r=d)}const s=null!==a?a:o,l=this._calculateCellSizeAtZoom(s,t),d=Math.abs(l-e)/e*100;return u.debug(`SpatialIdAdapter: Optimal zoom ${s} for target size ${e}m (cell size: ${l.toFixed(1)}m, error: ${d.toFixed(1)}%)${null===a?" [closest, exceeds tolerance]":""}`),s}static _normalizeVertices(e){return Array.isArray(e)?e.map((e,t)=>{if(Array.isArray(e)){const[t,i,o]=e;return{lng:C._toNumber(t),lat:C._toNumber(i),alt:C._toNumber(o)}}if(e&&"object"==typeof e){const t=e.lng??e.lon??e.longitude,i=e.lat??e.latitude,o=e.alt??e.altitude??e.height;return{lng:C._toNumber(t),lat:C._toNumber(i),alt:C._toNumber(o)}}return u.warn("SpatialIdAdapter: Unexpected vertex format from provider",{index:t,vertex:e}),{lng:0,lat:0,alt:0}}):[]}static _toNumber(e){const t=Number(e);return Number.isFinite(t)?t:0}_calculateCellSizeAtZoom(e,t){const i=r,o=t*Math.PI/180;return i*Math.cos(o)/Math.pow(2,e)}getStatus(){return{provider:this.provider,loaded:this.loaded,fallbackMode:this.fallbackMode}}}function V(e,t=i.JulianDate.now()){if(null==e)return e;try{if("function"==typeof e.getValue)return e.getValue(t);if("function"==typeof e.get)return e.get(t)}catch(e){return}return e}class I{static async classifyEntitiesIntoVoxels(e,t,o,n={}){if(n.spatialId?.enabled)return await I._classifyBySpatialId(e,t,o,n);const a=new Map;let r=0,s=0;const l=n.aggregation||{},d=Boolean(l.enabled),c=i.JulianDate.now(),h="string"==typeof l.byProperty&&""!==l.byProperty.trim()?l.byProperty.trim():null,p="function"==typeof l.keyResolver?l.keyResolver:null;let m=null;if(d&&(p||h?m=(e,t)=>{let i;if(p){try{i=p(e)}catch(e){return u.warn(`[aggregation] keyResolver threw error for entity ${t}, using "unknown"`,e),"unknown"}i=V(i,c)}else if(h){let t;try{const i=e.properties?.getValue?.(c);i&&"object"==typeof i&&h in i&&(t=i[h])}catch(e){u.warn(`[aggregation] Failed to resolve PropertyBag for ${h}, fallback to direct property`,e)}if(void 0===t){const i=e.properties?.[h];t=V(i,c)}i=t}if(null==i||"number"==typeof i&&Number.isNaN(i))return"unknown";const o=String(i);return""===o.trim()?"unknown":o}:(u.warn('[aggregation] enabled but no byProperty or keyResolver specified, using "default" key'),m=()=>"default")),u.debug(`Processing ${e.length} entities for classification`),e.forEach((e,n)=>{try{let l,u,h,p;if(e.position&&(l="function"==typeof e.position.getValue?e.position.getValue(c):e.position),!l)return void s++;if("number"==typeof l?.x&&"number"==typeof l?.y&&Math.abs(l.x)<=360&&Math.abs(l.y)<=90)u=l.x,h=l.y,p="number"==typeof l.z?l.z:0;else if(i.Cartographic&&"function"==typeof i.Cartographic.fromCartesian){const e=i.Cartographic.fromCartesian(l);if(!e)return void s++;u=i.Math.toDegrees(e.longitude),h=i.Math.toDegrees(e.latitude),p=e.height}else{if("number"!=typeof l.x||"number"!=typeof l.y)return void s++;u=l.x,h=l.y,p="number"==typeof l.z?l.z:0}if(u<t.minLon-.001||u>t.maxLon+.001||h<t.minLat-.001||h>t.maxLat+.001||p<t.minAlt-1||p>t.maxAlt+1)return void s++;const{x:g,y,z:f}=I._normalizeGridIndices(u,h,p,t,o);if(g>=0&&g<o.numVoxelsX&&y>=0&&y<o.numVoxelsY&&f>=0&&f<o.numVoxelsZ){const t=_.getVoxelKey(g,y,f);if(!a.has(t)){const e={x:g,y,z:f,entities:[],count:0};d&&(e.layerStats=new Map),a.set(t,e)}const i=a.get(t);if(i.entities.push(e),i.count++,d&&m){const t=m(e,n)||"unknown",o=i.layerStats.get(t)||0;i.layerStats.set(t,o+1)}r++}else s++}catch(e){u.warn(`エンティティ ${n} の処理に失敗:`,e),s++}}),d){for(const e of a.values())if(e.layerStats&&e.layerStats.size>0){let t=0,i=null;for(const[o,n]of e.layerStats)n>t&&(t=n,i=o);e.layerTop=i}u.debug(`[aggregation] Calculated layerTop for ${a.size} voxels`)}return u.info(`${r}個のエンティティを${a.size}個のボクセルに分類(${s}個はスキップ)`),a}static calculateStatistics(e,t){if(0===e.size)return{totalVoxels:t.totalVoxels,renderedVoxels:0,nonEmptyVoxels:0,emptyVoxels:t.totalVoxels,totalEntities:0,minCount:0,maxCount:0,averageCount:0,autoAdjusted:!1,originalVoxelSize:null,finalVoxelSize:null,adjustmentReason:null};const i=Array.from(e.values()).map(e=>e.count),o=i.reduce((e,t)=>e+t,0),n=Math.max(0,t.totalVoxels-e.size),a={totalVoxels:t.totalVoxels,renderedVoxels:0,nonEmptyVoxels:e.size,emptyVoxels:n,totalEntities:o,minCount:Math.min(...i),maxCount:Math.max(...i),averageCount:o/e.size,autoAdjusted:!1,originalVoxelSize:null,finalVoxelSize:null,adjustmentReason:null};return u.debug("統計情報計算完了:",a),a}static _normalizeGridIndices(e,t,i,o,n){const a=(e,t,i,o)=>{const n=Number.isFinite(i-t)?i-t:0,a=Number.isFinite(e)?e:t,r=(e=>{const t=Number.isFinite(e)?Math.floor(e):0;return t>0?t:1})(o);if(0===n)return 0;const s=(a-t)/n,l=Math.floor(s*r),d=r-1,c=Number.isFinite(l)?l:0;return Math.max(0,Math.min(d,c))};return{x:a(e,o.minLon,o.maxLon,n.numVoxelsX),y:a(t,o.minLat,o.maxLat,n.numVoxelsY),z:a(i,o.minAlt,o.maxAlt,n.numVoxelsZ)}}static getTopNVoxels(e,t){if(0===e.size||t<=0)return[];const i=Array.from(e.values()).sort((e,t)=>t.count-e.count);return i.slice(0,Math.min(t,i.length))}static async _classifyBySpatialId(e,t,o,n){u.debug(`Spatial ID mode enabled: ${n.spatialId.mode}`);const a=new C({provider:n.spatialId.provider||"ouranos-gex"});let r;await a.loadProvider();const s=(t.minLat+t.maxLat)/2;if("auto"===n.spatialId.zoomControl){const e=n.voxelSize||30,t=n.spatialId.zoomTolerancePct||10;r=a.calculateOptimalZoom(e,s,t),u.info(`Auto-selected zoom level ${r} for target size ${e}m (lat: ${s.toFixed(4)}°)`)}else{const e=n.spatialId.zoom;"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=35?r=Math.floor(e):(r=25,u.warn(`Invalid zoom value in manual mode (${e}), using default zoom level ${r}`)),u.info(`Using manual zoom level ${r}`)}n._resolvedZoom=r,n._spatialIdProvider=a.fallbackMode?null:n.spatialId.provider;const l=n.aggregation||{},d=Boolean(l.enabled),c=i.JulianDate.now(),h="string"==typeof l.byProperty&&""!==l.byProperty.trim()?l.byProperty.trim():null,p="function"==typeof l.keyResolver?l.keyResolver:null;let m=null;d&&(p||h?m=(e,t)=>{let i;if(p){try{i=p(e)}catch(e){return u.warn(`[aggregation] keyResolver threw error for entity ${t}, using "unknown"`,e),"unknown"}i=V(i,c)}else if(h){let t;try{const i=e.properties?.getValue?.(c);i&&"object"==typeof i&&h in i&&(t=i[h])}catch(e){u.warn(`[aggregation] Failed to resolve PropertyBag for ${h}, fallback to direct property`,e)}if(void 0===t){const i=e.properties?.[h];t=V(i,c)}i=t}if(null==i||"number"==typeof i&&Number.isNaN(i))return"unknown";const o=String(i);return""===o.trim()?"unknown":o}:(u.warn('[aggregation] enabled but no byProperty or keyResolver specified, using "default" key'),m=()=>"default"));const g=new Map;let y=0,f=0,x=0;for(const n of e){try{let e,s,l,u;if(n.position&&(e="function"==typeof n.position.getValue?n.position.getValue(c):n.position),!e){f++;continue}if("number"==typeof e?.x&&"number"==typeof e?.y&&Math.abs(e.x)<=360&&Math.abs(e.y)<=90)s=e.x,l=e.y,u="number"==typeof e.z?e.z:0;else if(i.Cartographic&&"function"==typeof i.Cartographic.fromCartesian){const t=i.Cartographic.fromCartesian(e);if(!t){f++;continue}s=i.Math.toDegrees(t.longitude),l=i.Math.toDegrees(t.latitude),u=t.height}else{if("number"!=typeof e.x||"number"!=typeof e.y){f++;continue}s=e.x,l=e.y,u="number"==typeof e.z?e.z:0}const{zfxy:h,zfxyStr:p,vertices:v}=a.getVoxelBounds(s,l,u,r);if(!g.has(p)){const e=v.reduce((e,t)=>e+t.lng,0)/8,i=v.reduce((e,t)=>e+t.lat,0)/8,n=v.reduce((e,t)=>e+t.alt,0)/8,{x:a,y:r,z:s}=I._normalizeGridIndices(e,i,n,t,o),l={key:p,x:a,y:r,z:s,bounds:v,spatialId:{...h,id:p},entities:[],count:0};d&&(l.layerStats=new Map),g.set(p,l)}const b=g.get(p);if(b.entities.push(n),b.count++,d&&m){const e=m(n,x)||"unknown",t=b.layerStats.get(e)||0;b.layerStats.set(e,t+1)}y++}catch(e){u.warn("Failed to process entity for spatial ID:",e),f++}x++}if(d){for(const e of g.values())if(e.layerStats&&e.layerStats.size>0){let t=0,i=null;for(const[o,n]of e.layerStats)n>t&&(t=n,i=o);e.layerTop=i}u.debug(`[aggregation] Calculated layerTop for ${g.size} voxels (Spatial ID mode)`)}return u.info(`Spatial ID: ${y} entities classified into ${g.size} voxels (${f} skipped)`),g}}const A=Object.freeze({viridis:Object.freeze([[68,1,84],[72,40,120],[62,74,137],[49,104,142],[38,130,142],[31,158,137],[53,183,121],[109,205,89],[180,222,44],[253,231,37]]),inferno:Object.freeze([[0,0,4],[31,12,72],[85,15,109],[136,34,106],[186,54,85],[227,89,51],[249,142,8],[252,187,17],[245,219,76],[252,255,164]]),diverging:Object.freeze([[0,0,255],[32,64,255],[64,128,255],[96,160,255],[128,192,255],[160,224,255],[192,240,255],[224,248,255],[255,255,255],[255,248,224],[255,240,192],[255,224,160],[255,192,128],[255,160,96],[255,128,64],[255,64,32],[255,0,0]])});class L{static calculateColor(e,t=null,o={}){try{Number.isFinite(e)||(u.warn(`Invalid normalizedDensity: ${e}. Using 0.5 as fallback.`),e=.5);const{minColor:i=[0,0,255],maxColor:n=[255,0,0],colorMap:a,diverging:r=!1,divergingPivot:s=0}=o;if(r&&null!==t){const e="number"==typeof s?s:0;return L.calculateDivergingColor(t,{divergingPivot:e})}return a&&"custom"!==a?L.interpolateFromColorMap(e,a):L.interpolateLinear(e,i,n)}catch(e){return u.warn(`Color calculation failed: ${e.message}. Falling back to gray.`),i.Color.GRAY}}static interpolateLinear(e,t,o){const n=Math.max(0,Math.min(1,e)),[a,r,s]=t,[l,d,c]=o,u=Math.round(a+(l-a)*n),h=Math.round(r+(d-r)*n),p=Math.round(s+(c-s)*n);return i.Color.fromBytes(u,h,p)}static interpolateFromColorMap(e,t){const o=A[t];if(!o)return u.warn(`Unknown color map: ${t}. Falling back to linear interpolation.`),L.interpolateLinear(e,[0,0,255],[255,0,0]);const n=Math.max(0,Math.min(1,e))*(o.length-1),a=Math.floor(n),r=Math.min(a+1,o.length-1),s=n-a,[l,d,c]=o[a],[h,p,m]=o[r],g=Math.round(l+(h-l)*s),y=Math.round(d+(p-d)*s),f=Math.round(c+(m-c)*s);return i.Color.fromBytes(g,y,f)}static calculateDivergingColor(e,t={}){const{divergingPivot:i=0}=t,o=i;let n;return 0===o?e<0?(n=1/(1-e)*.5,n=Math.max(0,Math.min(.5,n))):e>0?(n=.5+e/(1+e)*.5,n=Math.max(.5,Math.min(1,n))):n=.5:e<=o?(n=e/o*.5,n=Math.max(0,Math.min(.5,n))):(n=.5+(e-o)/o*.5,n=Math.max(.5,Math.min(1,n))),L.interpolateFromColorMap(n,"diverging")}static getAvailableColorMaps(){return Object.keys(A)}static isValidColorMap(e){return Object.hasOwn(A,e)}}class N{constructor(e={}){this.options={renderLimitStrategy:"density",highlightTopN:0,coverageBinsXY:"auto",minCoverageRatio:.2,...e},this._lastSelectionStats=null,u.debug(`VoxelSelector initialized with strategy: ${this.options.renderLimitStrategy}`)}selectVoxels(e,t,i={}){try{if(!Array.isArray(e)||0===e.length)return u.warn("VoxelSelector: Empty or invalid voxel array provided"),this._createEmptyResult();if(t<=0)return u.warn(`VoxelSelector: Invalid maxCount: ${t}`),this._createEmptyResult();if(e.length<=t)return this._createResult(e,this.options.renderLimitStrategy,e.length,0);const{grid:o}=i,n=this.options.renderLimitStrategy||"density",a=this._identifyTopNVoxels(e);let r;switch(n){case"coverage":r=this._selectByCoverageStrategy(e,t,o,a);break;case"hybrid":r=this._selectByHybridStrategy(e,t,o,a);break;default:r=this._selectByDensityStrategy(e,t,a)}return this._lastSelectionStats={strategy:r.strategy,clippedNonEmpty:r.clippedNonEmpty,coverageRatio:r.coverageRatio||null,selectedCount:r.selectedVoxels.length,totalCount:e.length},u.debug(`VoxelSelector: Applied ${r.strategy} strategy - selected ${r.selectedVoxels.length}/${e.length} voxels`),r}catch(i){return u.error(`VoxelSelector: Selection failed: ${i.message}. Falling back to density strategy.`),this._fallbackToDensitySelection(e,t)}}getLastSelectionStats(){return this._lastSelectionStats}_identifyTopNVoxels(e){const t=new Set;if(this.options.highlightTopN&&this.options.highlightTopN>0){const i=[...e].sort((e,t)=>t.info.count-e.info.count).slice(0,this.options.highlightTopN);i.forEach(e=>t.add(e.key)),u.debug(`VoxelSelector: Identified ${i.length} TopN voxels for forced inclusion`)}return t}_selectByDensityStrategy(e,t,i=new Set){const o=[...e].sort((e,t)=>t.info.count-e.info.count),n=[],a=new Set;o.forEach(e=>{i.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))}),o.forEach(e=>{!a.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))});const r=e.length-n.length;return this._createResult(n,"density",n.length,r)}_selectByCoverageStrategy(e,t,i,o=new Set){const n=[],a=new Set;e.forEach(e=>{o.has(e.key)&&n.length<t&&(n.push(e),a.add(e.key))});const r="auto"===this.options.coverageBinsXY?Math.ceil(Math.sqrt(t/4)):this.options.coverageBinsXY,s=new Map;e.filter(e=>!a.has(e.key)).forEach(e=>{const t=`${Math.max(0,Math.min(r-1,Math.floor(e.info.x/Math.max(1,i.numVoxelsX)*r)))},${Math.max(0,Math.min(r-1,Math.floor(e.info.y/Math.max(1,i.numVoxelsY)*r)))}`;s.has(t)||s.set(t,[]),s.get(t).push(e)});const l=Array.from(s.keys());let d=0;for(;n.length<t&&d<10*l.length;){const e=l[d%l.length],t=s.get(e);if(t&&t.length>0){t.sort((e,t)=>t.info.count-e.info.count);const i=t.shift();a.has(i.key)||(n.push(i),a.add(i.key)),0===t.length&&(s.delete(e),l.splice(l.indexOf(e),1))}d++}const c=e.length-n.length;return this._createResult(n,"coverage",n.length,c)}_selectByHybridStrategy(e,t,i,o=new Set){const n=this.options.minCoverageRatio||.2,a=[],r=new Set;e.forEach(e=>{o.has(e.key)&&a.length<t&&(a.push(e),r.add(e.key))});const s=t-a.length,l=Math.floor(s*n),d=s-l;l>0&&this._selectByCoverageStrategy(e.filter(e=>!r.has(e.key)),l,i,new Set).selectedVoxels.forEach(e=>{a.length<t&&!r.has(e.key)&&(a.push(e),r.add(e.key))}),d>0&&this._selectByDensityStrategy(e.filter(e=>!r.has(e.key)),d,new Set).selectedVoxels.forEach(e=>{a.length<t&&!r.has(e.key)&&(a.push(e),r.add(e.key))});const c=l>0?(a.length-o.size-d)/(a.length-o.size):0,u=e.length-a.length;return this._createResult(a,"hybrid",a.length,u,c)}_fallbackToDensitySelection(e,t){try{const i=new Set,o=this._selectByDensityStrategy(e,t,i);return o.strategy="density-fallback",this._lastSelectionStats={strategy:o.strategy,clippedNonEmpty:o.clippedNonEmpty,coverageRatio:null,selectedCount:o.selectedVoxels.length,totalCount:e.length,error:!0},o}catch(e){return u.error(`VoxelSelector: Even fallback failed: ${e.message}`),this._createEmptyResult()}}_createResult(e,t,i,o,n=null){return{selectedVoxels:e,strategy:t,clippedNonEmpty:o,coverageRatio:n}}_createEmptyResult(){return{selectedVoxels:[],strategy:"none",clippedNonEmpty:0,coverageRatio:null}}}const F=o.adaptiveParams||{};class ${constructor(e={}){const t={...F,...e.adaptiveParams||{}};this.options={...e,adaptiveParams:t},u.debug("AdaptiveController initialized with options:",this.options)}calculateNeighborhoodDensity(e,t,i=null,o=null){if(!t||"function"!=typeof t.get)return{isDenseArea:!1,neighborhoodDensity:0,neighborCount:0};const{x:n,y:a,z:r}=e,s={...F,...this.options?.adaptiveParams||{},...o?.adaptiveParams||{}},l=s.neighborhoodRadius??F.neighborhoodRadius??30,d=null!==i?i:Math.max(1,Math.floor(l/20));let c=0,u=0;for(let e=-d;e<=d;e++)for(let i=-d;i<=d;i++)for(let o=-d;o<=d;o++){if(0===e&&0===i&&0===o)continue;const s=`${n+e},${a+i},${r+o}`,l=t.get(s);l&&(c+=l.count,u++)}const h=u>0?c/u:0;return{totalDensity:c,neighborCount:u,avgDensity:h,isDenseArea:h>(s.densityThreshold??F.densityThreshold??5),searchRadius:d}}_calculateZScaleCompensation(e,t){const i=this.options.adaptiveParams||F;if(!t||!i.zScaleCompensation)return 1;const{cellSizeX:o,cellSizeY:n,cellSizeZ:a}=t;if(!o||!n||!a)return 1;const r=a/((o+n)/2);return r<.1?Math.max(.7,Math.min(1.3,1+2*(.1-r))):1}_countAdjacentVoxels(e,t){if(!e||!t||"function"!=typeof t.get)return 0;const{x:i,y:o,z:n}=e,a=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];let r=0;for(const[e,s,l]of a){const a=`${i+e},${o+s},${n+l}`;t.get(a)&&r++}return r}_detectOverlapAndRecommendMode(e,t,i=null){const o=i||this.options||{},n={...F,...this.options?.adaptiveParams||{},...i?.adaptiveParams||{}},a=o.outlineRenderMode||"standard",r=o.outlineInset||0;if(!n.overlapDetection)return{recommendedMode:a,recommendedInset:r};const s=this._countAdjacentVoxels(e,t)/6;return s>.5&&"emulation-only"!==a?{recommendedMode:"inset",recommendedInset:Math.max(.3,.8-.4*s),reason:`High overlap risk (${(100*s).toFixed(0)}%)`}:{recommendedMode:a,recommendedInset:r}}applyPresetLogic(e,t,i,o,n){let a,r,s;switch(e){case"thin":a=Math.max(1,.8*n.outlineWidth),r=n.opacity,s=n.outlineOpacity||.8;break;case"medium":case"uniform":default:a=n.outlineWidth,r=n.opacity,s=n.outlineOpacity||1;break;case"thick":a=Math.max(1,1.5*n.outlineWidth),r=n.opacity,s=n.outlineOpacity||1;break;case"adaptive":case"adaptive-density":{const e=o?Math.max(.6,.8+.3*(i-.5)):1;a=Math.max(1,Math.min(3*n.outlineWidth,n.outlineWidth*e)),r=o?.8*n.opacity:n.opacity,s=o?.6:1;break}case"topn-focus":a=t?Math.max(1,Math.min(3*n.outlineWidth,n.outlineWidth*(1.5+.5*i))):Math.max(1,.8*n.outlineWidth),r=t?n.opacity:.6*n.opacity,s=t?1:.4}return{adaptiveWidth:a,adaptiveBoxOpacity:r,adaptiveOutlineOpacity:s}}calculateAdaptiveParams(e,t,i,o,n,a=null){if(!e||!o||!n)return{outlineWidth:null,boxOpacity:null,outlineOpacity:null,shouldUseEmulation:!1};if(!n.adaptiveOutlines)return{outlineWidth:null,boxOpacity:null,outlineOpacity:null,shouldUseEmulation:!1};const{count:r}=e,s=o.maxCount>o.minCount?(r-o.minCount)/(o.maxCount-o.minCount):0,l=this.calculateNeighborhoodDensity(e,i,null,n),{isDenseArea:d}=l,c=this._calculateZScaleCompensation(e,a),u=this._detectOverlapAndRecommendMode(e,i,n),h={...F,...this.options?.adaptiveParams||{},...n?.adaptiveParams||{}},p=h.cameraDistanceFactor??1,m=h.overlapRiskFactor??0,g=Math.min(1,1)*p,y=d?m:0,f=this.applyPresetLogic(n.outlineWidthPreset,t,s,d,n),x=f.adaptiveWidth*g*c,v=Math.max(.2,f.adaptiveOutlineOpacity*(1-y)),b=n&&n.adaptiveParams||h||{},M=(e,t,i,o)=>{let n=e;if(Array.isArray(t)&&2===t.length){const[e,a]=t,r=null!=e?e:i,s=null!=a?a:o;n=Math.min(s??n,Math.max(r??n,n))}return null!=i&&(n=Math.max(i,n)),null!=o&&(n=Math.min(o,n)),n};return{outlineWidth:M(Math.max(1,x),b.outlineWidthRange,h.minOutlineWidth??1,h.maxOutlineWidth??null),boxOpacity:M(Math.max(0,Math.min(1,f.adaptiveBoxOpacity)),b.boxOpacityRange,0,1),outlineOpacity:M(Math.max(.2,Math.min(1,v)),b.outlineOpacityRange,0,1),shouldUseEmulation:d||x>2&&"standard"!==n.outlineRenderMode,_debug:{normalizedDensity:s,neighborhoodResult:l,cameraFactor:g,overlapRisk:y,zScaleFactor:c,overlapRecommendation:u,preset:n.outlineWidthPreset}}}updateOptions(e){this.options={...this.options,...e,adaptiveParams:{...this.options.adaptiveParams,...e.adaptiveParams||{}}},u.debug("AdaptiveController options updated:",this.options)}getConfiguration(){return{...this.options,version:"0.1.11",phase:"ADR-0009 Phase 3"}}}const P={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"},D=/[&<>"'`]/g;function E(e){return"string"!=typeof e?null==e?"":String(e):e.replace(D,e=>P[e]||e)}class k{constructor(e,t={}){this.viewer=e,this.options={wireframeOnly:!1,showOutline:!0,outlineWidth:2,outlineInset:0,outlineInsetMode:"all",outlineRenderMode:"standard",enableThickFrames:!1,...t},this.entities=[],u.debug("GeometryRenderer initialized with viewer and options:",this.options)}createVoxelBox(e){const{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s,color:l,opacity:d,shouldShowOutline:c,outlineColor:h,outlineWidth:p,voxelInfo:m,voxelKey:g,emulateThick:y=!1}=e,f=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,x=Number.isFinite(o)?Math.max(-90,Math.min(90,o)):0,v=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,b=Number.isFinite(a)&&a>0?Math.min(a,1e6):1,M=Number.isFinite(r)&&r>0?Math.min(r,1e6):1,w=Number.isFinite(s)&&s>0?Math.min(s,1e6):1;f===t&&x===o&&v===n&&b===a&&M===r&&w===s||u.warn(`Clamped invalid geometry values for voxel ${g}:`,{original:{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s},clamped:{safeCenterLon:f,safeCenterLat:x,safeCenterAlt:v,safeCellSizeX:b,safeCellSizeY:M,safeBoxHeight:w}});const S=Boolean(c&&!y),z={dimensions:new i.Cartesian3(b,M,w),outline:S};S&&(z.outlineColor=h,z.outlineWidth=Math.max(p||1,1));const R={position:i.Cartesian3.fromDegrees(f,x,v),box:z,properties:{type:"voxel",key:g,count:m.count,x:m.x,y:m.y,z:m.z},description:this.createVoxelDescription(m,g)};if(m.spatialId&&(R.properties.spatialId=m.spatialId),m.layerTop&&(R.properties.layerTop=m.layerTop),m.layerStats){const e={};for(const[t,i]of m.layerStats)e[t]=i;R.properties.layerStats=e}this.options.wireframeOnly||"emulation-only"===this.options.outlineRenderMode?(R.box.material=i.Color.TRANSPARENT,R.box.fill=!1):(R.box.material=l.withAlpha(d),R.box.fill=!0);const _=this.viewer.entities.add(R);return this.entities.push(_),_}createInsetOutline(e){const{centerLon:t,centerLat:o,centerAlt:n,baseSizeX:a,baseSizeY:r,baseSizeZ:s,outlineColor:l,outlineWidth:d,voxelKey:c,insetAmount:h=null}=e,p=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,m=Number.isFinite(o)?Math.max(-90,Math.min(90,o)):0,g=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,y=Number.isFinite(a)&&a>0?Math.min(a,1e6):1,f=Number.isFinite(r)&&r>0?Math.min(r,1e6):1,x=Number.isFinite(s)&&s>0?Math.min(s,1e6):1,v=.2*y,b=.2*f,M=.2*x,w=null!==h?h:this.options.outlineInset,S=Math.min(w,v),z=Math.min(w,b),R=Math.min(w,M),_=Math.max(y-2*S,.1*y),O=Math.max(f-2*z,.1*f),C=Math.max(x-2*R,.1*x),V=this.viewer.entities.add({position:i.Cartesian3.fromDegrees(p,m,g),box:{dimensions:new i.Cartesian3(_,O,C),fill:!1,outline:!0,outlineColor:l,outlineWidth:Math.max(d||1,1)},properties:{type:"voxel-inset-outline",parentKey:c,insetSize:{x:_,y:O,z:C}}});return this.entities.push(V),this.options.enableThickFrames&&(S>.1||z>.1||R>.1)&&this.createThickOutlineFrames({centerLon:p,centerLat:m,centerAlt:g,outerX:y,outerY:f,outerZ:x,innerX:_,innerY:O,innerZ:C,frameColor:l,voxelKey:c}),u.debug(`Inset outline created for voxel ${c}:`,{originalSize:{x:a,y:r,z:s},insetSize:{x:_,y:O,z:C},effectiveInset:{x:S,y:z,z:R}}),V}createThickOutlineFrames(e){const{centerLon:t,centerLat:o,centerAlt:n,outerX:a,outerY:r,outerZ:s,innerX:l,innerY:d,innerZ:c,frameColor:h,voxelKey:p}=e;let m=(a-l)/2,g=(r-d)/2,y=(s-c)/2;const f=.05;if(m<=0||g<=0||y<=0)return u.warn(`Invalid frame thickness for voxel ${p}, skipping thick frames`),[];m=Math.max(m,f),g=Math.max(g,f),y=Math.max(y,f);const x=a/2,v=r/2,b=s/2,M=[],w=[{x,z:b,sizeX:m,sizeZ:y},{x:-x,z:b,sizeX:m,sizeZ:y},{x,z:-b,sizeX:m,sizeZ:y},{x:-x,z:-b,sizeX:m,sizeZ:y}],S=[{x,y:v,sizeX:m,sizeY:g},{x:-x,y:v,sizeX:m,sizeY:g},{x,y:-v,sizeX:m,sizeY:g},{x:-x,y:-v,sizeX:m,sizeY:g}];return[{y:v,z:b,sizeY:g,sizeZ:y},{y:-v,z:b,sizeY:g,sizeZ:y},{y:v,z:-b,sizeY:g,sizeZ:y},{y:-v,z:-b,sizeY:g,sizeZ:y}].forEach((e,r)=>{const s=i.Cartesian3.fromDegrees(t,o+e.y/111320,n+e.z),l=this.viewer.entities.add({position:s,box:{dimensions:new i.Cartesian3(a,e.sizeY,e.sizeZ),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-x",parentKey:p,frameIndex:r}});this.entities.push(l),M.push(l)}),w.forEach((e,a)=>{const s=i.Cartesian3.fromDegrees(t+e.x/(111320*Math.cos(o*Math.PI/180)),o,n+e.z),l=this.viewer.entities.add({position:s,box:{dimensions:new i.Cartesian3(e.sizeX,r,e.sizeZ),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-y",parentKey:p,frameIndex:a}});this.entities.push(l),M.push(l)}),S.forEach((e,a)=>{const r=i.Cartesian3.fromDegrees(t+e.x/(111320*Math.cos(o*Math.PI/180)),o+e.y/111320,n),l=this.viewer.entities.add({position:r,box:{dimensions:new i.Cartesian3(e.sizeX,e.sizeY,s),fill:!0,material:h.withAlpha(.3),outline:!1},properties:{type:"voxel-thick-frame-z",parentKey:p,frameIndex:a}});this.entities.push(l),M.push(l)}),u.debug(`Created ${M.length} thick frame entities for voxel ${p}`),M}createEdgePolylines(e){const{centerLon:t,centerLat:o,centerAlt:n,cellSizeX:a,cellSizeY:r,boxHeight:s,outlineColor:l,outlineWidth:d,voxelKey:c}=e,h=[],p=Number.isFinite(t)?Math.max(-180,Math.min(180,t)):0,m=Number.isFinite(o)?Math.max(-85,Math.min(85,o)):0,g=Number.isFinite(n)?Math.max(-1e4,Math.min(1e5,n)):0,y=Number.isFinite(a)&&a>0?Math.min(a,1e5):1,f=Number.isFinite(r)&&r>0?Math.min(r,1e5):1,x=Number.isFinite(s)&&s>0?Math.min(s,1e5):1;if(y<.001||f<.001||x<.001)return u.warn(`Dimensions too small for voxel ${c}, skipping edge polylines`),h;const v=y/2,b=f/2,M=x/2,w=Math.cos(m*Math.PI/180),S=v/(111320*Math.max(.1,Math.abs(w))),z=b/111320;if(!Number.isFinite(S)||!Number.isFinite(z)||Math.abs(S)>.1||Math.abs(z)>.1)return u.warn(`Coordinate offsets out of range for voxel ${c}, skipping edge polylines`),h;const R=[[p-S,m-z,g-M],[p+S,m-z,g-M],[p+S,m+z,g-M],[p-S,m+z,g-M],[p-S,m-z,g+M],[p+S,m-z,g+M],[p+S,m+z,g+M],[p-S,m+z,g+M]];if(!R.every(([e,t,i])=>Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(i)&&e>=-180&&e<=180&&t>=-85&&t<=85&&i>=-5e4&&i<=5e5))return u.warn(`Invalid vertex coordinates for voxel ${c}, skipping edge polylines`),h;let _;try{_=R.map(([e,t,o])=>i.Cartesian3.fromDegrees(e,t,o))}catch(e){return u.warn(`Failed to create Cartesian3 vertices for voxel ${c}:`,e),h}return _.every(e=>e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.z))?([[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]].forEach((e,t)=>{try{const i=_[e[0]],o=_[e[1]];if(!i||!o)return void u.warn(`Missing vertices for edge ${t} in voxel ${c}`);const n=[i,o];if(2!==n.length)return void u.warn(`Invalid positions array length for edge ${t} in voxel ${c}`);const a=this.viewer.entities.add({polyline:{positions:n,width:Math.max(Math.min(d,20),1),material:l,clampToGround:!1},properties:{type:"voxel-edge-polyline",parentKey:c,edgeIndex:t}});this.entities.push(a),h.push(a)}catch(e){u.warn(`Failed to create polyline for edge ${t} in voxel ${c}:`,e)}}),u.debug(`Created ${h.length} edge polylines for voxel ${c}`),h):(u.warn(`Generated vertices contain invalid values for voxel ${c}, skipping edge polylines`),h)}createVoxelDescription(e,t){const i=e.spatialId?`\n <tr><td><b>空間ID:</b></td><td>${E(e.spatialId.id)}</td></tr>\n <tr><td><b>ズームレベル:</b></td><td>Z=${E(String(e.spatialId.z))}, F=${E(String(e.spatialId.f))}</td></tr>\n <tr><td><b>タイル座標:</b></td><td>X=${E(String(e.spatialId.x))}, Y=${E(String(e.spatialId.y))}</td></tr>\n `:"";let o="";if(this.options.aggregation?.enabled&&!1!==this.options.aggregation?.showInDescription&&e.layerStats&&e.layerStats.size>0){const t=Array.from(e.layerStats.entries()).sort((e,t)=>t[1]-e[1]).map(([t,i])=>{const o=e.count>0?(i/e.count*100).toFixed(1):"0.0";return`\n <tr><td style="padding-left: 10px;">${E(t)}</td><td>${i} (${o}%)</td></tr>\n `}).join("");o=`\n ${e.layerTop?`\n <tr><td><b>支配的レイヤ:</b></td><td>${E(e.layerTop)}</td></tr>\n `:""}\n <tr><td colspan="2"><b>レイヤ内訳:</b></td></tr>\n ${t}\n `}return`\n <div style="padding: 10px; font-family: Arial, sans-serif;">\n <h3 style="margin-top: 0;">ボクセル [${e.x}, ${e.y}, ${e.z}]</h3>\n <table style="width: 100%;">\n <tr><td><b>エンティティ数:</b></td><td>${e.count}</td></tr>\n <tr><td><b>ボクセルキー:</b></td><td>${E(t)}</td></tr>\n <tr><td><b>座標:</b></td><td>X=${e.x}, Y=${e.y}, Z=${e.z}</td></tr>${i}${o}\n </table>\n <p style="margin-bottom: 0;">\n <small>v0.1.18 GeometryRenderer (Layer aggregation support)</small>\n </p>\n </div>\n `}shouldApplyInsetOutline(e){switch(this.options.outlineInsetMode||"all"){case"topn":return e;case"all":default:return!0;case"none":return!1}}clear(){u.debug("GeometryRenderer.clear - Removing",this.entities.length,"entities"),this.entities.forEach(e=>{try{const t=!(!e||"function"!=typeof e.isDestroyed)&&e.isDestroyed();e&&!t&&this.viewer.entities.remove(e)}catch(e){u.warn("Entity removal error:",e)}}),this.entities=[]}renderBoundingBox(e){if(e)try{const t=(e.minLon+e.maxLon)/2,o=(e.minLat+e.maxLat)/2,n=(e.minAlt+e.maxAlt)/2,a=111e3*(e.maxLon-e.minLon)*Math.cos(o*Math.PI/180),r=111e3*(e.maxLat-e.minLat),s=e.maxAlt-e.minAlt,l=this.viewer.entities.add({position:i.Cartesian3.fromDegrees(t,o,n),box:{dimensions:new i.Cartesian3(a,r,s),material:i.Color.YELLOW.withAlpha(.1),outline:!0,outlineColor:i.Color.YELLOW.withAlpha(.3),outlineWidth:2},description:`Bounding Box<br>Size: ${a.toFixed(1)} x ${r.toFixed(1)} x ${s.toFixed(1)} m`});this.entities.push(l),u.debug("Debug bounding box added:",{center:{lon:t,lat:o,alt:n},size:{width:a,depth:r,height:s}})}catch(e){u.warn("Failed to render bounding box:",e)}}getEntityCount(){return this.entities.length}updateOptions(e){this.options={...this.options,...e},u.debug("GeometryRenderer options updated:",this.options)}getConfiguration(){return{...this.options,entityCount:this.entities.length,version:"0.1.11",phase:"ADR-0009 Phase 4"}}}class T{constructor(e,t={}){this.viewer=e,this.options={minColor:[0,0,255],maxColor:[255,0,0],opacity:.8,emptyOpacity:.03,showOutline:!0,showEmptyVoxels:!1,wireframeOnly:!1,heightBased:!1,outlineWidth:2,outlineInset:0,outlineInsetMode:"all",outlineRenderMode:"standard",emulationScope:"off",adaptiveOutlines:!1,outlineWidthPreset:"medium",...t},this.voxelSelector=new N(this.options),this._selectionStats=null,this.adaptiveController=new $(this.options),this.geometryRenderer=new k(this.viewer,this.options),Object.defineProperty(this,"voxelEntities",{get:()=>this.geometryRenderer.entities,enumerable:!0,configurable:!0}),this._currentVoxelData=null,u.debug("VoxelRenderer initialized with options:",this.options)}_calculateAdaptiveParams(e,t,i,o,n){return this.adaptiveController.calculateAdaptiveParams(e,t,i,o,this.options,n)}_shouldApplyInsetOutline(e){return this.geometryRenderer.shouldApplyInsetOutline(e)}render(e,t,i,o){this.geometryRenderer.clear(),u.debug("VoxelRenderer.render - Starting render with simplified approach",{voxelDataSize:e.size,bounds:t,grid:i,statistics:o}),this._currentVoxelData=e,this._shouldShowBounds()&&this.geometryRenderer.renderBoundingBox(t);let n=[];const a=new Set;if(this.options.showEmptyVoxels){const t=Math.min(i.totalVoxels,this.options.maxRenderVoxels||1e4);u.debug(`Generating grid for up to ${t} voxels`);for(let o=0;o<i.numVoxelsX;o++){for(let a=0;a<i.numVoxelsY;a++){for(let r=0;r<i.numVoxelsZ;r++){const i=`${o},${a},${r}`,s=e.get(i)||{x:o,y:a,z:r,count:0};if(n.push({key:i,info:s}),n.length>=t){u.debug(`Reached maximum voxel limit of ${t}`);break}}if(n.length>=t)break}if(n.length>=t)break}}else if(n=Array.from(e.entries()).map(([e,t])=>({key:e,info:t})),this.options.maxRenderVoxels&&n.length>this.options.maxRenderVoxels){const e=this._selectVoxelsForRendering(n,this.options.maxRenderVoxels,t,i);n=e.selectedVoxels,this._selectionStats={strategy:e.strategy,clippedNonEmpty:e.clippedNonEmpty,coverageRatio:e.coverageRatio||0},u.debug(`Applied ${e.strategy} strategy: ${n.length} voxels selected, ${e.clippedNonEmpty} clipped`)}this.options.highlightTopN&&this.options.highlightTopN>0&&([...n].sort((e,t)=>t.info.count-e.info.count).slice(0,this.options.highlightTopN).forEach(e=>a.add(e.key)),u.debug(`TopN highlight enabled: ${a.size} voxels will be highlighted`)),u.debug(`Rendering ${n.length} voxels`);let r=0;const s={x:0,y:0,z:0,count:0},l={voxel:s,isTopN:!1,normalizedDensity:0,statistics:o,adaptiveParams:null},d={voxel:s,isTopN:!1,normalizedDensity:0,statistics:o,adaptiveParams:null};return n.forEach(({key:e,info:n})=>{try{r+=this._renderSingleVoxel(e,n,t,i,o,a,s,l,d)}catch(e){u.warn("Error rendering voxel:",e)}}),u.info(`Successfully rendered ${r} voxels`),this._currentVoxelData=null,r}_renderSingleVoxel(e,t,i,o,n,a,r,s,l){const d=a.has(e),c=this._calculateVoxelRenderingParams(t,i,o,n,d,r,s,l);return c?(this._delegateVoxelRendering(e,c),1):0}_calculateVoxelRenderingParams(e,t,o,n,a,r,s,l){if(!(e&&t&&o&&n))return null;let d,c,u,h,p,m;if(e.bounds&&Array.isArray(e.bounds)&&8===e.bounds.length){const t=e.bounds;d=t.reduce((e,t)=>e+t.lng,0)/8,c=t.reduce((e,t)=>e+t.lat,0)/8,u=t.reduce((e,t)=>e+t.alt,0)/8;const o=i.Cartesian3.fromDegrees(t[0].lng,t[0].lat,t[0].alt),n=i.Cartesian3.fromDegrees(t[1].lng,t[1].lat,t[1].alt),a=i.Cartesian3.fromDegrees(t[3].lng,t[3].lat,t[3].alt),r=i.Cartesian3.fromDegrees(t[4].lng,t[4].lat,t[4].alt);h=i.Cartesian3.distance(o,n),p=i.Cartesian3.distance(o,a),m=i.Cartesian3.distance(o,r)}else{const{x:i,y:n,z:a}=e;d=t.minLon+(i+.5)*(t.maxLon-t.minLon)/o.numVoxelsX,c=t.minLat+(n+.5)*(t.maxLat-t.minLat)/o.numVoxelsY,u=t.minAlt+(a+.5)*(t.maxAlt-t.minAlt)/o.numVoxelsZ,h=o.cellSizeX||(o.lonRangeMeters?o.lonRangeMeters/o.numVoxelsX:o.voxelSizeMeters),p=o.cellSizeY||(o.latRangeMeters?o.latRangeMeters/o.numVoxelsY:o.voxelSizeMeters),m=o.cellSizeZ||(o.altRangeMeters?Math.max(o.altRangeMeters/Math.max(o.numVoxelsZ,1),1):Math.max(o.voxelSizeMeters,1))}const g=n.maxCount>n.minCount?(e.count-n.minCount)/(n.maxCount-n.minCount):0,y=this._calculateAdaptiveParams(e,a,this._currentVoxelData,n,o),{color:f,opacity:x}=this._calculateColorAndOpacity(e,g,a,y,n,r,l);let v,b,M;if(e.bounds){v=h,b=p;let e=m;this.options.voxelGap>0&&(v=Math.max(h-this.options.voxelGap,.1*h),b=Math.max(p-this.options.voxelGap,.1*p),e=Math.max(m-this.options.voxelGap,.1*m)),M=e,this.options.heightBased&&(M=e*(.1+.9*g))}else{const e=this._calculateDimensions(o,g);v=e.cellSizeX,b=e.cellSizeY,M=e.boxHeight}return{centerLon:d,centerLat:c,centerAlt:u,cellSizeX:v,cellSizeY:b,boxHeight:M,color:f,opacity:x,...this._calculateOutlineProperties(e,a,g,y,n,f,r,s),voxelInfo:e,isTopN:a,adaptiveParams:y}}_calculateColorAndOpacity(e,t,o,n,a,r,s){let l,d;if(0===e.count)l=i.Color.LIGHTGRAY,d=this.options.emptyOpacity;else{if(l=L.calculateColor(t,e.count,this.options),this.options.boxOpacityResolver&&"function"==typeof this.options.boxOpacityResolver){r.x=e.x,r.y=e.y,r.z=e.z,r.count=e.count,s.isTopN=o,s.normalizedDensity=t,s.adaptiveParams=n;try{const e=this.options.boxOpacityResolver(s);d=isNaN(e)?this.options.opacity:Math.max(0,Math.min(1,e))}catch(e){u.warn("boxOpacityResolver error, using fallback:",e),d=n.boxOpacity||this.options.opacity}}else d=n.boxOpacity||this.options.opacity;this.options.highlightTopN&&!o&&(d*=1-(this.options.highlightStyle?.boostOpacity||.2))}return{color:l,opacity:d}}_calculateDimensions(e,t){let i=e.cellSizeX||(e.lonRangeMeters?e.lonRangeMeters/e.numVoxelsX:e.voxelSizeMeters),o=e.cellSizeY||(e.latRangeMeters?e.latRangeMeters/e.numVoxelsY:e.voxelSizeMeters),n=e.cellSizeZ||(e.altRangeMeters?Math.max(e.altRangeMeters/Math.max(e.numVoxelsZ,1),1):Math.max(e.voxelSizeMeters,1));this.options.voxelGap>0&&(i=Math.max(i-this.options.voxelGap,.1*i),o=Math.max(o-this.options.voxelGap,.1*o),n=Math.max(n-this.options.voxelGap,.1*n));let a=n;return this.options.heightBased&&(a=n*(.1+.9*t)),{cellSizeX:i,cellSizeY:o,boxHeight:a}}_calculateOutlineProperties(e,t,i,o,n,a,r,s){let l;if(this.options.outlineWidthResolver&&"function"==typeof this.options.outlineWidthResolver){r.x=e.x,r.y=e.y,r.z=e.z,r.count=e.count,s.isTopN=t,s.normalizedDensity=i,s.adaptiveParams=o;try{l=this.options.outlineWidthResolver(s),isNaN(l)&&(l=o.outlineWidth||this.options.outlineWidth)}catch(e){u.warn("outlineWidthResolver error, using fallback:",e),l=o.outlineWidth||this.options.outlineWidth}}else l=this.options.adaptiveOutlines&&null!==o.outlineWidth?o.outlineWidth:t&&this.options.highlightTopN&&this.options.highlightStyle?.outlineWidth||this.options.outlineWidth;const d=o.outlineOpacity||(this.options.outlineOpacity??1),c=a.withAlpha(d),h=this._determineRenderModeConfig();let p=h.shouldUseEmulationOnly;if(!h.shouldUseEmulationOnly){const e=this.options.emulationScope||"off";"topn"===e?p=t&&(l||1)>1:"non-topn"===e?p=!t&&(l||1)>1:"all"===e?p=(l||1)>1:this.options.adaptiveOutlines&&o.shouldUseEmulation&&(p="off"!==e)}return{shouldShowOutline:h.shouldShowStandardOutline,outlineColor:c,outlineWidth:l||1,shouldShowInsetOutline:h.shouldShowInsetOutline,emulateThick:p}}_determineRenderModeConfig(){let e=!0,t=!1,i=!1;switch(this.options.outlineRenderMode){case"standard":e=this.options.showOutline,t=this.options.outlineInset>0;break;case"inset":e=!1,t=!0;break;case"emulation-only":e=!1,t=!1,i=!0}return{shouldShowStandardOutline:e,shouldShowInsetOutline:t,shouldUseEmulationOnly:i}}_delegateVoxelRendering(e,t){if(this.geometryRenderer.createVoxelBox({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,cellSizeX:t.cellSizeX,cellSizeY:t.cellSizeY,boxHeight:t.boxHeight,color:t.color,opacity:t.opacity,shouldShowOutline:t.shouldShowOutline,outlineColor:t.outlineColor,outlineWidth:t.outlineWidth,voxelInfo:t.voxelInfo,voxelKey:e,emulateThick:t.emulateThick}),t.shouldShowInsetOutline&&this.geometryRenderer.shouldApplyInsetOutline(t.isTopN))try{const i=this.options.outlineInset>0?this.options.outlineInset:1;this.geometryRenderer.createInsetOutline({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,baseSizeX:t.cellSizeX,baseSizeY:t.cellSizeY,baseSizeZ:t.boxHeight,outlineColor:t.outlineColor,outlineWidth:Math.max(t.outlineWidth,1),voxelKey:e,insetAmount:i})}catch(e){u.warn("Failed to create inset outline:",e)}if(("emulation-only"===this.options.outlineRenderMode||this.options.emulationScope&&"off"!==this.options.emulationScope)&&t.emulateThick)try{this.geometryRenderer.createEdgePolylines({centerLon:t.centerLon,centerLat:t.centerLat,centerAlt:t.centerAlt,cellSizeX:t.cellSizeX,cellSizeY:t.cellSizeY,boxHeight:t.boxHeight,outlineColor:t.outlineColor,outlineWidth:Math.max(t.outlineWidth,1),voxelKey:e})}catch(e){u.warn("Failed to add emulated thick outline polylines:",e)}}interpolateColor(e,t=null){return L.calculateColor(e,t,this.options)}clear(){this.geometryRenderer.clear()}_shouldShowBounds(){return!!this.options.debug&&("boolean"==typeof this.options.debug?this.options.debug:"object"==typeof this.options.debug&&null!==this.options.debug&&!0===this.options.debug.showBounds)}setVisible(e){u.debug("VoxelRenderer.setVisible:",e),this.voxelEntities.forEach(t=>{!t||t.isDestroyed&&t.isDestroyed()||(t.show=e)})}_selectVoxelsForRendering(e,t,i,o){const n=this.voxelSelector.selectVoxels(e,t,{grid:o,bounds:i});return this._selectionStats=this.voxelSelector.getLastSelectionStats(),n}getSelectionStats(){return this._selectionStats||null}}class W{constructor(e={}){this.options={position:"top-right",fpsAveragingWindowMs:1e3,autoUpdate:!0,...e},this.element=null,this.isVisible=!1,this.updateInterval=null,this.frameTimeHistory=[],this.lastUpdateTime=Date.now(),this._createOverlay()}_createOverlay(){this.element=document.createElement("div"),this.element.id="cesium-heatbox-perf-overlay",this.element.style.cssText=`\n position: absolute;\n ${this._getPositionStyles()}\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n padding: 10px;\n border-radius: 5px;\n font-family: 'Courier New', monospace;\n font-size: 12px;\n line-height: 1.4;\n z-index: 1000;\n min-width: 200px;\n user-select: none;\n pointer-events: auto;\n display: none;\n `;const e=document.createElement("button");e.textContent="×",e.style.cssText="\n position: absolute;\n top: 2px;\n right: 5px;\n background: none;\n border: none;\n color: #fff;\n font-size: 16px;\n cursor: pointer;\n padding: 0;\n width: 20px;\n height: 20px;\n ",e.onclick=()=>this.hide(),this.element.appendChild(e),this.contentElement=document.createElement("div"),this.contentElement.style.marginTop="15px",this.element.appendChild(this.contentElement),document.body.appendChild(this.element)}_getPositionStyles(){const e={"top-left":"top: 10px; left: 10px;","top-right":"top: 10px; right: 10px;","bottom-left":"bottom: 10px; left: 10px;","bottom-right":"bottom: 10px; right: 10px;"};return e[this.options.position]||e["top-right"]}show(){this.element&&(this.element.style.display="block",this.isVisible=!0,this.options.autoUpdate&&this.startAutoUpdate())}hide(){this.element&&(this.element.style.display="none",this.isVisible=!1,this.stopAutoUpdate())}toggle(){this.isVisible?this.hide():this.show()}update(e,t){if(!this.contentElement||!this.isVisible)return;void 0!==t&&this._trackFrameTime(t);const i=this._calculateFPS(),o=this._formatStats(e,i,t);this.contentElement.innerHTML=o}_trackFrameTime(e){const t=Date.now();this.frameTimeHistory.push({time:t,frameTime:e});const i=t-this.options.fpsAveragingWindowMs;this.frameTimeHistory=this.frameTimeHistory.filter(e=>e.time>i)}_calculateFPS(){if(this.frameTimeHistory.length<2)return 0;const e=this.frameTimeHistory.reduce((e,t)=>e+t.frameTime,0)/this.frameTimeHistory.length;return e>0?Math.round(1e3/e):0}_formatStats(e,t,i){const o=[];if(o.push('<div style="font-weight: bold; color: #4CAF50;">🚀 Performance Stats</div>'),o.push(""),t>0){const e=t>=30?"#4CAF50":t>=15?"#FF9800":"#F44336";o.push(`<div style="color: ${e};">FPS: ${t}</div>`)}if(void 0!==i){const e=i<=33?"#4CAF50":i<=66?"#FF9800":"#F44336";o.push(`<div style="color: ${e};">Frame: ${i.toFixed(1)}ms</div>`)}if(o.push(""),e){if(o.push('<div style="font-weight: bold;">Voxels:</div>'),o.push(` Total: ${e.totalVoxels||0}`),o.push(` Rendered: ${e.renderedVoxels||0}`),e.totalVoxels>0){const t=((e.renderedVoxels||0)/e.totalVoxels*100).toFixed(1);o.push(` Ratio: ${t}%`)}if(e.topNCount&&o.push(` TopN: ${e.topNCount}`),o.push(""),e.selectionStrategy&&(o.push('<div style="font-weight: bold;">Strategy:</div>'),o.push(` Selection: ${e.selectionStrategy}`),void 0!==e.coverageRatio&&o.push(` Coverage: ${(100*e.coverageRatio).toFixed(1)}%`),e.renderBudgetTier&&o.push(` Budget Tier: ${e.renderBudgetTier}`),o.push("")),e.adaptive){if(o.push('<div style="font-weight: bold; color: #2196F3;">📊 Adaptive Control:</div>'),void 0!==e.adaptive.denseModeCount){const t=e.renderedVoxels>0?(e.adaptive.denseModeCount/e.renderedVoxels*100).toFixed(1):"0.0";o.push(` Dense Areas: ${e.adaptive.denseModeCount} (${t}%)`)}if(void 0!==e.adaptive.emulationModeCount){const t=e.renderedVoxels>0?(e.adaptive.emulationModeCount/e.renderedVoxels*100).toFixed(1):"0.0";o.push(` Emulation: ${e.adaptive.emulationModeCount} (${t}%)`)}if(void 0!==e.adaptive.avgOutlineWidth){const t=e.adaptive.avgOutlineWidth>=1&&e.adaptive.avgOutlineWidth<=3?"#4CAF50":"#FF9800";o.push(` <span style="color: ${t};">Avg Width: ${e.adaptive.avgOutlineWidth.toFixed(2)}px</span>`)}if(void 0!==e.adaptive.overlapDetections){const t=e.renderedVoxels>0?(e.adaptive.overlapDetections/e.renderedVoxels*100).toFixed(1):"0.0",i=e.adaptive.overlapDetections>0?"#FF9800":"#4CAF50";o.push(` <span style="color: ${i};">Overlaps: ${e.adaptive.overlapDetections} (${t}%)</span>`)}void 0!==e.adaptive.zScaleAdjustments&&e.adaptive.zScaleAdjustments>0&&o.push(` Z-Scale Adj: ${e.adaptive.zScaleAdjustments}`),o.push("")}if(void 0!==e.renderTimeMs){const t=e.renderTimeMs<=50?"#4CAF50":e.renderTimeMs<=100?"#FF9800":"#F44336";o.push(`<div style="color: ${t};">Render Time: ${e.renderTimeMs.toFixed(1)}ms</div>`)}if(void 0!==e.memoryUsageMB){const t=e.memoryUsageMB<=50?"#4CAF50":e.memoryUsageMB<=100?"#FF9800":"#F44336";o.push(`<div style="color: ${t};">Memory: ${e.memoryUsageMB.toFixed(1)}MB</div>`)}}return o.join("<br>")}startAutoUpdate(){this.stopAutoUpdate(),this.updateInterval=setInterval(()=>{},100)}stopAutoUpdate(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null)}destroy(){this.stopAutoUpdate(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.contentElement=null}}class B{constructor(e,t={}){if(!function(e){if(!e)return!1;if(!e.scene||!e.entities||!e.scene.canvas)return!1;const t=e.scene.canvas;return!!(t.getContext("webgl2")||t.getContext("webgl")||t.getContext("experimental-webgl"))}(e))throw new Error("CesiumJS Viewerが無効です");this.viewer=e;let i={...t||{}};i.profile&&g().includes(i.profile)&&(i=f(i.profile,i),delete i.profile);const a={...o,...i};this.options=M(function(e){if("auto"!==e.renderBudgetMode&&"auto"!==e.maxRenderVoxels)return e;const t=function(){try{const e=function(){try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return{webgl2:!1,maxTextureSize:0,maxRenderbufferSize:0};const i={webgl2:!!e.getContext("webgl2"),maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:t.getParameter(t.MAX_RENDERBUFFER_SIZE)};return e.remove(),i}catch(e){return u.warn("WebGL info detection failed:",e),{webgl2:!1,maxTextureSize:0,maxRenderbufferSize:0}}}(),t=function(){try{return{deviceMemory:navigator.deviceMemory||null,hardwareConcurrency:navigator.hardwareConcurrency||null,devicePixelRatio:window.devicePixelRatio||1,screenPixels:screen.width*screen.height*Math.pow(window.devicePixelRatio||1,2),userAgent:navigator.userAgent}}catch(e){return u.warn("Device info detection failed:",e),{deviceMemory:null,hardwareConcurrency:null,devicePixelRatio:1,screenPixels:2073600,userAgent:""}}}();let i="mid",o="fallback";if(null!==t.deviceMemory)i=t.deviceMemory<=4?"low":t.deviceMemory<=8?"mid":"high",o="deviceMemory";else if(null!==t.hardwareConcurrency){const e=t.hardwareConcurrency*Math.min(t.screenPixels/2073600,2);i=e<=4?"low":e<=8?"mid":"high",o="hardwareConcurrency+resolution"}(e.maxTextureSize<4096||!e.webgl2)&&(i="high"===i?"mid":"low",o+="+webglLimits");const a=z[i];let r=Math.min(Math.floor((a.min+a.max)/2),n);try{const e=navigator&&navigator.userAgent?navigator.userAgent:"",t=/iPhone|iPad|iPod|Android/i.test(e),i=/Safari\//.test(e)&&!/Chrome\//.test(e);(t||i)&&(r=Math.min(r,12e3))}catch(e){}return u.debug(`Device tier detected: ${i} (${o}), maxRenderVoxels: ${r}`),{tier:i,maxRenderVoxels:r,detectionMethod:o,deviceInfo:t,webglInfo:e}}catch(e){return u.warn("Device tier detection failed, using default mid tier:",e),{tier:"mid",maxRenderVoxels:Math.min(25e3,n),detectionMethod:"error-fallback",deviceInfo:null,webglInfo:null}}}(),i={...e,maxRenderVoxels:t.maxRenderVoxels,_autoRenderBudget:{tier:t.tier,detectionMethod:t.detectionMethod,autoMaxRenderVoxels:t.maxRenderVoxels}};return u.info(`Auto Render Budget applied: ${t.tier} tier, maxRenderVoxels: ${t.maxRenderVoxels}`),i}(a)),u.setLogLevel(this.options),this.renderer=new T(this.viewer,this.options),this._bounds=null,this._grid=null,this._voxelData=null,this._statistics=null,this._spatialIdEdgeCaseMetrics=null,this._eventHandler=null,this._performanceOverlay=null,this._lastRenderTime=null,this._overlayLastUpdate=0,this._postRenderListener=null,this._prevFrameTimestamp=null,this._initializeEventListeners(),this.options.performanceOverlay&&this.options.performanceOverlay.enabled&&this._initializePerformanceOverlay()}getEffectiveOptions(){try{return JSON.parse(JSON.stringify(this.options))}catch(e){return{...this.options}}}static listProfiles(){return g()}static getProfileDetails(e){return y(e)}_initializePerformanceOverlay(){if("undefined"==typeof window)return void u.warn("Performance overlay requires browser environment");const e={position:"top-right",fpsAveragingWindowMs:1e3,autoUpdate:!0,updateIntervalMs:500,...this.options.performanceOverlay};this._performanceOverlay=new W(e),e.autoShow&&this._performanceOverlay.show(),u.debug("Performance overlay initialized"),this._hookPerformanceOverlayUpdates()}togglePerformanceOverlay(){return this._performanceOverlay?(this._performanceOverlay.toggle(),this._performanceOverlay.isVisible):(u.warn("Performance overlay not initialized. Set performanceOverlay.enabled: true in options."),!1)}showPerformanceOverlay(){this._performanceOverlay&&this._performanceOverlay.show()}hidePerformanceOverlay(){this._performanceOverlay&&this._performanceOverlay.hide()}setPerformanceOverlayEnabled(e,t={}){if(e)return this._performanceOverlay?(t&&Object.keys(t).length>0&&(this._performanceOverlay.options={...this._performanceOverlay.options,...t}),this._performanceOverlay.show()):(this.options.performanceOverlay={enabled:!0,...this.options.performanceOverlay||{},...t},this._initializePerformanceOverlay()),!0;if(this._performanceOverlay&&this._performanceOverlay.hide(),this._postRenderListener){try{this.viewer.scene.postRender.removeEventListener(this._postRenderListener)}catch(e){u.debug("postRender listener removal failed (non-fatal)")}this._postRenderListener=null}return!1}_estimateMemoryUsage(){try{const e=this.renderer?.geometryRenderer?.entities?.length||this.renderer?.voxelEntities?.length||0;let t=0;this._voxelData&&(this._voxelData instanceof Map||"number"==typeof this._voxelData.size?t=this._voxelData.size:Array.isArray(this._voxelData)?t=this._voxelData.length:"object"==typeof this._voxelData&&(t=Object.keys(this._voxelData).length));const i=(1024*e+100*t)/1048576;return Math.max(.1,i)}catch(e){return 0}}async setData(e){if(b(e))try{if(u.debug("Heatbox.setData - 処理開始:",e.length,"個のエンティティ"),u.debug("Step 1: 境界計算"),this._bounds=R.calculateBounds(e),!this._bounds)return u.error("境界計算に失敗"),void this.clear();u.debug("境界計算完了:",this._bounds);let t=this.options.voxelSize||o.voxelSize,i=null;if(this.options.autoVoxelSize&&!this.options.voxelSize)try{u.debug("自動ボクセルサイズ調整開始");const o={autoVoxelSizeMode:this.options.autoVoxelSizeMode,autoVoxelTargetFill:this.options.autoVoxelTargetFill,maxRenderVoxels:this.options.maxRenderVoxels},r=function(e,t,i={}){try{return"occupancy"===(i.autoVoxelSizeMode||"basic")?function(e,t,i){const o=S(e),n=i.maxRenderVoxels||5e4,r=i.autoVoxelTargetFill||.6;let s=w(e,t);u.debug(`Starting occupancy-based estimation: N=${t}, target=${r}, maxVoxels=${n}`);for(let i=0;i<10;i++){(!Number.isFinite(s)||s<=0)&&(u.warn(`Invalid currentSize detected: ${s}, using fallback`),s=w(e,t),(!Number.isFinite(s)||s<=0)&&(s=5));const l=Math.max(1,Math.ceil(Math.max(0,o.x)/s))*Math.max(1,Math.ceil(Math.max(0,o.y)/s))*Math.max(1,Math.ceil(Math.max(0,o.z)/s));if(!Number.isFinite(l)||l<=0||l>1e9){u.warn(`Invalid totalVoxels calculated: ${l}, breaking iteration`);break}const d=l*(1-Math.exp(-t/l)),c=Math.min(d/n,1);if(u.debug(`Iteration ${i}: size=${s.toFixed(1)}m, totalVoxels=${l}, expectedOccupied=${d.toFixed(0)}, fill=${c.toFixed(3)}`),Math.abs(c-r)<.05){u.debug(`Converged at iteration ${i}: size=${s.toFixed(1)}m, fill=${c.toFixed(3)}`);break}const h=Math.max(.1,Math.min(10,c/r));s*=Math.pow(h,.3),s=Math.max(5,Math.min(a,s))}const l=Math.round(s);return u.info(`Occupancy-based voxel size: ${l}m (target fill: ${r})`),l}(e,t,i):w(e,t)}catch(e){return u.warn("Initial voxel size estimation failed:",e),20}}(this._bounds,e.length,o),s=_.createGrid(this._bounds,r),l=function(e,t){const i={valid:!0,warning:!1,error:null,recommendedSize:null};if(e>n){i.valid=!1,i.error="ボクセル数が上限を超えています";const o=e/n,r=t*Math.pow(Math.max(1,Math.min(1e3,o)),1/3);i.recommendedSize=Math.ceil(Math.max(5,Math.min(a,r)))}else e>3e4&&(i.warning=!0,i.error="推定メモリ使用量が警告値を超えています");return i}(s.totalVoxels,r);!l.valid&&l.recommendedSize?(t=l.recommendedSize,i={enabled:!0,mode:this.options.autoVoxelSizeMode,originalSize:r,finalSize:t,adjusted:!0,reason:`Performance limit exceeded: ${s.totalVoxels} > 50000`},u.info(`Auto-adjusted voxelSize: ${r}m → ${t}m (${s.totalVoxels} voxels)`)):(t=r,i={enabled:!0,mode:this.options.autoVoxelSizeMode,originalSize:r,finalSize:t,adjusted:!1,reason:null},u.info(`Auto-determined voxelSize: ${t}m`))}catch(e){u.warn("Auto voxel size adjustment failed, using default:",e),t=o.voxelSize,i={enabled:!0,adjusted:!1,reason:"Estimation failed, using default size",originalSize:null,finalSize:t}}u.debug("Step 2: グリッド生成 (サイズ:",t,"m)"),this._grid=_.createGrid(this._bounds,t),u.debug("グリッド生成完了:",this._grid),u.debug("Step 3: エンティティ分類");const r={...this.options,voxelSize:t};this._voxelData=await I.classifyEntitiesIntoVoxels(e,this._bounds,this._grid,r),u.debug("エンティティ分類完了:",this._voxelData.size,"個のボクセル"),u.debug("Step 4: 統計計算"),this._statistics=I.calculateStatistics(this._voxelData,this._grid),u.debug("統計情報:",this._statistics),i&&(this._statistics.autoAdjusted=i.adjusted,this._statistics.originalVoxelSize=i.originalSize,this._statistics.finalVoxelSize=i.finalSize,this._statistics.adjustmentReason=i.reason),r.spatialId?.enabled?(this._statistics.spatialIdEnabled=!0,this._statistics.spatialIdMode=r.spatialId.mode,this._statistics.spatialIdProvider=r._spatialIdProvider||null,this._statistics.spatialIdZoom=r._resolvedZoom||null,this._statistics.zoomControl=r.spatialId.zoomControl):this._statistics.spatialIdEnabled=!1,u.debug("Step 5: 描画");const s="undefined"!=typeof performance&&performance.now?performance.now():Date.now(),l=this.renderer.render(this._voxelData,this._bounds,this._grid,this._statistics),d="undefined"!=typeof performance&&performance.now?performance.now():Date.now();if(this._lastRenderTime=Math.max(0,d-s),this._statistics.renderedVoxels=l,this._statistics.renderTimeMs=this._lastRenderTime,u.info("描画完了 - 実際の描画数:",l),this.options.autoView)try{u.debug("Auto view adjustment triggered"),await this.fitView(),u.debug("Auto view adjustment completed")}catch(e){u.warn("Auto view adjustment failed:",e)}if(u.debug("Heatbox.setData - 処理完了"),this._performanceOverlay&&this._performanceOverlay.isVisible){const e=this.getStatistics()||{};e.renderTimeMs=this._lastRenderTime,e.memoryUsageMB=this._estimateMemoryUsage(),this._performanceOverlay.update(e,void 0)}}catch(e){throw u.error("ヒートマップ作成エラー:",e),this.clear(),e}else this.clear()}async createFromEntities(e){if(!b(e))throw new Error(s);return await this.setData(e),this.getStatistics()}setVisible(e){this.renderer.setVisible(e)}clear(){this.renderer.clear(),this._bounds=null,this._grid=null,this._voxelData=null,this._statistics=null}destroy(){if(this.clear(),this._eventHandler&&!this._eventHandler.isDestroyed()&&this._eventHandler.destroy(),this._postRenderListener){try{this.viewer.scene.postRender.removeEventListener(this._postRenderListener)}catch(e){u.debug("postRender listener removal failed (non-fatal)")}this._postRenderListener=null}if(this._performanceOverlay){try{this._performanceOverlay.destroy()}catch(e){u.debug("overlay destroy failed (non-fatal)")}this._performanceOverlay=null}this._eventHandler=null}dispose(){this.destroy()}getOptions(){return{...this.options}}updateOptions(e){if(this.options=M({...this.options,...e}),this.renderer.options=this.options,this.renderer.adaptiveController&&"function"==typeof this.renderer.adaptiveController.updateOptions&&this.renderer.adaptiveController.updateOptions(this.options),this.renderer.geometryRenderer&&"function"==typeof this.renderer.geometryRenderer.updateOptions&&this.renderer.geometryRenderer.updateOptions(this.options),this._voxelData){const e=this.renderer.render(this._voxelData,this._bounds,this._grid,this._statistics);this._statistics.renderedVoxels=e}}_initializeEventListeners(){this._eventHandler=new i.ScreenSpaceEventHandler(this.viewer.scene.canvas),this._eventHandler.setInputAction(e=>{const t=this.viewer.scene.pick(e.position);if(i.defined(t)&&t.id&&t.id.properties&&"voxel"===t.id.properties.type){const e=t.id.properties.key,o={x:t.id.properties.x,y:t.id.properties.y,z:t.id.properties.z,count:t.id.properties.count},n=new i.Entity({id:`voxel-${e}`,description:this.renderer.createVoxelDescription(o,e)});this.viewer.selectedEntity=n}},i.ScreenSpaceEventType.LEFT_CLICK)}getStatistics(){if(!this._statistics)return null;const e={...this._statistics},t=this.renderer.getSelectionStats();t&&(e.selectionStrategy=t.strategy,e.clippedNonEmpty=t.clippedNonEmpty,e.coverageRatio=t.coverageRatio??0),this.options._autoRenderBudget&&(e.renderBudgetTier=this.options._autoRenderBudget.tier,e.autoMaxRenderVoxels=this.options._autoRenderBudget.autoMaxRenderVoxels),"number"==typeof this.options.maxRenderVoxels&&this.options.maxRenderVoxels>0?e.occupancyRatio=Math.min(1,Math.max(0,(e.renderedVoxels||0)/this.options.maxRenderVoxels)):e.occupancyRatio=null;const i=this.options&&this.options.spatialId?this.options.spatialId:{},o=Boolean(e.spatialIdEnabled),n=this._spatialIdEdgeCaseMetrics??null;if(e.spatialId={enabled:o,provider:o?e.spatialIdProvider??null:null,zoom:o?e.spatialIdZoom??null:null,zoomControl:e.zoomControl??i.zoomControl??null,edgeCaseMetrics:n},this.options.aggregation?.enabled&&this._voxelData){const t=new Map;for(const e of this._voxelData.values())if(e.layerStats)for(const[i,o]of e.layerStats)t.set(i,(t.get(i)||0)+o);const i=this.options.aggregation?.topN??10,o=Array.from(t.entries()).sort((e,t)=>t[1]-e[1]).slice(0,i);e.layers=o.map(([e,t])=>({key:e,total:t})),u.debug(`[aggregation] Aggregated ${t.size} unique layers, returning top ${e.layers.length}`)}return e}getBounds(){return this._bounds}getDebugInfo(){const e={options:{...this.options},bounds:this._bounds,grid:this._grid,statistics:this._statistics};return this.options.autoVoxelSize&&(e.autoVoxelSizeInfo={enabled:this.options.autoVoxelSize,originalSize:this._statistics?.originalVoxelSize,finalSize:this._statistics?.finalVoxelSize,adjusted:this._statistics?.autoAdjusted||!1,reason:this._statistics?.adjustmentReason,dataRange:this._bounds?S(this._bounds):null,estimatedDensity:this._bounds&&this._statistics?this._statistics.totalEntities/(S(this._bounds).x*S(this._bounds).y*S(this._bounds).z):null}),e}_hookPerformanceOverlayUpdates(){if(!this._performanceOverlay||this._postRenderListener)return;const e=this._performanceOverlay.options?.updateIntervalMs??500;this._postRenderListener=()=>{if(!this._performanceOverlay||!this._performanceOverlay.isVisible)return;const t="undefined"!=typeof performance&&performance.now?performance.now():Date.now();let i;if(null!=this._prevFrameTimestamp&&(i=Math.max(0,t-this._prevFrameTimestamp)),this._prevFrameTimestamp=t,t-this._overlayLastUpdate<e)return;this._overlayLastUpdate=t;const o=this.getStatistics()||{};null!=this._lastRenderTime&&(o.renderTimeMs=this._lastRenderTime),o.memoryUsageMB=this._estimateMemoryUsage();try{this._performanceOverlay.update(o,i)}catch(e){}};try{this.viewer.scene.postRender.addEventListener(this._postRenderListener)}catch(e){}}async fitView(e=null,t={}){try{const i=e||this._bounds;if(!i)return void u.warn("No bounds available for fitView");if(!this._isValidBounds(i))return void u.warn("Invalid bounds provided to fitView:",i);const o={...this.options.fitViewOptions,...t};u.debug("fitView called with bounds:",i,"options:",o);const n={...o};return Number.isFinite(n.pitchDegrees)||(n.pitchDegrees=-35),Number.isFinite(n.headingDegrees)||(n.headingDegrees=0),await new Promise(e=>{let t=!1;const o=async()=>{if(!t){t=!0;try{await this._fitByBoundingSphere(i,n)}catch(e){u.warn("fitView (postRender) failed, trying fallback:",e);try{await this.viewer.zoomTo(this.viewer.entities)}catch(e){u.warn("zoomTo fallback failed:",e)}}finally{try{this.viewer.scene.postRender.removeEventListener(o)}catch(e){u.debug("postRender removeEventListener failed (non-fatal):",e)}e()}}};try{this.viewer.scene.postRender.addEventListener(o)}catch(t){u.warn("postRender addEventListener failed:",t),e()}})}catch(e){throw u.error("fitView failed:",e),e}}async _fitByBoundingSphere(e,t){const o=i.Rectangle.fromDegrees(e.minLon,e.minLat,e.maxLon,e.maxLat),n=i.BoundingSphere.fromRectangle3D(o,i.Ellipsoid.WGS84,Math.max(0,e.minAlt||0)),a=i.Math.toRadians(t.headingDegrees??0),r=Math.max(-85,Math.min(-10,t.pitchDegrees??-35)),s=i.Math.toRadians(r),l=Math.max(2.2*n.radius,1e3);await this.viewer.camera.flyToBoundingSphere(n,{duration:1.2,offset:new i.HeadingPitchRange(a,s,l)})}_isValidBounds(e){return e&&"number"==typeof e.minLon&&!isNaN(e.minLon)&&"number"==typeof e.maxLon&&!isNaN(e.maxLon)&&"number"==typeof e.minLat&&!isNaN(e.minLat)&&"number"==typeof e.maxLat&&!isNaN(e.maxLat)&&"number"==typeof e.minAlt&&!isNaN(e.minAlt)&&"number"==typeof e.maxAlt&&!isNaN(e.maxAlt)&&e.minLon<=e.maxLon&&e.minLat<=e.maxLat&&e.minAlt<=e.maxAlt}async _handleMinimalDataRange(e,t,o,n){u.debug("Handling minimal data range");const a=i.Cartesian3.fromDegrees(e,t,o+2e3),r=i.Math.toRadians(n.headingDegrees||n.heading),s=i.Math.toRadians(n.pitchDegrees||n.pitch);return this.viewer.camera.flyTo({destination:a,orientation:{heading:r,pitch:s,roll:0},duration:1.5})}async _handleLargeDataRange(e,t){u.debug("Handling large data range with bounding sphere");const o=(e.minLon+e.maxLon)/2,n=(e.minLat+e.maxLat)/2,a=(e.minAlt+e.maxAlt)/2,r=S(e),s=Math.max(r.x,r.y,r.z),l=new i.BoundingSphere(i.Cartesian3.fromDegrees(o,n,a),s/2),d=i.Math.toRadians(t.headingDegrees||t.heading),c=i.Math.toRadians(t.pitchDegrees||t.pitch);return this.viewer.camera.flyToBoundingSphere(l,{duration:2.5,offset:new i.HeadingPitchRange(d,c,0)})}_calculateOptimalCameraHeight(e,t,o){if("auto"!==o.altitudeStrategy)return o.altitude||5e3;try{const n=i.Math.toRadians(o.pitchDegrees||o.pitch),a=this.viewer.camera.frustum.fovy||i.Math.toRadians(60),r=(e+t)/(2*Math.tan(a/2)),s=Math.abs(n);let l=r*Math.max(.5,Math.sin(Math.PI/2-s)+.3);const d=e/Math.min(e,100);d>5&&(l*=Math.log10(d)+1);const c=Math.max(500,.1*e),h=Math.min(1e5,10*e);return l=Math.max(c,Math.min(h,l)),u.debug(`Camera height calculated: ${l.toFixed(0)}m (range: ${e.toFixed(0)}m, pitch: ${o.pitchDegrees||o.pitch}°)`),l}catch(t){return u.warn("Camera height calculation failed, using fallback:",t),Math.max(2e3,2*e)}}async _executeCameraMovement(e,t,o,n,a,r,s){try{const l=i.Cartesian3.fromDegrees(e,t,o+n),d=i.Math.toRadians(a.headingDegrees||a.heading),c=i.Math.toRadians(a.pitchDegrees||a.pitch),h={heading:d,pitch:c,roll:0};u.debug(`Camera target: position=${e.toFixed(6)},${t.toFixed(6)},${(o+n).toFixed(0)}, heading=${a.headingDegrees||a.heading}°, pitch=${a.pitchDegrees||a.pitch}°`);const p=Math.max(1,Math.min(3,.8*Math.log10(r))),m=this.viewer.camera.flyTo({destination:l,orientation:h,duration:p,complete:()=>{u.debug("fitView camera movement completed")},cancel:()=>{u.debug("fitView camera movement cancelled")}});if(m)await m;else{u.debug("Using fallback: flyToBoundingSphere");const n=new i.BoundingSphere(i.Cartesian3.fromDegrees(e,t,o),r/2+s);await this.viewer.camera.flyToBoundingSphere(n,{duration:p,offset:new i.HeadingPitchRange(d,c,0)})}u.info("fitView completed successfully")}catch(e){throw u.error("Camera movement execution failed:",e),e}}static filterEntities(e,t){return Array.isArray(e)&&"function"==typeof t?e.filter(t):[]}}function H(e,t,o=500){if(!e)throw new Error("viewer is required");if(!(t&&"minLon"in t&&"maxLon"in t&&"minLat"in t&&"maxLat"in t))throw new Error("bounds must include minLon, maxLon, minLat, maxLat");const n=[],a=t.minAlt||0,r=t.maxAlt||100;for(let s=0;s<o;s++){const o=t.minLon+(t.maxLon-t.minLon)*Math.random(),l=t.minLat+(t.maxLat-t.minLat)*Math.random(),d=a+(r-a)*Math.random(),c=e.entities.add({id:`test-entity-${s}`,position:i.Cartesian3.fromDegrees(o,l,d),point:{pixelSize:5,color:i.Color.YELLOW,outlineColor:i.Color.BLACK,outlineWidth:1},label:{text:`Test ${s}`,font:"10pt sans-serif",pixelOffset:new i.Cartesian2(0,-30),fillColor:i.Color.WHITE,outlineColor:i.Color.BLACK,outlineWidth:1,style:i.LabelStyle.FILL_AND_OUTLINE}});n.push(c)}return n}function Y(e){if(!e||!e.entities)throw new Error("Invalid viewer");return e.entities.values}const X=B,U="0.1.19",j="hiro-nyon",Z="https://github.com/hiro-nyon/cesium-heatbox";function G(e,t){return new B(e,t)}function K(){let e=!1;try{if("undefined"!=typeof WebGLRenderingContext){const t=document.createElement("canvas");e=!(!t.getContext("webgl")&&!t.getContext("experimental-webgl"))}}catch(t){e=!1}return{version:U,cesiumVersion:"undefined"!=typeof Cesium?Cesium.VERSION:"N/A",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"N/A",webglSupport:e,timestamp:(new Date).toISOString()}}u.info(`CesiumJS Heatbox v${U} loaded`);export{j as AUTHOR,B as CesiumHeatbox,B as Heatbox,Z as REPOSITORY,U as VERSION,G as createHeatbox,X as default,H as generateTestEntities,Y as getAllEntities,K as getEnvironmentInfo};
2
2
  //# sourceMappingURL=cesium-heatbox.min.js.map