minerender 2.1.0-alpha.86 → 2.1.0-alpha.87

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.
@@ -3157,6 +3157,41 @@ declare class AnvilParser {
3157
3157
  private static unpack;
3158
3158
  }
3159
3159
 
3160
+ /** Loads chunk columns at absolute integer chunk coordinates. */
3161
+ interface WorldChunkSource {
3162
+ /** Returns the requested column, or `undefined` if absent. Honor signal to cancel discarded reads. */
3163
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3164
+ }
3165
+
3166
+ /**
3167
+ * Reads `r.<x>.<z>.mca` at integer region coordinates, or returns `undefined` when absent.
3168
+ * Forward `signal` to file or network I/O; it aborts when every caller waiting for the region cancels.
3169
+ */
3170
+ type AnvilRegionReader = (x: number, z: number, signal?: AbortSignal) => Promise<Uint8Array | ArrayBuffer | undefined>;
3171
+ /** Cache limits passed to `new AnvilWorldSource(readRegion, options)`. */
3172
+ interface AnvilWorldSourceOptions {
3173
+ /** Maximum cached regions, including missing regions. Defaults to 4; 0 disables caching. */
3174
+ maxCachedRegions?: number;
3175
+ /** Maximum retained region bytes. Defaults to 64 MiB; larger regions are read without caching. */
3176
+ maxCachedBytes?: number;
3177
+ }
3178
+ /** Reads selected Java Anvil chunk columns and caches raw regions within count and byte limits. */
3179
+ declare class AnvilWorldSource implements WorldChunkSource {
3180
+ private readonly readRegion;
3181
+ private readonly regions;
3182
+ private readonly pending;
3183
+ private readonly maxCachedRegions;
3184
+ private readonly maxCachedBytes;
3185
+ private cachedBytes;
3186
+ constructor(readRegion: AnvilRegionReader, options?: AnvilWorldSourceOptions);
3187
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
3188
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3189
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
3190
+ clearCache(): void;
3191
+ private getRegion;
3192
+ private cacheRegion;
3193
+ }
3194
+
3160
3195
  /** A placed block's data snapshot and optional render object, returned by world and chunk accessors. */
3161
3196
  interface BlockInfo<SectionMeshing extends boolean = false> {
3162
3197
  /** Detached block data; use world or chunk setters to update stored blocks. */
@@ -3316,6 +3351,73 @@ interface MineRenderWorldOptions<SectionMeshing extends boolean = boolean> {
3316
3351
  maxAtlasSize?: number;
3317
3352
  }
3318
3353
 
3354
+ interface WorldStreamerOptions {
3355
+ /** Loads a square of chunk columns around the center. Integer from 0 to 32; defaults to 2. */
3356
+ loadRadius?: number;
3357
+ /** Retains loaded columns within this radius. Defaults to loadRadius + 1, capped at 32. */
3358
+ unloadRadius?: number;
3359
+ }
3360
+ /**
3361
+ * Loads nearby chunk columns in distance order and unloads distant columns.
3362
+ * Updates coalesce to the latest center and serialize world mutations. Use a dedicated world:
3363
+ * the streamer replaces columns it loads, and callers must await disposal before editing that world.
3364
+ * The source remains caller-owned. Lighting, biome tint, and LOD are not added by streaming.
3365
+ */
3366
+ declare class WorldStreamer {
3367
+ private readonly world;
3368
+ private readonly source;
3369
+ private readonly loadRadius;
3370
+ private readonly unloadRadius;
3371
+ private readonly loaded;
3372
+ private readonly owned;
3373
+ private readonly missing;
3374
+ private readonly failed;
3375
+ private desired;
3376
+ private center?;
3377
+ private loading?;
3378
+ private running?;
3379
+ private disposal?;
3380
+ private disposed;
3381
+ constructor(world: Pick<MineRenderWorld<boolean>, "placeChunk" | "unloadChunkColumn">, source: WorldChunkSource, options?: WorldStreamerOptions);
3382
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
3383
+ get loadedChunks(): readonly {
3384
+ x: number;
3385
+ z: number;
3386
+ }[];
3387
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
3388
+ get failedChunks(): readonly {
3389
+ x: number;
3390
+ z: number;
3391
+ error: unknown;
3392
+ }[];
3393
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
3394
+ get pendingChunks(): number;
3395
+ /**
3396
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
3397
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
3398
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
3399
+ * Placement and unload failures reject the drain; call update again to retry those operations.
3400
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
3401
+ * Sources should represent an unchanged world during streaming.
3402
+ */
3403
+ update(x: number, z: number): Promise<void>;
3404
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
3405
+ updatePosition(position: {
3406
+ x: number;
3407
+ z: number;
3408
+ }): Promise<void>;
3409
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
3410
+ retryFailedChunks(): Promise<void>;
3411
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
3412
+ dispose(): Promise<void>;
3413
+ private drain;
3414
+ private needsLoad;
3415
+ private unload;
3416
+ private validateChunk;
3417
+ private within;
3418
+ private key;
3419
+ }
3420
+
3319
3421
  /**
3320
3422
  * {@link EnvProvider} for headless Node.
3321
3423
  *
@@ -3355,4 +3457,4 @@ declare class NodeCache extends PersistentCache<LocalStorage> {
3355
3457
  forEach<T>(callback: (v: T, k: string) => void): Promise<void>;
3356
3458
  }
3357
3459
 
3358
- export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, NodeCache, NodeEnv, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, registerNodeEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
3460
+ export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, type AnvilRegionReader, AnvilWorldSource, type AnvilWorldSourceOptions, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, NodeCache, NodeEnv, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, type WorldChunkSource, WorldStreamer, type WorldStreamerOptions, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, registerNodeEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
@@ -3157,6 +3157,41 @@ declare class AnvilParser {
3157
3157
  private static unpack;
3158
3158
  }
3159
3159
 
3160
+ /** Loads chunk columns at absolute integer chunk coordinates. */
3161
+ interface WorldChunkSource {
3162
+ /** Returns the requested column, or `undefined` if absent. Honor signal to cancel discarded reads. */
3163
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3164
+ }
3165
+
3166
+ /**
3167
+ * Reads `r.<x>.<z>.mca` at integer region coordinates, or returns `undefined` when absent.
3168
+ * Forward `signal` to file or network I/O; it aborts when every caller waiting for the region cancels.
3169
+ */
3170
+ type AnvilRegionReader = (x: number, z: number, signal?: AbortSignal) => Promise<Uint8Array | ArrayBuffer | undefined>;
3171
+ /** Cache limits passed to `new AnvilWorldSource(readRegion, options)`. */
3172
+ interface AnvilWorldSourceOptions {
3173
+ /** Maximum cached regions, including missing regions. Defaults to 4; 0 disables caching. */
3174
+ maxCachedRegions?: number;
3175
+ /** Maximum retained region bytes. Defaults to 64 MiB; larger regions are read without caching. */
3176
+ maxCachedBytes?: number;
3177
+ }
3178
+ /** Reads selected Java Anvil chunk columns and caches raw regions within count and byte limits. */
3179
+ declare class AnvilWorldSource implements WorldChunkSource {
3180
+ private readonly readRegion;
3181
+ private readonly regions;
3182
+ private readonly pending;
3183
+ private readonly maxCachedRegions;
3184
+ private readonly maxCachedBytes;
3185
+ private cachedBytes;
3186
+ constructor(readRegion: AnvilRegionReader, options?: AnvilWorldSourceOptions);
3187
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
3188
+ getChunk(x: number, z: number, signal?: AbortSignal): Promise<AnvilChunk | undefined>;
3189
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
3190
+ clearCache(): void;
3191
+ private getRegion;
3192
+ private cacheRegion;
3193
+ }
3194
+
3160
3195
  /** A placed block's data snapshot and optional render object, returned by world and chunk accessors. */
3161
3196
  interface BlockInfo<SectionMeshing extends boolean = false> {
3162
3197
  /** Detached block data; use world or chunk setters to update stored blocks. */
@@ -3316,6 +3351,73 @@ interface MineRenderWorldOptions<SectionMeshing extends boolean = boolean> {
3316
3351
  maxAtlasSize?: number;
3317
3352
  }
3318
3353
 
3354
+ interface WorldStreamerOptions {
3355
+ /** Loads a square of chunk columns around the center. Integer from 0 to 32; defaults to 2. */
3356
+ loadRadius?: number;
3357
+ /** Retains loaded columns within this radius. Defaults to loadRadius + 1, capped at 32. */
3358
+ unloadRadius?: number;
3359
+ }
3360
+ /**
3361
+ * Loads nearby chunk columns in distance order and unloads distant columns.
3362
+ * Updates coalesce to the latest center and serialize world mutations. Use a dedicated world:
3363
+ * the streamer replaces columns it loads, and callers must await disposal before editing that world.
3364
+ * The source remains caller-owned. Lighting, biome tint, and LOD are not added by streaming.
3365
+ */
3366
+ declare class WorldStreamer {
3367
+ private readonly world;
3368
+ private readonly source;
3369
+ private readonly loadRadius;
3370
+ private readonly unloadRadius;
3371
+ private readonly loaded;
3372
+ private readonly owned;
3373
+ private readonly missing;
3374
+ private readonly failed;
3375
+ private desired;
3376
+ private center?;
3377
+ private loading?;
3378
+ private running?;
3379
+ private disposal?;
3380
+ private disposed;
3381
+ constructor(world: Pick<MineRenderWorld<boolean>, "placeChunk" | "unloadChunkColumn">, source: WorldChunkSource, options?: WorldStreamerOptions);
3382
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
3383
+ get loadedChunks(): readonly {
3384
+ x: number;
3385
+ z: number;
3386
+ }[];
3387
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
3388
+ get failedChunks(): readonly {
3389
+ x: number;
3390
+ z: number;
3391
+ error: unknown;
3392
+ }[];
3393
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
3394
+ get pendingChunks(): number;
3395
+ /**
3396
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
3397
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
3398
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
3399
+ * Placement and unload failures reject the drain; call update again to retry those operations.
3400
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
3401
+ * Sources should represent an unchanged world during streaming.
3402
+ */
3403
+ update(x: number, z: number): Promise<void>;
3404
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
3405
+ updatePosition(position: {
3406
+ x: number;
3407
+ z: number;
3408
+ }): Promise<void>;
3409
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
3410
+ retryFailedChunks(): Promise<void>;
3411
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
3412
+ dispose(): Promise<void>;
3413
+ private drain;
3414
+ private needsLoad;
3415
+ private unload;
3416
+ private validateChunk;
3417
+ private within;
3418
+ private key;
3419
+ }
3420
+
3319
3421
  /**
3320
3422
  * {@link EnvProvider} for headless Node.
3321
3423
  *
@@ -3355,4 +3457,4 @@ declare class NodeCache extends PersistentCache<LocalStorage> {
3355
3457
  forEach<T>(callback: (v: T, k: string) => void): Promise<void>;
3356
3458
  }
3357
3459
 
3358
- export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, NodeCache, NodeEnv, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, registerNodeEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
3460
+ export { AXES, type AnimationFrame, type AnimationMeta, type AnimatorFunction, type AnvilChunk, AnvilParser, type AnvilRegion, type AnvilRegionReader, AnvilWorldSource, type AnvilWorldSourceOptions, ArchiveAssetSource, type ArchiveAssetSourceOptions, type ArchiveEntry, type ArchiveProxy, AssetKey, AssetLoadError, AssetLoader, AssetParser, AssetSource, type AssetType, Assets, Axis, BUILTIN_ENTITY, BUILTIN_GENERATED, type BannerPattern, type BannerPatternDraw, BannerPatterns, BasicAssetKey, type BasicMinecraftAsset, BatchedExecutor, type BedrockBone, type BedrockCube, type BedrockEntityDescription, type BedrockEntityFile, type BedrockGeometry, type BedrockGeometryFile, type BitmapFont, type BitmapGlyph, type Block, BlockEntities, type BlockEntityEntry, type BlockEntityIndex, type BlockEntityPart, type BlockEntityRotation, type BlockFluidState, type BlockInfo, type BlockModel, type BlockModelTextures, BlockObject, type BlockObjectOptions, type BlockState, type BlockStateMultipart, type BlockStateProperties, type BlockStateProperty, type BlockStatePropertyDefaults, type BlockStatePropertyValue, BlockStateResolver, type BlockStateVariant, type BlockStateVariants, BlockStates, BlockTints, type BoxGeometryKey, BrowserArchiveProxy, CUBE_FACES, CUBE_FACE_OFFSETS, type CacheKey, Caching, type CameraOptions, CanvasImage, type CapeLayout, Chunk, ChunkData, Colormaps, type CompatCanvas, type CompatImage, type ComposerOptions, type ControlsOptions, CubeFace, CubeFaceIndex, DEFAULT_ELEMENTS, DEFAULT_NAMESPACE, DEFAULT_ROOT, DEFAULT_UV, DISPLAY_POSITIONS, DYE_COLORS, type DebugOptions, type DeepPartial, DefaultBlockStates, DisplayPosition, DisplayTransforms, type Disposable, type DoubleArray, type DyeColor, ENTITY_ANIMATION_CHANNELS, type ElementFace, type ElementRotation, Entities, type EntityAnimation, type EntityAnimationBone, type EntityAnimationChannel, type EntityAnimationFile, type EntityAnimationKeyframe, type EntityAnimationOptions, EntityAnimationPlayer, type EntityAnimationPose, type EntityLayer, type EntityModel, type EntityModelCube, type EntityModelFile, type EntityModelLayer, type EntityModelOptions, type EntityModelPart, type EntityModelPass, EntityObject, type EntityObjectOptions, type EntityRenderMode, type EntityTransformOp, Env, type EnvProvider, type ExtractableImageData, type FluidKind, FluidModelObject, type FluidSample, type FluidSampler, Fonts, type FrameCallback, type FromTo, GUI_CONTAINER_LAYOUTS, Geometries, type GuiBookButtonState, type GuiBookOptions, type GuiBossBarColor, type GuiBossBarOptions, type GuiContainerType, GuiHelper, type GuiItemLayer, type GuiLayer, GuiLight, GuiObject, type GuiObjectOptions, type GuiRecipe, type GuiRecipeIngredient, type GuiRecipeOptions, type GuiSpriteScaling, type GuiText, type GuiTextLayer, type GuiTextLayout, type GuiTextOptions, type GuiTextRun, type GuiTextStyle, type GuiTextureLayer, type GuiTooltipOptions, HostedAssetSource, type IModelTextures, ITEM_GENERATED, type ImageInfo, ImageLoader, type ImageSizeInfo, InstanceManager, InstanceReference, type Instanceable, type ItemModel, type ItemModelContext, type ItemModelTextures, type ItemTintColor, type ItemTintSource, ItemTints, type ListAsset, type LoadedSceneDocument, type LoadedSceneObject, MapControls, type MaterialKey, Materials, type Maybe, type MeshKey, Meshes, MineRenderError, MineRenderScene, type MineRenderSceneOptions, MineRenderWorld, type MineRenderWorldOptions, type MinecraftAsset, MinecraftCubeTexture, MinecraftFaceUV, type MinecraftTextureMeta, type Model, ModelCulling, type ModelDisplay, type ModelElement, type ModelFaces, ModelGenerator, ModelMerger, ModelObject, type ModelObjectOptions, ModelTextures, Models, type MultiBlockBlock, type MultiBlockEntity, type MultiBlockStructure, type MultipartCondition, type NBTAsset, NBTHelper, NodeCache, NodeEnv, OrbitControls, type PackFormat, PackFormats, PackMetadata, PersistentCache, type PositionedGuiGlyph, type QuadArray, type RawImageKey, type RenderOptions, Renderer, type RendererFrame, type RendererOptions, type RequestConfig, RequestError, type RequestResponse, Requests, type ResolvedBlockEntity, type ResponseParser, SKIN_PARTS, type SceneBlockDefinition, type SceneDocument, SceneDocumentLoader, type SceneEntityDefinition, SceneExporter, type SceneGLTFExportOptions, type SceneGuiDefinition, type SceneGuiLayer, SceneInspector, type SceneModelDefinition, SceneObject, type SceneObjectDefinition, type SceneObjectDefinitionBase, type SceneObjectOptions, type SceneSkinDefinition, type SceneSkinPosePart, SceneStats, SceneStatsDisplay, SchematicParser, type SchematicParserOptions, SectionMesh, type SectionMeshEntry, type SectionMeshTemplate, SectionModels, type Serializable, type SkinGeometries, SkinImage, SkinObject, type SkinObjectOptions, SkinPart, type SkinTexture, type SkinTextureCoordinates, SkinTextures, Skins, type SpecialItemPart, type SpecialItemRenderer, SpecialItems, type StructureNBT, StructureParser, type TextureAsset, TextureAtlas, type TextureKey, TextureLoader, Textures, Ticker, type TickerFunction, TintColors, type Transformable, type TripleArray, UVMapper, type VideoExportOptions, VideoExporter, type WorldChunkSource, WorldStreamer, type WorldStreamerOptions, WrappedImage, addBox3WireframeToObject, addWireframeToMesh, addWireframeToObject, applyElementRotation, applyGenericRotation, axisToVec3, base64decode, base64encode, capeTextureSizes, captureException, changeEvent, clampRotationDegrees, classicSkinGeometries, classicSkinTextureCoordinates, computeMorphedAttributes, createCanvas, createFluidGeometry, createGuiTextGeometry, createGuiTextureGeometry, createImage, entityAnimationTime, estimateBytesUsed, getBlockFluidState, getFluidKind, interleaveAttributes, isAssetKey, isBasicAssetKey, isBlockObject, isDisposable, isDoubleArray, isEntityObject, isGuiObject, isInstanceManager, isInstanceReference, isInstanceable, isInstancedMesh, isMesh, isMineRenderScene, isModelObject, isObject3D, isOrthographicCamera, isPerspectiveCamera, isQuadArray, isSceneObject, isTransformable, isTripleArray, isVector3, layoutGuiText, md5, mergeBufferAttributes, mergeBufferGeometries, mergeVertices, parseSceneDocument, prefix, registerNodeEnv, sampleEntityAnimation, sampleEntityKeyframes, sampleFluid, serializeBoxGeometryKey, serializeImageKey, serializeMaterialKey, serializeMeshKey, serializeTextureKey, sha1, sha256, sha512, shutdown, sleep, slimSkinGeometries, slimSkinTextureCoordinates, timingEnd, timingStart, toDegrees, toRadians, toTrianglesDrawMode, trimCanvas };
@@ -18780,6 +18780,7 @@ var index_node_exports = {};
18780
18780
  __export(index_node_exports, {
18781
18781
  AXES: () => AXES,
18782
18782
  AnvilParser: () => AnvilParser,
18783
+ AnvilWorldSource: () => AnvilWorldSource,
18783
18784
  ArchiveAssetSource: () => ArchiveAssetSource,
18784
18785
  AssetKey: () => AssetKey,
18785
18786
  AssetLoadError: () => AssetLoadError,
@@ -18883,6 +18884,7 @@ __export(index_node_exports, {
18883
18884
  TintColors: () => TintColors,
18884
18885
  UVMapper: () => UVMapper,
18885
18886
  VideoExporter: () => VideoExporter,
18887
+ WorldStreamer: () => WorldStreamer,
18886
18888
  WrappedImage: () => WrappedImage,
18887
18889
  addBox3WireframeToObject: () => addBox3WireframeToObject,
18888
18890
  addWireframeToMesh: () => addWireframeToMesh,
@@ -28952,6 +28954,134 @@ var AnvilParser = class {
28952
28954
  }
28953
28955
  };
28954
28956
 
28957
+ // src/world/AnvilWorldSource.ts
28958
+ init_MineRenderError();
28959
+ async function abortable2(promise, signal) {
28960
+ if (!signal) return promise;
28961
+ let abort;
28962
+ const cancelled = new Promise((_, reject) => {
28963
+ abort = () => reject(signal.reason);
28964
+ signal.addEventListener("abort", abort, { once: true });
28965
+ if (signal.aborted) abort();
28966
+ });
28967
+ try {
28968
+ return await Promise.race([promise, cancelled]);
28969
+ } finally {
28970
+ signal.removeEventListener("abort", abort);
28971
+ }
28972
+ }
28973
+ var AnvilWorldSource = class {
28974
+ constructor(readRegion, options = {}) {
28975
+ this.readRegion = readRegion;
28976
+ this.regions = /* @__PURE__ */ new Map();
28977
+ this.pending = /* @__PURE__ */ new Map();
28978
+ this.cachedBytes = 0;
28979
+ this.maxCachedRegions = options.maxCachedRegions ?? 4;
28980
+ this.maxCachedBytes = options.maxCachedBytes ?? 64 * 1024 * 1024;
28981
+ for (const [name, value] of Object.entries({ maxCachedRegions: this.maxCachedRegions, maxCachedBytes: this.maxCachedBytes })) {
28982
+ if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a nonnegative safe integer`);
28983
+ }
28984
+ }
28985
+ /** Decodes one column at absolute chunk coordinates. Aborting a caller leaves other shared readers active. */
28986
+ async getChunk(x, z, signal) {
28987
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(z)) {
28988
+ throw new RangeError("Chunk column coordinates must be safe integers");
28989
+ }
28990
+ const regionX = Math.floor(x / 32), regionZ = Math.floor(z / 32);
28991
+ const data = await this.getRegion(regionX, regionZ, signal);
28992
+ signal?.throwIfAborted();
28993
+ if (!data) return void 0;
28994
+ const chunk = await abortable2(AnvilParser.parseChunk(data, x - regionX * 32, z - regionZ * 32), signal);
28995
+ signal?.throwIfAborted();
28996
+ if (chunk && (chunk.x !== x || chunk.z !== z)) {
28997
+ throw new MineRenderError(`Anvil chunk coordinates ${chunk.x},${chunk.z} do not match requested column ${x},${z}`);
28998
+ }
28999
+ return chunk;
29000
+ }
29001
+ /** Releases cached regions. Reads already in progress finish without repopulating this cache. */
29002
+ clearCache() {
29003
+ this.regions.clear();
29004
+ this.pending.clear();
29005
+ this.cachedBytes = 0;
29006
+ }
29007
+ getRegion(x, z, signal) {
29008
+ signal?.throwIfAborted();
29009
+ const key = `${x},${z}`;
29010
+ const cached2 = this.regions.get(key);
29011
+ if (cached2) {
29012
+ this.regions.delete(key);
29013
+ this.regions.set(key, cached2);
29014
+ return Promise.resolve(cached2.data);
29015
+ }
29016
+ let loading = this.pending.get(key);
29017
+ if (!loading) {
29018
+ const controller = new AbortController();
29019
+ loading = {
29020
+ controller,
29021
+ waiters: 0,
29022
+ settled: false,
29023
+ promise: Promise.resolve().then(() => {
29024
+ controller.signal.throwIfAborted();
29025
+ return this.readRegion(x, z, controller.signal);
29026
+ }).then((data) => {
29027
+ controller.signal.throwIfAborted();
29028
+ let bytes = data instanceof Uint8Array ? data : data === void 0 ? void 0 : new Uint8Array(data);
29029
+ if (bytes && bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
29030
+ if (bytes) AnvilParser.getChunkList(bytes);
29031
+ loading.settled = true;
29032
+ if (this.pending.get(key) === loading) this.cacheRegion(key, bytes);
29033
+ return bytes;
29034
+ }).finally(() => {
29035
+ loading.settled = true;
29036
+ if (this.pending.get(key) === loading) this.pending.delete(key);
29037
+ })
29038
+ };
29039
+ this.pending.set(key, loading);
29040
+ }
29041
+ const read = loading;
29042
+ read.waiters++;
29043
+ return new Promise((resolve, reject) => {
29044
+ let finished = false;
29045
+ const release = () => {
29046
+ if (finished) return false;
29047
+ finished = true;
29048
+ signal?.removeEventListener("abort", abort);
29049
+ read.waiters--;
29050
+ return true;
29051
+ };
29052
+ const abort = () => {
29053
+ if (!release()) return;
29054
+ if (!read.waiters && !read.settled) {
29055
+ if (this.pending.get(key) === read) this.pending.delete(key);
29056
+ read.controller.abort(signal.reason);
29057
+ }
29058
+ reject(signal.reason);
29059
+ };
29060
+ signal?.addEventListener("abort", abort, { once: true });
29061
+ read.promise.then(
29062
+ (data) => {
29063
+ if (release()) resolve(data);
29064
+ },
29065
+ (error) => {
29066
+ if (release()) reject(error);
29067
+ }
29068
+ );
29069
+ if (signal?.aborted) abort();
29070
+ });
29071
+ }
29072
+ cacheRegion(key, data) {
29073
+ const size = data?.byteLength ?? 0;
29074
+ if (!this.maxCachedRegions || size > this.maxCachedBytes) return;
29075
+ this.regions.set(key, { data, size });
29076
+ this.cachedBytes += size;
29077
+ while (this.regions.size > this.maxCachedRegions || this.cachedBytes > this.maxCachedBytes) {
29078
+ const oldest = this.regions.keys().next().value;
29079
+ this.cachedBytes -= this.regions.get(oldest).size;
29080
+ this.regions.delete(oldest);
29081
+ }
29082
+ }
29083
+ };
29084
+
28955
29085
  // src/world/Chunk.ts
28956
29086
  var import_three42 = require("three");
28957
29087
  init_BlockStates();
@@ -29626,10 +29756,185 @@ var Chunk = class _Chunk {
29626
29756
  );
29627
29757
  }
29628
29758
  };
29759
+
29760
+ // src/world/WorldStreamer.ts
29761
+ var WorldStreamer = class {
29762
+ constructor(world, source, options = {}) {
29763
+ this.world = world;
29764
+ this.source = source;
29765
+ this.loaded = /* @__PURE__ */ new Map();
29766
+ this.owned = /* @__PURE__ */ new Map();
29767
+ this.missing = /* @__PURE__ */ new Map();
29768
+ this.failed = /* @__PURE__ */ new Map();
29769
+ this.desired = [];
29770
+ this.disposed = false;
29771
+ this.loadRadius = options.loadRadius ?? 2;
29772
+ this.unloadRadius = options.unloadRadius ?? Math.min(32, this.loadRadius + 1);
29773
+ if (![this.loadRadius, this.unloadRadius].every((value) => Number.isInteger(value) && value >= 0 && value <= 32) || this.unloadRadius < this.loadRadius) {
29774
+ throw new RangeError("Chunk radii must be integers from 0 to 32, with unloadRadius at least loadRadius");
29775
+ }
29776
+ }
29777
+ /** Returns absolute coordinates of successfully placed columns, including retained columns. */
29778
+ get loadedChunks() {
29779
+ return [...this.loaded.values()].map((position) => ({ ...position }));
29780
+ }
29781
+ /** Returns source failures retained within the unload radius. Failed columns do not block other loads. */
29782
+ get failedChunks() {
29783
+ return [...this.failed.values()].map((failure) => ({ ...failure }));
29784
+ }
29785
+ /** Counts desired columns still waiting for a source read or placement, including the active column. */
29786
+ get pendingChunks() {
29787
+ return this.desired.filter((position) => this.needsLoad(position)).length;
29788
+ }
29789
+ /**
29790
+ * Updates the center in absolute chunk coordinates. Repeated calls share the active drain.
29791
+ * Source failures are recorded in failedChunks; other columns continue loading. Missing and failed
29792
+ * columns are remembered within the retention radius. Call retryFailedChunks to retry source failures.
29793
+ * Placement and unload failures reject the drain; call update again to retry those operations.
29794
+ * Reads outside the latest load radius receive an abort signal; placement finishes before unloading.
29795
+ * Sources should represent an unchanged world during streaming.
29796
+ */
29797
+ async update(x, z) {
29798
+ if (this.disposed) throw new Error("WorldStreamer is disposed");
29799
+ if (![x, z].every((value) => Number.isSafeInteger(value) && Number.isSafeInteger(value - this.unloadRadius) && Number.isSafeInteger(value + this.unloadRadius))) {
29800
+ throw new RangeError("Chunk coordinates must be safe integers within the streaming radius");
29801
+ }
29802
+ if (!this.center || this.center.x !== x || this.center.z !== z) {
29803
+ this.center = { x, z };
29804
+ this.desired = [];
29805
+ for (let dz = -this.loadRadius; dz <= this.loadRadius; dz++) {
29806
+ for (let dx = -this.loadRadius; dx <= this.loadRadius; dx++) {
29807
+ this.desired.push({ x: x + dx, z: z + dz });
29808
+ }
29809
+ }
29810
+ this.desired.sort((a, b) => (a.x - x) ** 2 + (a.z - z) ** 2 - (b.x - x) ** 2 - (b.z - z) ** 2);
29811
+ if (this.loading && !this.within(this.loading.position, this.loadRadius)) {
29812
+ this.loading.controller.abort();
29813
+ }
29814
+ }
29815
+ return this.running ??= Promise.resolve().then(() => this.drain());
29816
+ }
29817
+ /** Updates from a camera or view-center position in scene units. One chunk spans 256 scene units. */
29818
+ async updatePosition(position) {
29819
+ if (![position.x, position.z].every(Number.isFinite)) throw new RangeError("Scene coordinates must be finite");
29820
+ return this.update(Math.floor(position.x / 256), Math.floor(position.z / 256));
29821
+ }
29822
+ /** Forgets recorded source failures and retries desired columns at the latest center. */
29823
+ async retryFailedChunks() {
29824
+ if (this.disposed) throw new Error("WorldStreamer is disposed");
29825
+ this.failed.clear();
29826
+ if (this.center) await this.update(this.center.x, this.center.z);
29827
+ }
29828
+ /** Aborts source reads, waits for active work, then unloads owned columns. The world and source remain caller-owned. */
29829
+ dispose() {
29830
+ this.disposed = true;
29831
+ this.desired = [];
29832
+ this.center = void 0;
29833
+ this.loading?.controller.abort();
29834
+ return this.disposal ??= Promise.resolve().then(async () => {
29835
+ await this.running?.catch(() => void 0);
29836
+ let failure;
29837
+ let failed = false;
29838
+ for (const position of this.owned.values()) {
29839
+ try {
29840
+ await this.unload(position);
29841
+ } catch (error) {
29842
+ failed = true;
29843
+ failure ??= error;
29844
+ }
29845
+ }
29846
+ this.missing.clear();
29847
+ this.failed.clear();
29848
+ if (failed) throw failure;
29849
+ }).catch((error) => {
29850
+ this.disposal = void 0;
29851
+ throw error;
29852
+ });
29853
+ }
29854
+ async drain() {
29855
+ try {
29856
+ while (!this.disposed) {
29857
+ for (const [key, position2] of this.missing) {
29858
+ if (!this.within(position2, this.unloadRadius)) this.missing.delete(key);
29859
+ }
29860
+ for (const [key, position2] of this.failed) {
29861
+ if (!this.within(position2, this.unloadRadius)) this.failed.delete(key);
29862
+ }
29863
+ const obsolete = [...this.owned.values()].find((position2) => !this.loaded.has(this.key(position2)) || !this.within(position2, this.unloadRadius));
29864
+ if (obsolete) {
29865
+ await this.unload(obsolete);
29866
+ continue;
29867
+ }
29868
+ const position = this.desired.find((position2) => this.needsLoad(position2));
29869
+ if (!position) return;
29870
+ let chunk;
29871
+ const controller = new AbortController();
29872
+ this.loading = { position, controller };
29873
+ try {
29874
+ chunk = await this.source.getChunk(position.x, position.z, controller.signal);
29875
+ if (chunk) this.validateChunk(chunk, position);
29876
+ } catch (error) {
29877
+ if (!controller.signal.aborted && !this.disposed && this.within(position, this.loadRadius)) {
29878
+ this.failed.set(this.key(position), { ...position, error });
29879
+ }
29880
+ continue;
29881
+ } finally {
29882
+ this.loading = void 0;
29883
+ }
29884
+ if (controller.signal.aborted || this.disposed || !this.within(position, this.loadRadius)) continue;
29885
+ if (!chunk) {
29886
+ this.missing.set(this.key(position), position);
29887
+ continue;
29888
+ }
29889
+ this.owned.set(this.key(position), position);
29890
+ try {
29891
+ await this.world.placeChunk(chunk);
29892
+ this.loaded.set(this.key(position), position);
29893
+ } catch (error) {
29894
+ try {
29895
+ await this.unload(position);
29896
+ } catch (cleanupError) {
29897
+ const failure = error instanceof Error ? error : new Error(String(error));
29898
+ try {
29899
+ Object.defineProperty(failure, "cause", { value: cleanupError, configurable: true });
29900
+ } catch {
29901
+ throw Object.assign(new Error(failure.message), { cause: cleanupError });
29902
+ }
29903
+ throw failure;
29904
+ }
29905
+ throw error;
29906
+ }
29907
+ }
29908
+ } finally {
29909
+ this.running = void 0;
29910
+ }
29911
+ }
29912
+ needsLoad(position) {
29913
+ const key = this.key(position);
29914
+ return !this.loaded.has(key) && !this.missing.has(key) && !this.failed.has(key);
29915
+ }
29916
+ async unload(position) {
29917
+ await this.world.unloadChunkColumn(position.x, position.z);
29918
+ this.owned.delete(this.key(position));
29919
+ this.loaded.delete(this.key(position));
29920
+ }
29921
+ validateChunk(chunk, position) {
29922
+ if (chunk.x !== position.x || chunk.z !== position.z) {
29923
+ throw new Error(`World source returned chunk ${chunk.x},${chunk.z} for ${position.x},${position.z}`);
29924
+ }
29925
+ }
29926
+ within(position, radius) {
29927
+ return !!this.center && Math.abs(position.x - this.center.x) <= radius && Math.abs(position.z - this.center.z) <= radius;
29928
+ }
29929
+ key(position) {
29930
+ return `${position.x},${position.z}`;
29931
+ }
29932
+ };
29629
29933
  // Annotate the CommonJS export names for ESM import in node:
29630
29934
  0 && (module.exports = {
29631
29935
  AXES,
29632
29936
  AnvilParser,
29937
+ AnvilWorldSource,
29633
29938
  ArchiveAssetSource,
29634
29939
  AssetKey,
29635
29940
  AssetLoadError,
@@ -29733,6 +30038,7 @@ var Chunk = class _Chunk {
29733
30038
  TintColors,
29734
30039
  UVMapper,
29735
30040
  VideoExporter,
30041
+ WorldStreamer,
29736
30042
  WrappedImage,
29737
30043
  addBox3WireframeToObject,
29738
30044
  addWireframeToMesh,