minerender 2.1.0-alpha.0 → 2.1.0-alpha.10

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.
Files changed (94) hide show
  1. package/README.md +1 -1
  2. package/dist/browser/index.d.mts +187 -137
  3. package/dist/browser/index.d.ts +187 -137
  4. package/dist/browser/index.js +1378 -1130
  5. package/dist/browser/index.js.map +1 -1
  6. package/dist/browser/index.mjs +1392 -1144
  7. package/dist/browser/index.mjs.map +1 -1
  8. package/dist/bundle.js +7531 -8873
  9. package/dist/bundle.js.map +1 -1
  10. package/dist/node/index.d.mts +186 -136
  11. package/dist/node/index.d.ts +186 -136
  12. package/dist/node/index.js +1598 -1280
  13. package/dist/node/index.js.map +1 -1
  14. package/dist/node/index.mjs +1550 -1233
  15. package/dist/node/index.mjs.map +1 -1
  16. package/package.json +11 -13
  17. package/.worktrees/jobqu-review/LICENSE +0 -21
  18. package/.worktrees/jobqu-review/README.md +0 -176
  19. package/.worktrees/v2-asset-sources/LICENSE +0 -21
  20. package/.worktrees/v2-asset-sources/README.md +0 -30
  21. package/.worktrees/v2-asset-sources/examples/script-tag/README.md +0 -13
  22. package/.worktrees/v2-asset-sources/examples/vite/README.md +0 -13
  23. package/.worktrees/v2-asset-sources/packages/minerender/LICENSE +0 -21
  24. package/.worktrees/v2-asset-sources/packages/minerender/README.md +0 -24
  25. package/.worktrees/v2-brightness/LICENSE +0 -21
  26. package/.worktrees/v2-brightness/README.md +0 -30
  27. package/.worktrees/v2-brightness/examples/script-tag/README.md +0 -13
  28. package/.worktrees/v2-brightness/examples/vite/README.md +0 -13
  29. package/.worktrees/v2-brightness/packages/minerender/LICENSE +0 -21
  30. package/.worktrees/v2-brightness/packages/minerender/README.md +0 -24
  31. package/.worktrees/v2-cache-recovery/LICENSE +0 -21
  32. package/.worktrees/v2-cache-recovery/README.md +0 -30
  33. package/.worktrees/v2-cache-recovery/examples/script-tag/README.md +0 -13
  34. package/.worktrees/v2-cache-recovery/examples/vite/README.md +0 -13
  35. package/.worktrees/v2-cache-recovery/packages/minerender/LICENSE +0 -21
  36. package/.worktrees/v2-cache-recovery/packages/minerender/README.md +0 -24
  37. package/.worktrees/v2-ci-stack/LICENSE +0 -21
  38. package/.worktrees/v2-ci-stack/README.md +0 -109
  39. package/.worktrees/v2-ci-stack/examples/script-tag/README.md +0 -15
  40. package/.worktrees/v2-ci-stack/examples/vite/README.md +0 -15
  41. package/.worktrees/v2-ci-stack/packages/minerender/LICENSE +0 -21
  42. package/.worktrees/v2-ci-stack/packages/minerender/README.md +0 -11
  43. package/.worktrees/v2-ci-typescript/LICENSE +0 -21
  44. package/.worktrees/v2-ci-typescript/README.md +0 -11
  45. package/.worktrees/v2-controls/LICENSE +0 -21
  46. package/.worktrees/v2-controls/README.md +0 -30
  47. package/.worktrees/v2-controls/examples/script-tag/README.md +0 -13
  48. package/.worktrees/v2-controls/examples/vite/README.md +0 -13
  49. package/.worktrees/v2-controls/packages/minerender/LICENSE +0 -21
  50. package/.worktrees/v2-controls/packages/minerender/README.md +0 -24
  51. package/.worktrees/v2-dependencies/LICENSE +0 -21
  52. package/.worktrees/v2-dependencies/README.md +0 -30
  53. package/.worktrees/v2-dependencies/examples/script-tag/README.md +0 -13
  54. package/.worktrees/v2-dependencies/examples/vite/README.md +0 -13
  55. package/.worktrees/v2-dependencies/packages/minerender/LICENSE +0 -21
  56. package/.worktrees/v2-dependencies/packages/minerender/README.md +0 -24
  57. package/.worktrees/v2-frame-limit/LICENSE +0 -21
  58. package/.worktrees/v2-frame-limit/README.md +0 -30
  59. package/.worktrees/v2-frame-limit/examples/script-tag/README.md +0 -13
  60. package/.worktrees/v2-frame-limit/examples/vite/README.md +0 -13
  61. package/.worktrees/v2-frame-limit/packages/minerender/LICENSE +0 -21
  62. package/.worktrees/v2-frame-limit/packages/minerender/README.md +0 -24
  63. package/.worktrees/v2-images/LICENSE +0 -21
  64. package/.worktrees/v2-images/README.md +0 -30
  65. package/.worktrees/v2-images/examples/script-tag/README.md +0 -13
  66. package/.worktrees/v2-images/examples/vite/README.md +0 -13
  67. package/.worktrees/v2-images/packages/minerender/LICENSE +0 -21
  68. package/.worktrees/v2-images/packages/minerender/README.md +0 -24
  69. package/.worktrees/v2-lifecycle/LICENSE +0 -21
  70. package/.worktrees/v2-lifecycle/README.md +0 -30
  71. package/.worktrees/v2-lifecycle/examples/script-tag/README.md +0 -13
  72. package/.worktrees/v2-lifecycle/examples/vite/README.md +0 -13
  73. package/.worktrees/v2-lifecycle/packages/minerender/LICENSE +0 -21
  74. package/.worktrees/v2-lifecycle/packages/minerender/README.md +0 -24
  75. package/.worktrees/v2-main-conflicts/LICENSE +0 -21
  76. package/.worktrees/v2-main-conflicts/README.md +0 -11
  77. package/.worktrees/v2-monorepo/LICENSE +0 -21
  78. package/.worktrees/v2-monorepo/README.md +0 -30
  79. package/.worktrees/v2-monorepo/examples/script-tag/README.md +0 -13
  80. package/.worktrees/v2-monorepo/examples/vite/README.md +0 -13
  81. package/.worktrees/v2-monorepo/packages/minerender/LICENSE +0 -21
  82. package/.worktrees/v2-monorepo/packages/minerender/README.md +0 -24
  83. package/.worktrees/v2-requests/LICENSE +0 -21
  84. package/.worktrees/v2-requests/README.md +0 -30
  85. package/.worktrees/v2-requests/examples/script-tag/README.md +0 -13
  86. package/.worktrees/v2-requests/examples/vite/README.md +0 -13
  87. package/.worktrees/v2-requests/packages/minerender/LICENSE +0 -21
  88. package/.worktrees/v2-requests/packages/minerender/README.md +0 -26
  89. package/.worktrees/v2-source-errors/LICENSE +0 -21
  90. package/.worktrees/v2-source-errors/README.md +0 -30
  91. package/.worktrees/v2-source-errors/examples/script-tag/README.md +0 -13
  92. package/.worktrees/v2-source-errors/examples/vite/README.md +0 -13
  93. package/.worktrees/v2-source-errors/packages/minerender/LICENSE +0 -21
  94. package/.worktrees/v2-source-errors/packages/minerender/README.md +0 -26
@@ -23,18 +23,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
24
  mod
25
25
  ));
26
- var __decorateClass = (decorators, target, key, kind) => {
27
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
28
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
29
- if (decorator = decorators[i])
30
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
31
- if (kind && result) __defProp(target, key, result);
32
- return result;
33
- };
34
26
 
35
- // node_modules/ts-deepmerge/dist/index.js
27
+ // ../../node_modules/ts-deepmerge/dist/index.js
36
28
  var require_dist = __commonJS({
37
- "node_modules/ts-deepmerge/dist/index.js"(exports) {
29
+ "../../node_modules/ts-deepmerge/dist/index.js"(exports) {
38
30
  "use strict";
39
31
  var __assign = exports && exports.__assign || function() {
40
32
  __assign = Object.assign || function(t) {
@@ -85,7 +77,7 @@ var require_dist = __commonJS({
85
77
  return false;
86
78
  };
87
79
  var PROTECTED_KEYS = ["__proto__"];
88
- var merge11 = function() {
80
+ var merge10 = function() {
89
81
  var objects = [];
90
82
  for (var _i = 0; _i < arguments.length; _i++) {
91
83
  objects[_i] = arguments[_i];
@@ -96,9 +88,9 @@ var require_dist = __commonJS({
96
88
  return;
97
89
  }
98
90
  if (Array.isArray(result[key]) && Array.isArray(current[key])) {
99
- result[key] = merge11.options.mergeArrays ? Array.from(new Set(result[key].concat(current[key]))) : current[key];
91
+ result[key] = merge10.options.mergeArrays ? Array.from(new Set(result[key].concat(current[key]))) : current[key];
100
92
  } else if (isObject(result[key]) && isObject(current[key])) {
101
- result[key] = merge11(result[key], current[key]);
93
+ result[key] = merge10(result[key], current[key]);
102
94
  } else {
103
95
  result[key] = current[key];
104
96
  }
@@ -109,18 +101,18 @@ var require_dist = __commonJS({
109
101
  var defaultOptions = {
110
102
  mergeArrays: true
111
103
  };
112
- merge11.options = defaultOptions;
113
- merge11.withOptions = function(options) {
104
+ merge10.options = defaultOptions;
105
+ merge10.withOptions = function(options) {
114
106
  var objects = [];
115
107
  for (var _i = 1; _i < arguments.length; _i++) {
116
108
  objects[_i - 1] = arguments[_i];
117
109
  }
118
- merge11.options = __assign({ mergeArrays: true }, options);
119
- var result = merge11.apply(void 0, __spreadArray([], __read(objects), false));
120
- merge11.options = defaultOptions;
110
+ merge10.options = __assign({ mergeArrays: true }, options);
111
+ var result = merge10.apply(void 0, __spreadArray([], __read(objects), false));
112
+ merge10.options = defaultOptions;
121
113
  return result;
122
114
  };
123
- exports.default = merge11;
115
+ exports.default = merge10;
124
116
  }
125
117
  });
126
118
 
@@ -149,25 +141,29 @@ var Env = class {
149
141
  };
150
142
 
151
143
  // src/cache/PersistentCache.ts
152
- var _PersistentCache = class _PersistentCache {
144
+ var PersistentCache = class _PersistentCache {
153
145
  constructor(backing) {
154
146
  this.backing = backing;
155
147
  }
148
+ static {
149
+ /** Bump to invalidate every persisted entry. */
150
+ this.VERSION = 2;
151
+ }
156
152
  static open(name) {
157
153
  return Env.provider.openCache(name, _PersistentCache.VERSION);
158
154
  }
155
+ /** Loads a missing entry and stores only non-nullish results. */
159
156
  async getOrLoad(key, loader) {
160
157
  let v = await this.get(key);
161
158
  if (typeof v === "undefined" || v === null) {
162
159
  v = await loader(key);
163
- await this.put(key, v);
160
+ if (typeof v !== "undefined" && v !== null) {
161
+ await this.put(key, v);
162
+ }
164
163
  }
165
164
  return v;
166
165
  }
167
166
  };
168
- /** Bump to invalidate every persisted entry. */
169
- _PersistentCache.VERSION = 1;
170
- var PersistentCache = _PersistentCache;
171
167
 
172
168
  // src/env/node/NodeCache.ts
173
169
  var NodeCache = class extends PersistentCache {
@@ -341,8 +337,7 @@ function serializeImageKey(key) {
341
337
  return md5(key.src);
342
338
  }
343
339
  function serializeBoxGeometryKey(key) {
344
- var _a;
345
- return md5([key.width, key.height, key.depth, (_a = key.uv) == null ? void 0 : _a.join(":")].join("_"));
340
+ return md5([key.width, key.height, key.depth, key.uv?.join(":")].join("_"));
346
341
  }
347
342
  function serializeTextureKey(key) {
348
343
  return md5([key.src, key.format, key.rotation].join("$"));
@@ -357,7 +352,61 @@ function serializeMeshKey(key) {
357
352
  // src/cache/Caching.ts
358
353
  import { Caches } from "@inventivetalent/loading-cache";
359
354
  import { Time } from "@inventivetalent/time";
360
- var Caching = class {
355
+ var Caching = class _Caching {
356
+ static {
357
+ this.rawImageCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(5)).buildAsync();
358
+ }
359
+ static {
360
+ this.imageDataCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
361
+ }
362
+ static {
363
+ this.canvasImageDataCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
364
+ }
365
+ static {
366
+ this.wrappedImageCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
367
+ }
368
+ static {
369
+ this.boxGeometryCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(20)).build();
370
+ }
371
+ static {
372
+ this.textureCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
373
+ }
374
+ static {
375
+ this.materialCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
376
+ }
377
+ static {
378
+ this.boxMeshCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
379
+ }
380
+ static {
381
+ this.textureAssetCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
382
+ }
383
+ static {
384
+ this.textureMetaCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
385
+ }
386
+ static {
387
+ this.rawModelCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
388
+ }
389
+ static {
390
+ this.mergedModelCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
391
+ }
392
+ static {
393
+ this.modelTextureAtlasCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
394
+ }
395
+ static {
396
+ this.blockStateCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
397
+ }
398
+ static {
399
+ this.listAssetCache = _Caching.createAssetCache();
400
+ }
401
+ static {
402
+ this.defaultBlockStatesCache = _Caching.createAssetCache();
403
+ }
404
+ static {
405
+ this.entityModelsCache = _Caching.createAssetCache();
406
+ }
407
+ static createAssetCache() {
408
+ return Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
409
+ }
361
410
  /** Every cache above, so clear()/end() can never fall out of sync with the field list again. */
362
411
  static get all() {
363
412
  return [
@@ -374,7 +423,10 @@ var Caching = class {
374
423
  this.rawModelCache,
375
424
  this.mergedModelCache,
376
425
  this.modelTextureAtlasCache,
377
- this.blockStateCache
426
+ this.blockStateCache,
427
+ this.listAssetCache,
428
+ this.defaultBlockStatesCache,
429
+ this.entityModelsCache
378
430
  ];
379
431
  }
380
432
  static clear() {
@@ -385,8 +437,8 @@ var Caching = class {
385
437
  /**
386
438
  * Clears every cache and stops its expiry timer.
387
439
  *
388
- * loading-cache reschedules that timer indefinitely, so a Node process will not exit until
389
- * this is called - see {@link shutdown}.
440
+ * Expiry timers are unref'd in Node, so idle processes can exit without this cleanup.
441
+ * Use {@link shutdown} to also stop requests and the shared Ticker.
390
442
  */
391
443
  static end() {
392
444
  for (const cache of this.all) {
@@ -400,20 +452,6 @@ var Caching = class {
400
452
  };
401
453
  }
402
454
  };
403
- Caching.rawImageCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(5)).buildAsync();
404
- Caching.imageDataCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
405
- Caching.canvasImageDataCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
406
- Caching.wrappedImageCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(10)).buildAsync();
407
- Caching.boxGeometryCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(20)).build();
408
- Caching.textureCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
409
- Caching.materialCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
410
- Caching.boxMeshCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).build();
411
- Caching.textureAssetCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
412
- Caching.textureMetaCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
413
- Caching.rawModelCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
414
- Caching.mergedModelCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
415
- Caching.modelTextureAtlasCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
416
- Caching.blockStateCache = Caches.builder().expireAfterWrite(Time.minutes(10)).expireAfterAccess(Time.minutes(5)).expirationInterval(Time.seconds(30)).buildAsync();
417
455
 
418
456
  // src/Geometries.ts
419
457
  var Geometries = class _Geometries {
@@ -441,6 +479,7 @@ import { CanvasTexture, Texture as Texture2 } from "three";
441
479
 
442
480
  // src/texture/TextureLoader.ts
443
481
  import { RGBAFormat, Texture } from "three";
482
+ import * as THREE from "three";
444
483
 
445
484
  // src/canvas/CanvasCompat.ts
446
485
  function createImage(width, height) {
@@ -451,9 +490,7 @@ function createCanvas2(width, height) {
451
490
  }
452
491
 
453
492
  // src/request/Requests.ts
454
- import axios from "axios";
455
- import { JobQueue } from "jobqu";
456
- import { Time as Time2 } from "@inventivetalent/time";
493
+ import { JobCancelledError, JobQueue } from "jobqu";
457
494
 
458
495
  // src/util/log.ts
459
496
  var Reset = "\x1B[0m";
@@ -463,198 +500,174 @@ function prefix(prefix2) {
463
500
  return `${FgGreen}MR${BgBlack}${prefix2 ?? ""}${Reset}`;
464
501
  }
465
502
 
466
- // src/util/BatchedExecutor.ts
467
- var BatchedExecutor = class {
468
- constructor(interval = 1, batch = 30) {
469
- this.interval = interval;
470
- this.batch = batch;
471
- this.queue = [];
472
- this.task = setInterval(() => this.run());
473
- }
474
- submit(task) {
475
- this.queue.push(task);
476
- }
477
- run() {
478
- for (let i = 0; i < this.batch; i++) {
479
- this.runNext();
480
- }
481
- }
482
- runNext() {
483
- let next = this.queue.shift();
484
- if (next) next();
503
+ // src/request/Requests.ts
504
+ var p = prefix("Requests");
505
+ var RequestError = class extends Error {
506
+ constructor(message, response, cause) {
507
+ super(message);
508
+ this.response = response;
509
+ this.cause = cause;
510
+ this.name = "RequestError";
485
511
  }
486
512
  };
487
-
488
- // src/util/model.ts
489
- import { AxesHelper, BoxGeometry as BoxGeometry2, EdgesGeometry, LineBasicMaterial, LineSegments, Vector3 as Vector32 } from "three";
490
- function applyElementRotation(rotation, geometry) {
491
- const origin = new Vector32(rotation.origin[0], rotation.origin[1], rotation.origin[2]);
492
- geometry.translate(-origin.x, -origin.y, -origin.z);
493
- switch (rotation.axis) {
494
- case "X" /* X */:
495
- geometry.rotateX(toRadians(rotation.angle));
496
- break;
497
- case "y" /* Y */:
498
- geometry.rotateY(toRadians(rotation.angle));
499
- break;
500
- case "z" /* Z */:
501
- geometry.rotateZ(toRadians(rotation.angle));
502
- break;
503
- }
504
- if (rotation.rescale) {
505
- if (Math.abs(rotation.angle) === 22.5) {
506
- const s = 1 / Math.cos(0.39269909262657166);
507
- geometry.scale(s, 1, s);
508
- } else {
509
- const s = 1 / Math.cos(0.7853981852531433);
510
- geometry.scale(s, 1, s);
513
+ async function fetchRequest(config, defaultBaseURL) {
514
+ const { url, baseURL = defaultBaseURL, timeout = 5e3, responseType = "json", signal, ...options } = config;
515
+ const target = baseURL && !/^([a-z][a-z\d+.-]*:|\/\/)/i.test(url) ? `${baseURL.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}` : url;
516
+ const headers = new Headers(options.headers);
517
+ if (typeof window === "undefined" && !headers.has("User-Agent")) {
518
+ headers.set("User-Agent", "MineRender");
519
+ }
520
+ const attemptSignal = AbortSignal.any([
521
+ ...signal ? [signal] : [],
522
+ ...timeout === 0 ? [] : [AbortSignal.timeout(timeout)]
523
+ ]);
524
+ const request = new Request(target, { ...options, headers, signal: attemptSignal });
525
+ attemptSignal.throwIfAborted();
526
+ try {
527
+ const response = await fetch(request);
528
+ const result = {
529
+ data: void 0,
530
+ status: response.status,
531
+ statusText: response.statusText,
532
+ headers: response.headers,
533
+ url: response.url
534
+ };
535
+ if (!response.ok) {
536
+ await response.body?.cancel().catch(() => {
537
+ });
538
+ throw new RequestError(`Request failed with status ${response.status}`, result);
511
539
  }
540
+ const emptyBody = request.method === "HEAD" || response.status === 204 || response.status === 205;
541
+ const data = responseType === "arraybuffer" ? await response.arrayBuffer() : emptyBody || response.body === null ? void 0 : await response.json();
542
+ return { ...result, data };
543
+ } catch (error) {
544
+ attemptSignal.throwIfAborted();
545
+ if (/^https?:/.test(request.url) && request.redirect !== "error" && error instanceof TypeError) {
546
+ throw new RequestError("Network request failed", void 0, error);
547
+ }
548
+ throw error;
512
549
  }
513
- geometry.translate(origin.x, origin.y, origin.z);
514
- }
515
- function applyModelPartRotation(modelPart, geometry) {
516
- const origin = new Vector32(modelPart.pivotX, modelPart.pivotY, modelPart.pivotZ);
517
- geometry.translate(-origin.x, -origin.y, -origin.z);
518
- geometry.rotateX(toRadians(modelPart.pitch));
519
- geometry.rotateY(toRadians(modelPart.yaw));
520
- geometry.rotateZ(toRadians(modelPart.roll));
521
- geometry.translate(origin.x, origin.y, origin.z);
522
550
  }
523
- function applyGenericRotation(axis, rotation, obj) {
524
- switch (axis) {
525
- case "X" /* X */:
526
- obj.rotateOnAxis(new Vector32(1, 0, 0), toRadians(rotation));
527
- break;
528
- case "y" /* Y */:
529
- obj.rotateOnAxis(new Vector32(0, 1, 0), toRadians(rotation));
530
- break;
531
- case "z" /* Z */:
532
- obj.rotateOnAxis(new Vector32(0, 0, 1), toRadians(rotation));
533
- break;
551
+ async function abortable(promise, signal) {
552
+ if (!signal) return promise;
553
+ let abort;
554
+ const cancelled = new Promise((_, reject) => {
555
+ abort = () => reject(signal.reason);
556
+ signal.addEventListener("abort", abort, { once: true });
557
+ if (signal.aborted) abort();
558
+ });
559
+ try {
560
+ return await Promise.race([promise, cancelled]);
561
+ } finally {
562
+ signal.removeEventListener("abort", abort);
534
563
  }
535
564
  }
536
- function addBox3WireframeToObject(box, obj, color = 16777215, w = 2) {
537
- let size = new Vector32();
538
- box.getSize(size);
539
- let boxGeo = new BoxGeometry2(size.x, size.y, size.z, 1, 1, 1);
540
- let wireGeo = new EdgesGeometry(boxGeo);
541
- let wireMat = new LineBasicMaterial({ color, linewidth: w });
542
- let wireframe = new LineSegments(wireGeo, wireMat);
543
- obj.add(wireframe);
544
- let axes = new AxesHelper(1);
545
- obj.add(axes);
546
- }
547
- function addWireframeToObject(obj, color = 16777215, w = 2) {
548
- let boxGeo = new BoxGeometry2(16, 16, 16, 1, 1, 1);
549
- let wireGeo = new EdgesGeometry(boxGeo);
550
- let wireMat = new LineBasicMaterial({ color, linewidth: w });
551
- let wireframe = new LineSegments(wireGeo, wireMat);
552
- obj.add(wireframe);
553
- let axes = new AxesHelper(1);
554
- obj.add(axes);
555
- }
556
- function addWireframeToMesh(geo, mesh, color = 16777215, w = 2) {
557
- let wireGeo = new EdgesGeometry(geo);
558
- let wireMat = new LineBasicMaterial({ color, linewidth: w });
559
- let wireframe = new LineSegments(wireGeo, wireMat);
560
- mesh.add(wireframe);
561
- let axes = new AxesHelper(1);
562
- mesh.add(axes);
563
- }
564
-
565
- // src/util/performance.ts
566
- function captureException(e, ...extra) {
567
- console.error(e, extra);
568
- }
569
- function timingStart(marker) {
570
- console.time(marker);
571
- }
572
- function timingEnd(marker) {
573
- console.timeEnd(marker);
574
- }
575
-
576
- // src/util/three.ts
577
- function isObject3D(obj) {
578
- return obj.isObject3D;
579
- }
580
- function isMesh(obj) {
581
- return obj.isMesh;
582
- }
583
- function isInstancedMesh(obj) {
584
- return obj.isInstancedMesh;
585
- }
586
- function isPerspectiveCamera(obj) {
587
- return obj.isPerspectiveCamera;
588
- }
589
- function isOrthographicCamera(obj) {
590
- return obj.isOrthographicCamera;
591
- }
592
-
593
- // src/request/Requests.ts
594
- var p = prefix("Requests");
595
- if (typeof window === "undefined") {
596
- axios.defaults.headers["User-Agent"] = "MineRender";
597
- }
598
- var _Requests = class _Requests {
599
- static genericRequest(request) {
600
- return this.genericQueue.add(request).catch(async (e) => {
601
- console.debug(p, "generic catch", e.code, e);
602
- if (this.shouldRetry(e, request)) {
603
- await sleep(100);
604
- return this.genericRequest(request);
605
- }
606
- throw e;
607
- });
608
- }
609
- static mcAssetRequest(request) {
610
- return this.mcAssetRequestQueue.add(request).catch((e) => {
611
- console.debug(p, "mcAssetRequest catch", e.code, e);
612
- throw e;
613
- });
565
+ var RequestQueue = class {
566
+ constructor() {
567
+ this.pendingRequests = 0;
568
+ this.stopped = new AbortController();
569
+ this.queue = new JobQueue(
570
+ (request) => fetchRequest(request, this.baseURL),
571
+ { interval: 10, maxPerRun: 1, maxActive: 8 }
572
+ );
614
573
  }
615
- static shouldRetry(e, request) {
616
- if ("code" in e) {
617
- if ("ECONNABORTED" === e.code) {
618
- if ("minerenderRetry" in request) {
619
- if (request["minerenderRetry"] > 0) {
620
- request["minerenderRetry"]--;
621
- return true;
574
+ async request(request) {
575
+ this.pendingRequests++;
576
+ const signal = request.signal;
577
+ try {
578
+ for (let retries = 0; ; retries++) {
579
+ signal?.throwIfAborted();
580
+ try {
581
+ return await abortable(this.queue.add(request), signal);
582
+ } catch (error) {
583
+ console.debug(p, "Request failed", error);
584
+ const delay = this.retryDelay(error, request, retries);
585
+ if (delay === void 0) {
586
+ throw error;
622
587
  }
623
- } else {
624
- request["minerenderRetry"] = 3;
625
- return true;
588
+ await this.waitForRetry(delay, signal);
626
589
  }
627
590
  }
591
+ } finally {
592
+ if (signal?.aborted) {
593
+ this.queue.remove(request);
594
+ }
595
+ this.pendingRequests--;
628
596
  }
629
- return false;
597
+ }
598
+ retryDelay(error, request, retries) {
599
+ if (this.stopped.signal.aborted || retries >= 3 || (request.method ?? "get").toLowerCase() !== "get" || request.signal?.aborted) {
600
+ return void 0;
601
+ }
602
+ if (error instanceof RequestError) {
603
+ const status = error.response?.status;
604
+ if (status !== void 0 && status !== 408 && status !== 429 && !(status >= 500 && status < 600)) return void 0;
605
+ } else if (!(error instanceof DOMException && error.name === "TimeoutError")) {
606
+ return void 0;
607
+ }
608
+ let delay = 100 * 2 ** retries;
609
+ const retryAfter = error instanceof RequestError ? error.response?.headers.get("Retry-After") : void 0;
610
+ if (retryAfter !== void 0 && retryAfter !== null) {
611
+ const seconds = Number(retryAfter);
612
+ if (!retryAfter.trim() || !Number.isFinite(seconds) || seconds < 0) {
613
+ return void 0;
614
+ }
615
+ delay = Math.max(delay, seconds * 1e3);
616
+ }
617
+ return delay;
618
+ }
619
+ async waitForRetry(delay, signal) {
620
+ let timer;
621
+ const waiting = new Promise((resolve) => {
622
+ timer = setTimeout(resolve, delay);
623
+ });
624
+ try {
625
+ await abortable(waiting, AbortSignal.any([this.stopped.signal, ...signal ? [signal] : []]));
626
+ } finally {
627
+ clearTimeout(timer);
628
+ }
629
+ }
630
+ get pendingSize() {
631
+ return this.pendingRequests;
632
+ }
633
+ end() {
634
+ this.queue.end();
635
+ this.stopped.abort(new JobCancelledError("ended"));
636
+ }
637
+ };
638
+ var Requests = class {
639
+ static {
640
+ this.genericQueue = new RequestQueue();
641
+ }
642
+ static {
643
+ this.mcAssetRequestQueue = new RequestQueue();
644
+ }
645
+ static genericRequest(request) {
646
+ return this.genericQueue.request(request);
647
+ }
648
+ static mcAssetRequest(request) {
649
+ return this.mcAssetRequestQueue.request(request);
630
650
  }
631
651
  static setMcAssetRoot(root) {
632
- this.mcAssetInstance.defaults.baseURL = root;
652
+ this.mcAssetRequestQueue.baseURL = root;
633
653
  }
654
+ /** Counts unsettled calls, including retry delays and requests still running after shutdown. */
634
655
  static get queueSizes() {
635
656
  return {
636
- generic: this.genericQueue.size,
637
- mcAsset: this.mcAssetRequestQueue.size
657
+ generic: this.genericQueue.pendingSize,
658
+ mcAsset: this.mcAssetRequestQueue.pendingSize
638
659
  };
639
660
  }
640
661
  /**
641
- * Stops both queue timers. jobqu reschedules itself indefinitely, so a Node process will not
642
- * exit until this is called - see {@link shutdown}.
662
+ * Permanently stops both queues and rejects waiting, retrying, and future requests.
663
+ * Requests already running can finish. Idle queues hold no timer, so Node can exit without
664
+ * this cleanup. See {@link shutdown}.
643
665
  */
644
666
  static end() {
645
667
  this.genericQueue.end();
646
668
  this.mcAssetRequestQueue.end();
647
669
  }
648
670
  };
649
- _Requests.axiosInstance = axios.create({
650
- timeout: 5e3
651
- });
652
- _Requests.mcAssetInstance = axios.create({
653
- timeout: 5e3
654
- });
655
- _Requests.genericQueue = new JobQueue((request) => _Requests.axiosInstance.request(request), Time2.millis(10), 1);
656
- _Requests.mcAssetRequestQueue = new JobQueue((request) => _Requests.mcAssetInstance.request(request), Time2.millis(10), 1);
657
- var Requests = _Requests;
658
671
 
659
672
  // src/WrappedImage.ts
660
673
  var WrappedImage = class {
@@ -719,29 +732,41 @@ var ImageLoader = class _ImageLoader {
719
732
  static async loadAsync(src) {
720
733
  return new Promise((resolve, reject) => {
721
734
  const image = this._createImage();
722
- image.src = src;
723
735
  image.onload = () => resolve(image);
724
- image.onerror = (err) => reject(err);
736
+ image.onerror = (err) => reject(err instanceof Error ? err : new Error("Failed to decode image"));
737
+ image.src = src;
725
738
  });
726
739
  }
727
740
  static loadElement(src, onload, onerr) {
728
741
  const image = this._createImage();
729
- image.src = src;
730
742
  if (onload)
731
743
  image.onload = onload;
732
744
  if (onerr)
733
745
  image.onerror = onerr;
746
+ image.src = src;
734
747
  return image;
735
748
  }
736
749
  static async loadData(src) {
737
750
  console.debug(p2, "loadData", src);
738
- return await this.infoToData(await this.getInfo(src));
751
+ const image = await this.loadCanvasData(src);
752
+ return image.data.getImageData(0, 0, image.width, image.height);
739
753
  }
740
754
  static async loadCanvasData(src) {
741
- return await this.infoToCanvasData(await this.getInfo(src));
755
+ const keyStr = serializeImageKey({ src });
756
+ const info = this.getInfo(src);
757
+ const cached = Caching.rawImageCache.getIfPresent(keyStr);
758
+ try {
759
+ return await this.infoToCanvasData(await info);
760
+ } catch (err) {
761
+ if (cached && Caching.rawImageCache.getIfPresent(keyStr) === cached) {
762
+ Caching.rawImageCache.invalidate(keyStr);
763
+ }
764
+ throw err;
765
+ }
742
766
  }
743
767
  static async infoToCanvasData(info) {
744
- const image = await _ImageLoader.loadAsync(info.src);
768
+ const type = info.type === "jpg" ? "jpeg" : info.type ?? "png";
769
+ const image = await _ImageLoader.loadAsync(`data:image/${type};base64,${info.data.toString("base64")}`);
745
770
  const canvas = createCanvas2(info.width, info.height);
746
771
  const context = canvas.getContext("2d");
747
772
  context.drawImage(image, 0, 0);
@@ -752,11 +777,8 @@ var ImageLoader = class _ImageLoader {
752
777
  };
753
778
  }
754
779
  static async infoToData(info) {
755
- const image = await _ImageLoader.loadAsync(info.src);
756
- const canvas = createCanvas2(info.width, info.height);
757
- const context = canvas.getContext("2d");
758
- context.drawImage(image, 0, 0);
759
- return context.getImageData(0, 0, canvas.width, canvas.height);
780
+ const image = await this.infoToCanvasData(info);
781
+ return image.data.getImageData(0, 0, image.width, image.height);
760
782
  }
761
783
  static async getData(src) {
762
784
  const keyStr = serializeImageKey({ src });
@@ -771,38 +793,25 @@ var ImageLoader = class _ImageLoader {
771
793
  });
772
794
  }
773
795
  static async processResponse(response) {
774
- const src = response.config.url;
796
+ const src = response.url;
775
797
  const data = Buffer2.from(response.data);
776
798
  const { width, height, type } = Env.provider.imageSize(data);
799
+ if (!width || !height) {
800
+ throw new Error("Invalid or unsupported image dimensions");
801
+ }
777
802
  return {
778
803
  src,
779
- width: width || 0,
780
- height: height || 0,
804
+ width,
805
+ height,
781
806
  type,
782
807
  data
783
808
  };
784
809
  }
785
810
  static async loadInfo(src) {
786
- if (src.startsWith("data:image/png;base64")) {
787
- return this.processResponse({
788
- config: {
789
- url: src
790
- },
791
- data: Buffer2.from(src.substr("data:image/png;base64,".length), "base64")
792
- });
793
- }
794
811
  return Requests.genericRequest({
795
812
  url: src,
796
813
  responseType: "arraybuffer"
797
- }).then(this.processResponse).catch((err) => {
798
- return {
799
- src,
800
- width: 0,
801
- height: 0,
802
- type: void 0,
803
- data: Buffer2.from([0])
804
- };
805
- });
814
+ }).then(this.processResponse);
806
815
  }
807
816
  static async getInfo(src) {
808
817
  const keyStr = serializeImageKey({ src });
@@ -824,15 +833,25 @@ var ImageLoader = class _ImageLoader {
824
833
 
825
834
  // src/texture/TextureLoader.ts
826
835
  var TextureLoader = class {
836
+ static {
837
+ this.failedTextures = /* @__PURE__ */ new WeakSet();
838
+ }
839
+ /** Reports whether image loading failed, so cached textures can be retried. */
840
+ static hasFailed(texture) {
841
+ return this.failedTextures.has(texture);
842
+ }
827
843
  static createTexture() {
828
844
  return new Texture();
829
845
  }
830
846
  static loadInBackground(src, format = RGBAFormat, rotation = 0) {
831
847
  const texture = this.createTexture();
832
- const image = ImageLoader.loadElement(src);
833
- image.onload = function() {
848
+ texture.colorSpace = THREE.SRGBColorSpace;
849
+ const image = ImageLoader.loadElement(src, () => {
834
850
  texture.needsUpdate = true;
835
- };
851
+ }, (error) => {
852
+ this.failedTextures.add(texture);
853
+ console.warn("Failed to load texture", src, error);
854
+ });
836
855
  texture.image = image;
837
856
  texture.format = format;
838
857
  texture.rotation = rotation;
@@ -840,9 +859,13 @@ var TextureLoader = class {
840
859
  }
841
860
  static load(src, format = RGBAFormat, rotation = 0) {
842
861
  const texture = new Texture();
862
+ texture.colorSpace = THREE.SRGBColorSpace;
843
863
  ImageLoader.getData(src).then((image) => {
844
- texture.needsUpdate = true;
845
864
  texture.image = image;
865
+ texture.needsUpdate = true;
866
+ }).catch((error) => {
867
+ this.failedTextures.add(texture);
868
+ console.warn("Failed to load texture", src, error);
846
869
  });
847
870
  texture.format = format;
848
871
  texture.rotation = rotation;
@@ -851,11 +874,11 @@ var TextureLoader = class {
851
874
  };
852
875
 
853
876
  // src/texture/Textures.ts
854
- import * as THREE from "three";
877
+ import * as THREE2 from "three";
855
878
  var Textures = class _Textures {
856
879
  static initTextureProps(texture) {
857
- texture.magFilter = THREE.NearestFilter;
858
- texture.minFilter = THREE.NearestFilter;
880
+ texture.magFilter = THREE2.NearestFilter;
881
+ texture.minFilter = THREE2.NearestFilter;
859
882
  texture.anisotropy = 0;
860
883
  return texture;
861
884
  }
@@ -866,10 +889,16 @@ var Textures = class _Textures {
866
889
  return new Texture2();
867
890
  }
868
891
  static createCanvasTexture(canvas) {
869
- return this.initTextureProps(new CanvasTexture(canvas));
892
+ const texture = new CanvasTexture(canvas);
893
+ texture.colorSpace = THREE2.SRGBColorSpace;
894
+ return this.initTextureProps(texture);
870
895
  }
871
896
  static getImage(key) {
872
897
  const keyStr = serializeTextureKey(key);
898
+ const cached = Caching.textureCache.peek(keyStr);
899
+ if (cached && TextureLoader.hasFailed(cached)) {
900
+ Caching.textureCache.invalidate(keyStr);
901
+ }
873
902
  return Caching.textureCache.get(keyStr, (k) => {
874
903
  return _Textures.createImage(key);
875
904
  });
@@ -877,7 +906,10 @@ var Textures = class _Textures {
877
906
  };
878
907
 
879
908
  // src/Materials.ts
880
- var _Materials = class _Materials {
909
+ var Materials = class _Materials {
910
+ static {
911
+ this.MISSING_TEXTURE_SRC = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQMAAACQp+OdAAAABlBMVEX/AP8AAACfphTyAAAAFUlEQVQoz2MIhQKGVVAwKjIqQrwIAHRz/wFI17TEAAAAAElFTkSuQmCC";
912
+ }
881
913
  // resolved lazily: as a static field this decoded an image the moment the library was
882
914
  // imported, which needs both a DOM and an EnvProvider to already be in place
883
915
  static get MISSING_TEXTURE() {
@@ -983,6 +1015,9 @@ var _Materials = class _Materials {
983
1015
  gl_FragColor = vec4(lift + color.rgb * light2, 1.0);
984
1016
 
985
1017
  }
1018
+
1019
+ #include <tonemapping_fragment>
1020
+ #include <colorspace_fragment>
986
1021
  }
987
1022
  `;
988
1023
  try {
@@ -1011,6 +1046,10 @@ var _Materials = class _Materials {
1011
1046
  }
1012
1047
  static getImage(key) {
1013
1048
  const keyStr = serializeMaterialKey(key);
1049
+ const map = Caching.materialCache.peek(keyStr)?.map;
1050
+ if (map && TextureLoader.hasFailed(map)) {
1051
+ Caching.materialCache.invalidate(keyStr);
1052
+ }
1014
1053
  return Caching.materialCache.get(keyStr, (k) => {
1015
1054
  return _Materials.createImage(key);
1016
1055
  });
@@ -1031,14 +1070,12 @@ var _Materials = class _Materials {
1031
1070
  }
1032
1071
  }
1033
1072
  };
1034
- _Materials.MISSING_TEXTURE_SRC = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAQMAAACQp+OdAAAABlBMVEX/AP8AAACfphTyAAAAFUlEQVQoz2MIhQKGVVAwKjIqQrwIAHRz/wFI17TEAAAAAElFTkSuQmCC";
1035
- var Materials = _Materials;
1036
1073
 
1037
1074
  // src/Meshes.ts
1038
- import { Mesh as Mesh2 } from "three";
1075
+ import { Mesh } from "three";
1039
1076
  var Meshes = class _Meshes {
1040
1077
  static createBox(key) {
1041
- return new Mesh2(Geometries.getBox(key.geometry), Materials.getImage(key.material));
1078
+ return new Mesh(Geometries.getBox(key.geometry), Materials.getImage(key.material));
1042
1079
  }
1043
1080
  static getBox(key) {
1044
1081
  const keyStr = serializeMeshKey(key);
@@ -1087,7 +1124,7 @@ var AssetKey = class _AssetKey extends BasicAssetKey {
1087
1124
  this.root = root;
1088
1125
  }
1089
1126
  static parse(assetType, str, origin) {
1090
- let namespace = (origin == null ? void 0 : origin.namespace) || DEFAULT_NAMESPACE;
1127
+ let namespace = origin?.namespace || DEFAULT_NAMESPACE;
1091
1128
  if (str.includes(":")) {
1092
1129
  let split2 = str.split(":");
1093
1130
  namespace = split2[0];
@@ -1100,8 +1137,8 @@ var AssetKey = class _AssetKey extends BasicAssetKey {
1100
1137
  split.shift();
1101
1138
  }
1102
1139
  let path = split.join("/");
1103
- let extension = assetType === "textures" ? ".png" : (origin == null ? void 0 : origin.assetType) || ".json";
1104
- return new _AssetKey(namespace, path, assetType, type, "assets", extension, origin == null ? void 0 : origin.root);
1140
+ let extension = assetType === "textures" ? ".png" : origin?.assetType || ".json";
1141
+ return new _AssetKey(namespace, path, assetType, type, "assets", extension, origin?.root);
1105
1142
  }
1106
1143
  toString() {
1107
1144
  let a = [
@@ -1164,9 +1201,6 @@ var ModelMerger = class {
1164
1201
  }
1165
1202
  };
1166
1203
 
1167
- // src/assets/Models.ts
1168
- import { Memoize } from "typescript-memoize";
1169
-
1170
1204
  // src/assets/source/parser/AssetParsers.ts
1171
1205
  var AssetParser = /* @__PURE__ */ ((AssetParser2) => {
1172
1206
  AssetParser2["MODEL"] = "model";
@@ -1180,14 +1214,14 @@ var AssetParser = /* @__PURE__ */ ((AssetParser2) => {
1180
1214
  })(AssetParser || {});
1181
1215
 
1182
1216
  // src/assets/Models.ts
1183
- var _Models = class _Models {
1217
+ var Models = class _Models {
1184
1218
  // opened lazily: touching the store at import time would hit IndexedDB/disk just for loading
1185
1219
  // the library, and would require an EnvProvider before any entry has had a chance to register
1186
1220
  static get PERSISTENT_CACHE() {
1187
1221
  return this._persistentCache ??= PersistentCache.open("minerender-models");
1188
1222
  }
1189
1223
  static async getItemList() {
1190
- return AssetLoader.get(new AssetKey(
1224
+ const key = new AssetKey(
1191
1225
  DEFAULT_NAMESPACE,
1192
1226
  "_list",
1193
1227
  "models",
@@ -1195,7 +1229,10 @@ var _Models = class _Models {
1195
1229
  "assets",
1196
1230
  ".json",
1197
1231
  DEFAULT_ROOT
1198
- ), "list" /* LIST */).then((r) => (r == null ? void 0 : r.files) ?? []);
1232
+ );
1233
+ return Caching.listAssetCache.get(key.serialize(), () => {
1234
+ return AssetLoader.get(key, "list" /* LIST */);
1235
+ }).then((r) => r?.files ?? []);
1199
1236
  }
1200
1237
  static async loadAndMerge(key) {
1201
1238
  const model = await this.getRaw(key);
@@ -1242,19 +1279,15 @@ var _Models = class _Models {
1242
1279
  return this.PERSISTENT_CACHE.clear();
1243
1280
  }
1244
1281
  };
1245
- __decorateClass([
1246
- Memoize()
1247
- ], _Models, "getItemList", 1);
1248
- var Models = _Models;
1249
1282
 
1250
1283
  // src/assets/BlockStates.ts
1251
- import { Memoize as Memoize2 } from "typescript-memoize";
1252
1284
  var BlockStates = class {
1253
1285
  static get PERSISTENT_CACHE() {
1254
1286
  return this._persistentCache ??= PersistentCache.open("minerender-blockstates");
1255
1287
  }
1288
+ // BlockState names are hardcoded
1256
1289
  static async getList() {
1257
- return AssetLoader.get(new AssetKey(
1290
+ const key = new AssetKey(
1258
1291
  DEFAULT_NAMESPACE,
1259
1292
  "_list",
1260
1293
  "blockstates",
@@ -1262,11 +1295,16 @@ var BlockStates = class {
1262
1295
  "assets",
1263
1296
  ".json",
1264
1297
  DEFAULT_ROOT
1265
- ), "list" /* LIST */).then((r) => (r == null ? void 0 : r.files) ?? []);
1298
+ );
1299
+ return Caching.listAssetCache.get(key.serialize(), () => {
1300
+ return AssetLoader.get(key, "list" /* LIST */);
1301
+ }).then((r) => r?.files ?? []);
1266
1302
  }
1267
1303
  static async getDefaultStates() {
1268
1304
  const key = AssetKey.parse("blockstates", "minerender:defaultBlockStates");
1269
- return AssetLoader.get(key, "json" /* JSON */);
1305
+ return Caching.defaultBlockStatesCache.get(key.serialize(), () => {
1306
+ return AssetLoader.get(key, "json" /* JSON */);
1307
+ });
1270
1308
  }
1271
1309
  static async getDefaultState(key) {
1272
1310
  const defaultStates = await this.getDefaultStates();
@@ -1305,17 +1343,11 @@ var BlockStates = class {
1305
1343
  await this.PERSISTENT_CACHE.clear();
1306
1344
  }
1307
1345
  };
1308
- __decorateClass([
1309
- Memoize2()
1310
- ], BlockStates, "getList", 1);
1311
- __decorateClass([
1312
- Memoize2()
1313
- ], BlockStates, "getDefaultStates", 1);
1314
1346
  var DefaultBlockStates = class {
1315
1347
  };
1316
1348
 
1317
1349
  // src/assets/Assets.ts
1318
- var DEFAULT_ROOT = "https://cdn.mcasset.cloud/file/minecraft-assets/1.17.1";
1350
+ var DEFAULT_ROOT = "https://assets.mcasset.cloud/1.17.1";
1319
1351
  var DEFAULT_NAMESPACE = "minecraft";
1320
1352
  var Assets = class {
1321
1353
  /**
@@ -1338,22 +1370,225 @@ var AssetSource = class {
1338
1370
  }
1339
1371
  };
1340
1372
 
1341
- // src/nbt/NBTHelper.ts
1342
- var NBTHelper = class {
1343
- static async fromBuffer(buffer) {
1344
- const prismarineNbt = await import("prismarine-nbt");
1345
- const { parsed, type, metadata } = await prismarineNbt.parse(buffer);
1346
- return parsed;
1373
+ // src/util/BatchedExecutor.ts
1374
+ var BatchedExecutor = class {
1375
+ constructor(interval = 1, batch = 30) {
1376
+ this.interval = interval;
1377
+ this.batch = batch;
1378
+ this.queue = [];
1379
+ this.task = setInterval(() => this.run());
1380
+ }
1381
+ submit(task) {
1382
+ this.queue.push(task);
1383
+ }
1384
+ run() {
1385
+ for (let i = 0; i < this.batch; i++) {
1386
+ this.runNext();
1387
+ }
1388
+ }
1389
+ runNext() {
1390
+ let next = this.queue.shift();
1391
+ if (next) next();
1347
1392
  }
1348
1393
  };
1349
1394
 
1350
- // src/assets/source/HostedAssetSource.ts
1351
- var import_ts_deepmerge2 = __toESM(require_dist());
1352
- var p3 = prefix("HostedAssetSource");
1353
- var DEFAULT_OPTIONS = {
1354
- retryDefaults: true
1355
- };
1356
- var _HostedAssetSource = class _HostedAssetSource extends AssetSource {
1395
+ // src/util/model.ts
1396
+ import { AxesHelper, BoxGeometry as BoxGeometry2, EdgesGeometry, LineBasicMaterial, LineSegments, Vector3 as Vector32 } from "three";
1397
+ function applyElementRotation(rotation, geometry) {
1398
+ const origin = new Vector32(rotation.origin[0], rotation.origin[1], rotation.origin[2]);
1399
+ geometry.translate(-origin.x, -origin.y, -origin.z);
1400
+ switch (rotation.axis) {
1401
+ case "X" /* X */:
1402
+ geometry.rotateX(toRadians(rotation.angle));
1403
+ break;
1404
+ case "y" /* Y */:
1405
+ geometry.rotateY(toRadians(rotation.angle));
1406
+ break;
1407
+ case "z" /* Z */:
1408
+ geometry.rotateZ(toRadians(rotation.angle));
1409
+ break;
1410
+ }
1411
+ if (rotation.rescale) {
1412
+ if (Math.abs(rotation.angle) === 22.5) {
1413
+ const s = 1 / Math.cos(0.39269909262657166);
1414
+ geometry.scale(s, 1, s);
1415
+ } else {
1416
+ const s = 1 / Math.cos(0.7853981852531433);
1417
+ geometry.scale(s, 1, s);
1418
+ }
1419
+ }
1420
+ geometry.translate(origin.x, origin.y, origin.z);
1421
+ }
1422
+ function applyModelPartRotation(modelPart, geometry) {
1423
+ const origin = new Vector32(modelPart.pivotX, modelPart.pivotY, modelPart.pivotZ);
1424
+ geometry.translate(-origin.x, -origin.y, -origin.z);
1425
+ geometry.rotateX(toRadians(modelPart.pitch));
1426
+ geometry.rotateY(toRadians(modelPart.yaw));
1427
+ geometry.rotateZ(toRadians(modelPart.roll));
1428
+ geometry.translate(origin.x, origin.y, origin.z);
1429
+ }
1430
+ function applyGenericRotation(axis, rotation, obj) {
1431
+ switch (axis) {
1432
+ case "X" /* X */:
1433
+ obj.rotateOnAxis(new Vector32(1, 0, 0), toRadians(rotation));
1434
+ break;
1435
+ case "y" /* Y */:
1436
+ obj.rotateOnAxis(new Vector32(0, 1, 0), toRadians(rotation));
1437
+ break;
1438
+ case "z" /* Z */:
1439
+ obj.rotateOnAxis(new Vector32(0, 0, 1), toRadians(rotation));
1440
+ break;
1441
+ }
1442
+ }
1443
+ function addBox3WireframeToObject(box, obj, color = 16777215, w = 2) {
1444
+ let size = new Vector32();
1445
+ box.getSize(size);
1446
+ let boxGeo = new BoxGeometry2(size.x, size.y, size.z, 1, 1, 1);
1447
+ let wireGeo = new EdgesGeometry(boxGeo);
1448
+ let wireMat = new LineBasicMaterial({ color, linewidth: w });
1449
+ let wireframe = new LineSegments(wireGeo, wireMat);
1450
+ obj.add(wireframe);
1451
+ let axes = new AxesHelper(1);
1452
+ obj.add(axes);
1453
+ }
1454
+ function addWireframeToObject(obj, color = 16777215, w = 2) {
1455
+ let boxGeo = new BoxGeometry2(16, 16, 16, 1, 1, 1);
1456
+ let wireGeo = new EdgesGeometry(boxGeo);
1457
+ let wireMat = new LineBasicMaterial({ color, linewidth: w });
1458
+ let wireframe = new LineSegments(wireGeo, wireMat);
1459
+ obj.add(wireframe);
1460
+ let axes = new AxesHelper(1);
1461
+ obj.add(axes);
1462
+ }
1463
+ function addWireframeToMesh(geo, mesh, color = 16777215, w = 2) {
1464
+ let wireGeo = new EdgesGeometry(geo);
1465
+ let wireMat = new LineBasicMaterial({ color, linewidth: w });
1466
+ let wireframe = new LineSegments(wireGeo, wireMat);
1467
+ mesh.add(wireframe);
1468
+ let axes = new AxesHelper(1);
1469
+ mesh.add(axes);
1470
+ }
1471
+
1472
+ // src/util/performance.ts
1473
+ function captureException(e, ...extra) {
1474
+ console.error(e, extra);
1475
+ }
1476
+ function timingStart(marker) {
1477
+ console.time(marker);
1478
+ }
1479
+ function timingEnd(marker) {
1480
+ console.timeEnd(marker);
1481
+ }
1482
+
1483
+ // src/util/three.ts
1484
+ function isObject3D(obj) {
1485
+ return obj.isObject3D;
1486
+ }
1487
+ function isMesh(obj) {
1488
+ return obj.isMesh;
1489
+ }
1490
+ function isInstancedMesh(obj) {
1491
+ return obj.isInstancedMesh;
1492
+ }
1493
+ function isPerspectiveCamera(obj) {
1494
+ return obj.isPerspectiveCamera;
1495
+ }
1496
+ function isOrthographicCamera(obj) {
1497
+ return obj.isOrthographicCamera;
1498
+ }
1499
+
1500
+ // src/nbt/NBTHelper.ts
1501
+ var NBTHelper = class {
1502
+ static async fromBuffer(buffer) {
1503
+ const prismarineNbt = await import("prismarine-nbt");
1504
+ const { parsed, type, metadata } = await prismarineNbt.parse(buffer);
1505
+ return parsed;
1506
+ }
1507
+ };
1508
+
1509
+ // src/assets/source/HostedAssetSource.ts
1510
+ var import_ts_deepmerge2 = __toESM(require_dist());
1511
+ var p3 = prefix("HostedAssetSource");
1512
+ var DEFAULT_OPTIONS = {
1513
+ retryDefaults: true
1514
+ };
1515
+ var HostedAssetSource = class _HostedAssetSource extends AssetSource {
1516
+ static {
1517
+ this.MODEL = {
1518
+ config(request) {
1519
+ },
1520
+ parse(response) {
1521
+ return response.data;
1522
+ }
1523
+ };
1524
+ }
1525
+ static {
1526
+ this.BLOCKSTATE = {
1527
+ config(request) {
1528
+ },
1529
+ parse(response) {
1530
+ return response.data;
1531
+ }
1532
+ };
1533
+ }
1534
+ static {
1535
+ this.META = {
1536
+ config(request) {
1537
+ },
1538
+ parse(response) {
1539
+ return response.data;
1540
+ }
1541
+ };
1542
+ }
1543
+ static {
1544
+ this.NBT = {
1545
+ config(request) {
1546
+ request.responseType = "arraybuffer";
1547
+ },
1548
+ parse(response) {
1549
+ return NBTHelper.fromBuffer(Buffer.from(response.data));
1550
+ }
1551
+ };
1552
+ }
1553
+ static {
1554
+ this.IMAGE = {
1555
+ config(request) {
1556
+ request.responseType = "arraybuffer";
1557
+ },
1558
+ async parse(response) {
1559
+ return await ImageLoader.processResponse(response);
1560
+ }
1561
+ };
1562
+ }
1563
+ static {
1564
+ this.LIST = {
1565
+ config(request) {
1566
+ },
1567
+ parse(response) {
1568
+ return response.data;
1569
+ }
1570
+ };
1571
+ }
1572
+ static {
1573
+ this.JSON = {
1574
+ config(request) {
1575
+ },
1576
+ parse(response) {
1577
+ return response.data;
1578
+ }
1579
+ };
1580
+ }
1581
+ static {
1582
+ this.PARSER_MAP = /* @__PURE__ */ new Map([
1583
+ ["model" /* MODEL */, _HostedAssetSource.MODEL],
1584
+ ["blockstate" /* BLOCKSTATE */, _HostedAssetSource.BLOCKSTATE],
1585
+ ["meta" /* META */, _HostedAssetSource.META],
1586
+ ["nbt" /* NBT */, _HostedAssetSource.NBT],
1587
+ ["image" /* IMAGE */, _HostedAssetSource.IMAGE],
1588
+ ["list" /* LIST */, _HostedAssetSource.LIST],
1589
+ ["json" /* JSON */, _HostedAssetSource.JSON]
1590
+ ]);
1591
+ }
1357
1592
  async loadOrRetryWithDefaults(key, parser) {
1358
1593
  const direct = await this.load(key, parser);
1359
1594
  if (typeof direct !== "undefined") {
@@ -1410,7 +1645,7 @@ var _HostedAssetSource = class _HostedAssetSource extends AssetSource {
1410
1645
  return void 0;
1411
1646
  }
1412
1647
  }
1413
- console.debug(p3, "Failed to load", key, err == null ? void 0 : err.message);
1648
+ console.debug(p3, "Failed to load", key, err?.message);
1414
1649
  return void 0;
1415
1650
  });
1416
1651
  }
@@ -1436,67 +1671,6 @@ var _HostedAssetSource = class _HostedAssetSource extends AssetSource {
1436
1671
  return this.load(key, responseParser);
1437
1672
  }
1438
1673
  };
1439
- _HostedAssetSource.MODEL = {
1440
- config(request) {
1441
- },
1442
- parse(response) {
1443
- return response.data;
1444
- }
1445
- };
1446
- _HostedAssetSource.BLOCKSTATE = {
1447
- config(request) {
1448
- },
1449
- parse(response) {
1450
- return response.data;
1451
- }
1452
- };
1453
- _HostedAssetSource.META = {
1454
- config(request) {
1455
- },
1456
- parse(response) {
1457
- return response.data;
1458
- }
1459
- };
1460
- _HostedAssetSource.NBT = {
1461
- config(request) {
1462
- request.responseType = "arraybuffer";
1463
- },
1464
- parse(response) {
1465
- return NBTHelper.fromBuffer(Buffer.from(response.data));
1466
- }
1467
- };
1468
- _HostedAssetSource.IMAGE = {
1469
- config(request) {
1470
- request.responseType = "arraybuffer";
1471
- },
1472
- async parse(response) {
1473
- return await ImageLoader.processResponse(response);
1474
- }
1475
- };
1476
- _HostedAssetSource.LIST = {
1477
- config(request) {
1478
- },
1479
- parse(response) {
1480
- return response.data;
1481
- }
1482
- };
1483
- _HostedAssetSource.JSON = {
1484
- config(request) {
1485
- },
1486
- parse(response) {
1487
- return response.data;
1488
- }
1489
- };
1490
- _HostedAssetSource.PARSER_MAP = /* @__PURE__ */ new Map([
1491
- ["model" /* MODEL */, _HostedAssetSource.MODEL],
1492
- ["blockstate" /* BLOCKSTATE */, _HostedAssetSource.BLOCKSTATE],
1493
- ["meta" /* META */, _HostedAssetSource.META],
1494
- ["nbt" /* NBT */, _HostedAssetSource.NBT],
1495
- ["image" /* IMAGE */, _HostedAssetSource.IMAGE],
1496
- ["list" /* LIST */, _HostedAssetSource.LIST],
1497
- ["json" /* JSON */, _HostedAssetSource.JSON]
1498
- ]);
1499
- var HostedAssetSource = _HostedAssetSource;
1500
1674
 
1501
1675
  // src/assets/source/archive/BrowserArchiveProxy.ts
1502
1676
  import { BlobReader, BlobWriter, ZipReader } from "@zip.js/zip.js";
@@ -1572,7 +1746,7 @@ var ArchiveAssetSource = class _ArchiveAssetSource extends AssetSource {
1572
1746
  return void 0;
1573
1747
  }
1574
1748
  }
1575
- console.debug(p4, "Failed to load", key, err == null ? void 0 : err.message);
1749
+ console.debug(p4, "Failed to load", key, err?.message);
1576
1750
  return void 0;
1577
1751
  });
1578
1752
  }
@@ -1603,7 +1777,7 @@ var ArchiveAssetSource = class _ArchiveAssetSource extends AssetSource {
1603
1777
  return void 0;
1604
1778
  }
1605
1779
  }
1606
- console.debug(p4, "Failed to load", key, err == null ? void 0 : err.message);
1780
+ console.debug(p4, "Failed to load", key, err?.message);
1607
1781
  return void 0;
1608
1782
  });
1609
1783
  }
@@ -1613,9 +1787,14 @@ var ArchiveAssetSource = class _ArchiveAssetSource extends AssetSource {
1613
1787
  };
1614
1788
 
1615
1789
  // src/assets/AssetLoader.ts
1616
- var import_ts_deepmerge3 = __toESM(require_dist());
1617
1790
  var p5 = prefix("AssetLoader");
1618
- var _AssetLoader = class _AssetLoader {
1791
+ var AssetLoader = class {
1792
+ static {
1793
+ this.ROOT = DEFAULT_ROOT;
1794
+ }
1795
+ static {
1796
+ this._SOURCES = [];
1797
+ }
1619
1798
  static addSource(key, source, override = true) {
1620
1799
  if (override) {
1621
1800
  const existing = this.removeSource(key);
@@ -1636,8 +1815,11 @@ var _AssetLoader = class _AssetLoader {
1636
1815
  }
1637
1816
  return void 0;
1638
1817
  }
1818
+ static {
1819
+ this.addSource("mcassets-fallback", new HostedAssetSource("https://raw.githubusercontent.com/InventivetalentDev/minerender-fallback-assets/master", { retryDefaults: false }));
1820
+ this.addSource("mcassets", new HostedAssetSource(DEFAULT_ROOT, { retryDefaults: false }));
1821
+ }
1639
1822
  static async getAll(key, parser) {
1640
- console.log(this._SOURCES);
1641
1823
  let promises = [];
1642
1824
  for (const source of this._SOURCES) {
1643
1825
  promises.push(source.source.get(key, parser));
@@ -1646,31 +1828,18 @@ var _AssetLoader = class _AssetLoader {
1646
1828
  return results.filter((r) => r != void 0);
1647
1829
  });
1648
1830
  }
1831
+ /** Returns the first defined result in source-priority order, without merging assets. */
1649
1832
  static async get(key, parser) {
1650
- console.log(this._SOURCES);
1651
- let promises = [];
1652
- for (const source of this._SOURCES) {
1653
- promises.push(source.source.get(key, parser));
1654
- }
1655
- return Promise.all(promises).then((results) => {
1656
- const fallback = results[results.length - 1];
1657
- for (const result of results) {
1658
- if (result) {
1659
- if (fallback) {
1660
- return (0, import_ts_deepmerge3.default)({}, fallback, result);
1661
- }
1662
- return result;
1663
- }
1833
+ const sources = [...this._SOURCES];
1834
+ for (const source of sources) {
1835
+ const result = await source.source.get(key, parser);
1836
+ if (result !== void 0) {
1837
+ return result;
1664
1838
  }
1665
- return void 0;
1666
- });
1839
+ }
1840
+ return void 0;
1667
1841
  }
1668
1842
  };
1669
- _AssetLoader.ROOT = DEFAULT_ROOT;
1670
- _AssetLoader._SOURCES = [];
1671
- _AssetLoader.addSource("mcassets-fallback", new HostedAssetSource("https://raw.githubusercontent.com/InventivetalentDev/minerender-fallback-assets/master"));
1672
- _AssetLoader.addSource("mcassets", new HostedAssetSource(DEFAULT_ROOT));
1673
- var AssetLoader = _AssetLoader;
1674
1843
 
1675
1844
  // src/assets/ModelTextures.ts
1676
1845
  var ModelTextures = class {
@@ -1678,11 +1847,21 @@ var ModelTextures = class {
1678
1847
  return this._persistentMetaCache ??= PersistentCache.open("minerender-texturemeta");
1679
1848
  }
1680
1849
  static async get(key) {
1681
- const asset = await this.preload(key);
1682
- if (asset) {
1683
- return ImageLoader.infoToCanvasData(asset);
1850
+ const keyStr = key.serialize();
1851
+ const pending = this.preload(key);
1852
+ const cached = Caching.textureAssetCache.getIfPresent(keyStr);
1853
+ try {
1854
+ const asset = await pending;
1855
+ if (asset) {
1856
+ return await ImageLoader.infoToCanvasData(asset);
1857
+ }
1858
+ return void 0;
1859
+ } catch (err) {
1860
+ if (cached && Caching.textureAssetCache.getIfPresent(keyStr) === cached) {
1861
+ Caching.textureAssetCache.invalidate(keyStr);
1862
+ }
1863
+ throw err;
1684
1864
  }
1685
- return void 0;
1686
1865
  }
1687
1866
  static async preload(key) {
1688
1867
  const keyStr = key.serialize();
@@ -1756,7 +1935,28 @@ var CanvasImage = class {
1756
1935
  };
1757
1936
 
1758
1937
  // src/Ticker.ts
1759
- var _Ticker = class _Ticker {
1938
+ var Ticker = class _Ticker {
1939
+ static {
1940
+ this.TPS = 20;
1941
+ }
1942
+ static {
1943
+ this.counter = 0;
1944
+ }
1945
+ static {
1946
+ this._tickers = /* @__PURE__ */ new Map();
1947
+ }
1948
+ static {
1949
+ this.oneSecondTps = 0;
1950
+ }
1951
+ static {
1952
+ this.oneSecondTicks = 0;
1953
+ }
1954
+ static {
1955
+ this.fiveSecondTps = 0;
1956
+ }
1957
+ static {
1958
+ this.fiveSecondTicks = 0;
1959
+ }
1760
1960
  static schedule(fn, ms) {
1761
1961
  const handle = setInterval(fn, ms);
1762
1962
  const unref = handle.unref;
@@ -1818,14 +2018,6 @@ var _Ticker = class _Ticker {
1818
2018
  this._tickers.clear();
1819
2019
  }
1820
2020
  };
1821
- _Ticker.TPS = 20;
1822
- _Ticker.counter = 0;
1823
- _Ticker._tickers = /* @__PURE__ */ new Map();
1824
- _Ticker.oneSecondTps = 0;
1825
- _Ticker.oneSecondTicks = 0;
1826
- _Ticker.fiveSecondTps = 0;
1827
- _Ticker.fiveSecondTicks = 0;
1828
- var Ticker = _Ticker;
1829
2021
 
1830
2022
  // src/texture/TextureAtlas.ts
1831
2023
  var TextureAtlas = class {
@@ -1851,6 +2043,9 @@ var TextureAtlas = class {
1851
2043
 
1852
2044
  // src/model/ModelGenerator.ts
1853
2045
  var ModelGenerator = class {
2046
+ static {
2047
+ this.ITEM_LAYERS = ["layer0", "layer1", "layer2", "layer3", "layer4"];
2048
+ }
1854
2049
  static generateItemModel(imageData, layer) {
1855
2050
  const mainElement = {
1856
2051
  from: [0, 0, 7.5],
@@ -1870,7 +2065,6 @@ var ModelGenerator = class {
1870
2065
  return [mainElement];
1871
2066
  }
1872
2067
  };
1873
- ModelGenerator.ITEM_LAYERS = ["layer0", "layer1", "layer2", "layer3", "layer4"];
1874
2068
 
1875
2069
  // src/UVMapper.ts
1876
2070
  var p6 = prefix("UVMapper");
@@ -2046,7 +2240,6 @@ var UVMapper = class {
2046
2240
  return [tl, tr, bl, br];
2047
2241
  }
2048
2242
  static async createAtlas(originalModel) {
2049
- var _a;
2050
2243
  const textureMap = {};
2051
2244
  const metaMap = {};
2052
2245
  const model = { ...originalModel };
@@ -2126,16 +2319,15 @@ var UVMapper = class {
2126
2319
  if (texture.animated) {
2127
2320
  hasAnimation = true;
2128
2321
  const meta = metaMap[textureKey];
2129
- const frameTime = ((_a = meta == null ? void 0 : meta.animation) == null ? void 0 : _a.frametime) ?? 1;
2322
+ const frameTime = meta?.animation?.frametime ?? 1;
2130
2323
  console.log(meta);
2131
2324
  console.log(frameTime);
2132
2325
  let t = 0;
2133
2326
  let f = 0;
2134
2327
  animatorFunctions[textureKey] = () => {
2135
- var _a2;
2136
2328
  if (t++ >= frameTime) {
2137
2329
  t = 0;
2138
- const frames = (_a2 = meta == null ? void 0 : meta.animation) == null ? void 0 : _a2.frames;
2330
+ const frames = meta?.animation?.frames;
2139
2331
  const frame = frames ? frames[f] : f;
2140
2332
  image.putData(texture.getFrameSectionData(frame), x, y, 0, 0, maxWidth, maxWidth);
2141
2333
  f++;
@@ -2362,17 +2554,20 @@ function shutdown() {
2362
2554
  }
2363
2555
 
2364
2556
  // src/assets/Entities.ts
2365
- import { Memoize as Memoize3 } from "typescript-memoize";
2366
2557
  var Entities = class {
2367
2558
  static async getBlockEntityModels() {
2368
2559
  const key = AssetKey.parse("models", "minerender:blockEntityModels");
2369
2560
  console.log(key);
2370
- return AssetLoader.get(key, "json" /* JSON */);
2561
+ return Caching.entityModelsCache.get(key.serialize(), () => {
2562
+ return AssetLoader.get(key, "json" /* JSON */);
2563
+ });
2371
2564
  }
2372
2565
  static async getEntityModels() {
2373
2566
  const key = AssetKey.parse("models", "minerender:entityModels");
2374
2567
  console.log(key);
2375
- return AssetLoader.get(key, "json" /* JSON */);
2568
+ return Caching.entityModelsCache.get(key.serialize(), () => {
2569
+ return AssetLoader.get(key, "json" /* JSON */);
2570
+ });
2376
2571
  }
2377
2572
  // BlockEntity names are hardcoded
2378
2573
  static async getBlockList() {
@@ -2418,12 +2613,6 @@ var Entities = class {
2418
2613
  };
2419
2614
  }
2420
2615
  };
2421
- __decorateClass([
2422
- Memoize3()
2423
- ], Entities, "getBlockEntityModels", 1);
2424
- __decorateClass([
2425
- Memoize3()
2426
- ], Entities, "getEntityModels", 1);
2427
2616
  var EntityModels = class {
2428
2617
  };
2429
2618
  var BlockEntityModels = class {
@@ -2487,18 +2676,26 @@ var MineRenderError = class _MineRenderError extends Error {
2487
2676
  };
2488
2677
 
2489
2678
  // src/renderer/SceneObject.ts
2490
- var import_ts_deepmerge4 = __toESM(require_dist());
2679
+ var import_ts_deepmerge3 = __toESM(require_dist());
2491
2680
  var p7 = prefix("SceneObject");
2492
- var _SceneObject = class _SceneObject extends Object3D2 {
2681
+ var SceneObject = class _SceneObject extends Object3D2 {
2493
2682
  constructor(options) {
2494
2683
  super();
2495
2684
  this.isSceneObject = true;
2496
2685
  this.materialCallbacks = {};
2497
2686
  this._isInstanced = false;
2498
2687
  this._instanceCounter = 0;
2499
- this.options = (0, import_ts_deepmerge4.default)({}, _SceneObject.DEFAULT_OPTIONS, options ?? {});
2688
+ this.options = (0, import_ts_deepmerge3.default)({}, _SceneObject.DEFAULT_OPTIONS, options ?? {});
2500
2689
  console.log("SceneObject options", this.options);
2501
2690
  }
2691
+ static {
2692
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge3.default)({}, {
2693
+ instanceMeshes: true,
2694
+ maxInstanceCount: 50,
2695
+ mergeMeshes: true,
2696
+ wireframe: false
2697
+ });
2698
+ }
2502
2699
  set scene(scene) {
2503
2700
  if (!!this._scene) throw new MineRenderError("Scene already set");
2504
2701
  this._scene = scene;
@@ -2840,34 +3037,29 @@ var _SceneObject = class _SceneObject extends Object3D2 {
2840
3037
  this.notifyDirty();
2841
3038
  }
2842
3039
  removeFromScene() {
2843
- var _a;
2844
- (_a = this._scene) == null ? void 0 : _a.remove(this);
3040
+ this._scene?.remove(this);
2845
3041
  this.notifyDirty();
2846
3042
  }
2847
3043
  //</editor-fold>
2848
3044
  };
2849
- _SceneObject.DEFAULT_OPTIONS = (0, import_ts_deepmerge4.default)({}, {
2850
- instanceMeshes: true,
2851
- maxInstanceCount: 50,
2852
- mergeMeshes: true,
2853
- wireframe: false
2854
- });
2855
- var SceneObject = _SceneObject;
2856
3045
  function isSceneObject(obj) {
2857
3046
  return obj.isSceneObject;
2858
3047
  }
2859
3048
 
2860
3049
  // src/entity/scene/EntityObject.ts
2861
- var import_ts_deepmerge5 = __toESM(require_dist());
3050
+ var import_ts_deepmerge4 = __toESM(require_dist());
2862
3051
  import { Object3D as Object3D3 } from "three";
2863
- import * as THREE2 from "three";
3052
+ import * as THREE3 from "three";
2864
3053
  var EntityObject = class extends SceneObject {
2865
3054
  constructor(entity, options) {
2866
3055
  super();
2867
3056
  this.entity = entity;
2868
3057
  this.isEntityObject = true;
2869
3058
  this.meshesCreated = false;
2870
- this.options = (0, import_ts_deepmerge5.default)({}, SceneObject.DEFAULT_OPTIONS, options ?? {});
3059
+ this.options = (0, import_ts_deepmerge4.default)({}, SceneObject.DEFAULT_OPTIONS, options ?? {});
3060
+ }
3061
+ static {
3062
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge4.default)({}, SceneObject.DEFAULT_OPTIONS, {});
2871
3063
  }
2872
3064
  async init() {
2873
3065
  this.createMeshes();
@@ -2876,17 +3068,19 @@ var EntityObject = class extends SceneObject {
2876
3068
  dispose() {
2877
3069
  super.dispose();
2878
3070
  }
2879
- async loadTextures() {
2880
- var _a;
2881
- this.imageData = await ModelTextures.get(new AssetKey(
2882
- ((_a = this.entity.key) == null ? void 0 : _a.namespace) ?? DEFAULT_NAMESPACE,
3071
+ get textureKey() {
3072
+ return new AssetKey(
3073
+ this.entity.key?.namespace ?? DEFAULT_NAMESPACE,
2883
3074
  this.entity.key.path,
2884
3075
  //TODO: texture may differ from entity name; most of them are in subdirectories for multiple variants etc.
2885
3076
  "textures",
2886
3077
  "entity",
2887
3078
  "assets",
2888
3079
  ".png"
2889
- ));
3080
+ );
3081
+ }
3082
+ async loadTextures() {
3083
+ this.imageData = await ModelTextures.get(this.textureKey);
2890
3084
  }
2891
3085
  //TODO: abstract this, since extracted model data can be used for entities, blocks, players
2892
3086
  createMeshes(force = false) {
@@ -2905,8 +3099,8 @@ var EntityObject = class extends SceneObject {
2905
3099
  const l = cube.maxZ - cube.minZ;
2906
3100
  const uv = texture.toUvArray(w, h, l);
2907
3101
  const cubeGeo = this._getBoxGeometryForDimensionsAndUv(w, h, l, uv).clone();
2908
- cubeGeo.applyMatrix4(new THREE2.Matrix4().makeTranslation(w / 2, h / 2, l / 2));
2909
- cubeGeo.applyMatrix4(new THREE2.Matrix4().makeTranslation(cube.minX, cube.minY, cube.minZ));
3102
+ cubeGeo.applyMatrix4(new THREE3.Matrix4().makeTranslation(w / 2, h / 2, l / 2));
3103
+ cubeGeo.applyMatrix4(new THREE3.Matrix4().makeTranslation(cube.minX, cube.minY, cube.minZ));
2910
3104
  applyModelPartRotation(part, cubeGeo);
2911
3105
  const mesh = this.createMesh(partName, cubeGeo, mat);
2912
3106
  partAnchor.add(mesh);
@@ -2919,24 +3113,25 @@ var EntityObject = class extends SceneObject {
2919
3113
  this.meshesCreated = true;
2920
3114
  }
2921
3115
  async applyTextures() {
2922
- var _a;
2923
- const textureAsset = await ModelTextures.preload(new AssetKey(
2924
- ((_a = this.entity.key) == null ? void 0 : _a.namespace) ?? DEFAULT_NAMESPACE,
2925
- this.entity.key.path,
2926
- "textures",
2927
- "entity",
2928
- "assets",
2929
- ".png"
2930
- ));
2931
- if (textureAsset) {
2932
- let mat = Materials.getImage({ texture: { src: textureAsset.src } });
2933
- this.iterateAllMeshes((mesh) => {
2934
- mesh.material = mat;
2935
- });
2936
- }
3116
+ const assetKeyStr = this.textureKey.serialize();
3117
+ const keyStr = `entity:${assetKeyStr}`;
3118
+ let mat = Caching.materialCache.getIfPresent(keyStr);
3119
+ if (!mat) {
3120
+ const pending = this.loadTextures();
3121
+ const cachedAsset = Caching.textureAssetCache.getIfPresent(assetKeyStr);
3122
+ await pending;
3123
+ if (!this.imageData) return;
3124
+ const canvas = this.imageData.data.canvas;
3125
+ const createMaterial = () => Materials.createBasicCanvasMaterial(canvas);
3126
+ mat = cachedAsset && Caching.textureAssetCache.getIfPresent(assetKeyStr) === cachedAsset ? Caching.materialCache.get(keyStr, createMaterial) : createMaterial();
3127
+ this.imageData = void 0;
3128
+ }
3129
+ this.iterateAllMeshes((mesh) => {
3130
+ mesh.material = mat;
3131
+ });
3132
+ this.notifyDirty();
2937
3133
  }
2938
3134
  };
2939
- EntityObject.DEFAULT_OPTIONS = (0, import_ts_deepmerge5.default)({}, SceneObject.DEFAULT_OPTIONS, {});
2940
3135
  function isEntityObject(obj) {
2941
3136
  return obj.isEntityObject;
2942
3137
  }
@@ -2977,8 +3172,7 @@ var SceneInspector = class {
2977
3172
  return out;
2978
3173
  }
2979
3174
  onClick(event) {
2980
- var _a;
2981
- if (((_a = event.target) == null ? void 0 : _a.nodeName) !== "CANVAS") return;
3175
+ if (event.target?.nodeName !== "CANVAS") return;
2982
3176
  if (!event.ctrlKey) return;
2983
3177
  setTimeout(() => {
2984
3178
  this.mouse.x = event.clientX / window.innerWidth * 2 - 1;
@@ -3938,26 +4132,28 @@ function computeMorphedAttributes(object) {
3938
4132
  }
3939
4133
 
3940
4134
  // src/model/scene/ModelObject.ts
3941
- var import_ts_deepmerge6 = __toESM(require_dist());
4135
+ var import_ts_deepmerge5 = __toESM(require_dist());
3942
4136
  var p10 = prefix("ModelObject");
3943
- var _ModelObject = class _ModelObject extends SceneObject {
4137
+ var ModelObject = class _ModelObject extends SceneObject {
3944
4138
  constructor(originalModel, options) {
3945
4139
  super(options);
3946
4140
  this.originalModel = originalModel;
3947
4141
  this.isModelObject = true;
3948
4142
  this.meshesCreated = false;
3949
- this.options = (0, import_ts_deepmerge6.default)({}, _ModelObject.DEFAULT_OPTIONS, options ?? {});
4143
+ this.options = (0, import_ts_deepmerge5.default)({}, _ModelObject.DEFAULT_OPTIONS, options ?? {});
3950
4144
  console.log("ModelObject options", this.options);
3951
4145
  }
4146
+ static {
4147
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge5.default)({}, SceneObject.DEFAULT_OPTIONS, {});
4148
+ }
3952
4149
  async init() {
3953
4150
  await this.loadTextures();
3954
4151
  this.createMeshes();
3955
4152
  this.applyTextures();
3956
4153
  }
3957
4154
  dispose() {
3958
- var _a;
3959
4155
  super.dispose();
3960
- (_a = this.atlas) == null ? void 0 : _a.dispose();
4156
+ this.atlas?.dispose();
3961
4157
  }
3962
4158
  get textureAtlas() {
3963
4159
  return this.atlas;
@@ -3967,13 +4163,12 @@ var _ModelObject = class _ModelObject extends SceneObject {
3967
4163
  this.atlas = await UVMapper.getAtlas(this.originalModel);
3968
4164
  }
3969
4165
  createMeshes(force = false) {
3970
- var _a;
3971
4166
  if (this.meshesCreated && !force) return;
3972
4167
  const mat = Materials.MISSING_TEXTURE;
3973
4168
  let allGeos = [];
3974
4169
  if (this.atlas) {
3975
4170
  if (this.atlas.model.elements) {
3976
- (_a = this.atlas.model.elements) == null ? void 0 : _a.forEach((el) => {
4171
+ this.atlas.model.elements?.forEach((el) => {
3977
4172
  const elGeo = this._getBoxGeometryFromElement(el).clone();
3978
4173
  elGeo.applyMatrix4(new Matrix45().makeTranslation((el.to[0] - el.from[0]) / 2, (el.to[1] - el.from[1]) / 2, (el.to[2] - el.from[2]) / 2));
3979
4174
  elGeo.applyMatrix4(new Matrix45().makeTranslation(el.from[0], el.from[1], el.from[2]));
@@ -4046,17 +4241,15 @@ var _ModelObject = class _ModelObject extends SceneObject {
4046
4241
  }
4047
4242
  }
4048
4243
  };
4049
- _ModelObject.DEFAULT_OPTIONS = (0, import_ts_deepmerge6.default)({}, SceneObject.DEFAULT_OPTIONS, {});
4050
- var ModelObject = _ModelObject;
4051
4244
  function isModelObject(obj) {
4052
4245
  return obj.isModelObject;
4053
4246
  }
4054
4247
 
4055
4248
  // src/model/block/scene/BlockObject.ts
4056
- var import_ts_deepmerge7 = __toESM(require_dist());
4249
+ var import_ts_deepmerge6 = __toESM(require_dist());
4057
4250
  import { Euler as Euler3, Matrix4 as Matrix46, Vector3 as Vector36 } from "three";
4058
4251
  var p11 = prefix("BlockObject");
4059
- var _BlockObject = class _BlockObject extends SceneObject {
4252
+ var BlockObject = class _BlockObject extends SceneObject {
4060
4253
  constructor(blockState, options) {
4061
4254
  super(options);
4062
4255
  this.blockState = blockState;
@@ -4069,7 +4262,12 @@ var _BlockObject = class _BlockObject extends SceneObject {
4069
4262
  this._instanceModel = [];
4070
4263
  this._variants = [];
4071
4264
  this._models = [];
4072
- this.options = (0, import_ts_deepmerge7.default)({}, _BlockObject.DEFAULT_OPTIONS, options ?? {});
4265
+ this.options = (0, import_ts_deepmerge6.default)({}, _BlockObject.DEFAULT_OPTIONS, options ?? {});
4266
+ }
4267
+ static {
4268
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge6.default)({}, ModelObject.DEFAULT_OPTIONS, {
4269
+ applyDefaultState: true
4270
+ });
4073
4271
  }
4074
4272
  async init() {
4075
4273
  if (this.options.applyDefaultState) {
@@ -4358,10 +4556,6 @@ var _BlockObject = class _BlockObject extends SceneObject {
4358
4556
  //TODO: should override rotation + scale methods
4359
4557
  //TODO
4360
4558
  };
4361
- _BlockObject.DEFAULT_OPTIONS = (0, import_ts_deepmerge7.default)({}, ModelObject.DEFAULT_OPTIONS, {
4362
- applyDefaultState: true
4363
- });
4364
- var BlockObject = _BlockObject;
4365
4559
  function isBlockObject(obj) {
4366
4560
  return obj.isBlockObject;
4367
4561
  }
@@ -4386,11 +4580,10 @@ var StructureParser = class {
4386
4580
  throw new MineRenderError("Structure does not have palette(s)");
4387
4581
  }
4388
4582
  const blocks = nbt.blocks.value.value.map((block) => {
4389
- var _a;
4390
4583
  const state = palette.value.value[block.state.value];
4391
4584
  if (state.Name.value === "minecraft:air") return void 0;
4392
4585
  const props = {};
4393
- for (let k in (_a = state.Properties) == null ? void 0 : _a.value) {
4586
+ for (let k in state.Properties?.value) {
4394
4587
  props[k] = state.Properties.value[k].value;
4395
4588
  }
4396
4589
  return {
@@ -4409,7 +4602,7 @@ var StructureParser = class {
4409
4602
 
4410
4603
  // src/renderer/MineRenderScene.ts
4411
4604
  import { Scene as Scene2 } from "three";
4412
- var import_ts_deepmerge9 = __toESM(require_dist());
4605
+ var import_ts_deepmerge8 = __toESM(require_dist());
4413
4606
 
4414
4607
  // src/skin/SkinPart.ts
4415
4608
  var SkinPart = /* @__PURE__ */ ((SkinPart2) => {
@@ -5140,7 +5333,7 @@ var slimSkinGeometries = {
5140
5333
  };
5141
5334
 
5142
5335
  // src/skin/scene/SkinObject.ts
5143
- var import_ts_deepmerge8 = __toESM(require_dist());
5336
+ var import_ts_deepmerge7 = __toESM(require_dist());
5144
5337
  var SkinObject = class extends SceneObject {
5145
5338
  constructor(options) {
5146
5339
  super();
@@ -5148,7 +5341,7 @@ var SkinObject = class extends SceneObject {
5148
5341
  this.legacy = false;
5149
5342
  this.skinTextureWidth = 64;
5150
5343
  this.skinTextureHeight = 64;
5151
- this.options = (0, import_ts_deepmerge8.default)({}, SceneObject.DEFAULT_OPTIONS, options ?? {});
5344
+ this.options = (0, import_ts_deepmerge7.default)({}, SceneObject.DEFAULT_OPTIONS, options ?? {});
5152
5345
  }
5153
5346
  async init() {
5154
5347
  this.createMeshes();
@@ -5252,33 +5445,66 @@ var SkinObject = class extends SceneObject {
5252
5445
  };
5253
5446
 
5254
5447
  // src/renderer/MineRenderScene.ts
5255
- var _MineRenderScene = class _MineRenderScene extends Scene2 {
5448
+ var MineRenderScene = class _MineRenderScene extends Scene2 {
5256
5449
  constructor(options) {
5257
5450
  super();
5258
5451
  this.isMineRenderScene = true;
5259
5452
  this.stats = new SceneStats();
5260
5453
  this.instanceManager = new InstanceManager();
5261
5454
  this.dirty = true;
5262
- this.options = (0, import_ts_deepmerge9.default)({}, _MineRenderScene.DEFAULT_OPTIONS, options ?? {});
5455
+ this.observedObjects = /* @__PURE__ */ new Set();
5456
+ this.onObjectChange = (event) => {
5457
+ if (event.target?.parent === this) {
5458
+ this.dirty = true;
5459
+ }
5460
+ };
5461
+ this.options = (0, import_ts_deepmerge8.default)({}, _MineRenderScene.DEFAULT_OPTIONS, options ?? {});
5263
5462
  }
5264
- add(...object) {
5265
- this.dirty = true;
5266
- this.stats.objectCount += object.length;
5267
- for (let obj of object) {
5268
- if (isSceneObject(obj)) {
5269
- this.stats.sceneObjectCount++;
5463
+ static {
5464
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge8.default)({}, {});
5465
+ }
5466
+ add(...objects) {
5467
+ for (const object of objects) {
5468
+ this.dirty = true;
5469
+ try {
5470
+ super.add(object);
5471
+ } finally {
5472
+ if (object?.isObject3D && object !== this) {
5473
+ this.updateObjectRegistration(object, object.parent === this);
5474
+ }
5270
5475
  }
5271
- obj.addEventListener("change", (event) => {
5272
- this.dirty = true;
5273
- });
5274
5476
  }
5275
- return super.add(...object);
5477
+ return this;
5276
5478
  }
5277
- remove(...object) {
5278
- this.dirty = true;
5279
- return super.remove(...object);
5479
+ remove(...objects) {
5480
+ for (const object of objects) {
5481
+ if (!this.children.includes(object)) continue;
5482
+ this.dirty = true;
5483
+ this.updateObjectRegistration(object, false);
5484
+ try {
5485
+ super.remove(object);
5486
+ } finally {
5487
+ this.updateObjectRegistration(object, object.parent === this);
5488
+ }
5489
+ }
5490
+ return this;
5280
5491
  }
5281
- async initAndAdd(...object) {
5492
+ updateObjectRegistration(object, attached) {
5493
+ if (this.observedObjects.has(object) === attached) return;
5494
+ if (attached) {
5495
+ this.observedObjects.add(object);
5496
+ object.addEventListener("change", this.onObjectChange);
5497
+ } else {
5498
+ this.observedObjects.delete(object);
5499
+ object.removeEventListener("change", this.onObjectChange);
5500
+ }
5501
+ const change = attached ? 1 : -1;
5502
+ this.stats.objectCount += change;
5503
+ if (isSceneObject(object)) {
5504
+ this.stats.sceneObjectCount += change;
5505
+ }
5506
+ }
5507
+ async initAndAdd(...object) {
5282
5508
  this.dirty = true;
5283
5509
  for (let obj of object) {
5284
5510
  await obj.init();
@@ -5286,13 +5512,12 @@ var _MineRenderScene = class _MineRenderScene extends Scene2 {
5286
5512
  return this.add(...object);
5287
5513
  }
5288
5514
  async addSceneObject(asset, objectSupplier, _options, parent = this) {
5289
- var _a, _b;
5290
5515
  console.log("addSceneObject", asset);
5291
5516
  console.log("parent", parent);
5292
5517
  console.log(_options);
5293
5518
  this.dirty = true;
5294
5519
  const obj = await objectSupplier();
5295
- if (((_a = obj == null ? void 0 : obj.options) == null ? void 0 : _a.instanceMeshes) && asset.key && ((_b = asset.key) == null ? void 0 : _b.assetType) === "models") {
5520
+ if (obj?.options?.instanceMeshes && asset.key && asset.key?.assetType === "models") {
5296
5521
  console.log("instanceMeshes + key");
5297
5522
  const key = asset.key.serialize();
5298
5523
  return this.instanceManager.getOrCreate(key, async () => {
@@ -5332,734 +5557,342 @@ var _MineRenderScene = class _MineRenderScene extends Scene2 {
5332
5557
  return this.addSceneObject(entity, () => new EntityObject(entity, options), options, parent);
5333
5558
  }
5334
5559
  };
5335
- _MineRenderScene.DEFAULT_OPTIONS = (0, import_ts_deepmerge9.default)({}, {});
5336
- var MineRenderScene = _MineRenderScene;
5337
5560
  function isMineRenderScene(obj) {
5338
5561
  return obj.isMineRenderScene;
5339
5562
  }
5340
5563
 
5341
5564
  // src/renderer/Renderer.ts
5342
- import { AxesHelper as AxesHelper3, GridHelper, LinearEncoding, OrthographicCamera, PCFSoftShadowMap, PerspectiveCamera, Vector3 as Vector37, WebGLRenderer } from "three";
5343
- var import_ts_deepmerge10 = __toESM(require_dist());
5565
+ import { AxesHelper as AxesHelper3, GridHelper, OrthographicCamera, PCFSoftShadowMap, PerspectiveCamera, SRGBColorSpace as SRGBColorSpace3, Vector3 as Vector38, WebGLRenderer } from "three";
5566
+ var import_ts_deepmerge9 = __toESM(require_dist());
5344
5567
  import Stats from "stats.js";
5345
5568
  import { EffectComposer, RenderPass } from "postprocessing";
5346
- var _Renderer = class _Renderer {
5347
- constructor(options) {
5348
- this._dirty = true;
5349
- this._animationTimer = void 0;
5350
- this._animationFrame = void 0;
5351
- this._resizeListener = void 0;
5352
- this.options = (0, import_ts_deepmerge10.default)({}, _Renderer.DEFAULT_OPTIONS, options ?? {});
5353
- this._animationLoop = this.animate.bind(this);
5354
- this._fpsTimer = this.options.render.fpsLimit > 0 ? 1e3 / this.options.render.fpsLimit : void 0;
5355
- this._scene = this.createScene();
5356
- this._camera = this.createCamera();
5357
- this._renderer = this.createRenderer();
5358
- this._composer = this.createComposer();
5359
- if (this.options.render.stats) {
5360
- this._stats = new Stats();
5361
- document.body.appendChild(this._stats.dom);
5569
+
5570
+ // src/three/OrbitControls.js
5571
+ import {
5572
+ EventDispatcher,
5573
+ MOUSE,
5574
+ Quaternion as Quaternion3,
5575
+ Spherical,
5576
+ TOUCH,
5577
+ Vector2 as Vector23,
5578
+ Vector3 as Vector37
5579
+ } from "three";
5580
+ var _changeEvent = { type: "change" };
5581
+ var _startEvent = { type: "start" };
5582
+ var _endEvent = { type: "end" };
5583
+ var OrbitControls = class extends EventDispatcher {
5584
+ constructor(object, domElement) {
5585
+ super();
5586
+ if (domElement === void 0) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
5587
+ if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
5588
+ this.object = object;
5589
+ this.domElement = domElement;
5590
+ this.domElement.style.touchAction = "none";
5591
+ this.enabled = true;
5592
+ this.target = new Vector37();
5593
+ this.minDistance = 0;
5594
+ this.maxDistance = Infinity;
5595
+ this.minZoom = 0;
5596
+ this.maxZoom = Infinity;
5597
+ this.minPolarAngle = 0;
5598
+ this.maxPolarAngle = Math.PI;
5599
+ this.minAzimuthAngle = -Infinity;
5600
+ this.maxAzimuthAngle = Infinity;
5601
+ this.enableDamping = false;
5602
+ this.dampingFactor = 0.05;
5603
+ this.enableZoom = true;
5604
+ this.zoomSpeed = 1;
5605
+ this.enableRotate = true;
5606
+ this.rotateSpeed = 1;
5607
+ this.enablePan = true;
5608
+ this.panSpeed = 1;
5609
+ this.screenSpacePanning = true;
5610
+ this.keyPanSpeed = 7;
5611
+ this.autoRotate = false;
5612
+ this.autoRotateSpeed = 2;
5613
+ this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" };
5614
+ this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
5615
+ this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
5616
+ this.target0 = this.target.clone();
5617
+ this.position0 = this.object.position.clone();
5618
+ this.zoom0 = this.object.zoom;
5619
+ this._domElementKeyEvents = null;
5620
+ this.getPolarAngle = function() {
5621
+ return spherical.phi;
5622
+ };
5623
+ this.getAzimuthalAngle = function() {
5624
+ return spherical.theta;
5625
+ };
5626
+ this.getDistance = function() {
5627
+ return this.object.position.distanceTo(this.target);
5628
+ };
5629
+ this.saveState = function() {
5630
+ scope.target0.copy(scope.target);
5631
+ scope.position0.copy(scope.object.position);
5632
+ scope.zoom0 = scope.object.zoom;
5633
+ };
5634
+ this.reset = function() {
5635
+ scope.target.copy(scope.target0);
5636
+ scope.object.position.copy(scope.position0);
5637
+ scope.object.zoom = scope.zoom0;
5638
+ scope.object.updateProjectionMatrix();
5639
+ scope.dispatchEvent(_changeEvent);
5640
+ scope.update();
5641
+ state = STATE.NONE;
5642
+ };
5643
+ this.update = function() {
5644
+ const offset = new Vector37();
5645
+ const quat = new Quaternion3().setFromUnitVectors(object.up, new Vector37(0, 1, 0));
5646
+ const quatInverse = quat.clone().invert();
5647
+ const lastPosition = new Vector37();
5648
+ const lastQuaternion = new Quaternion3();
5649
+ const twoPI = 2 * Math.PI;
5650
+ return function update() {
5651
+ const position = scope.object.position;
5652
+ offset.copy(position).sub(scope.target);
5653
+ offset.applyQuaternion(quat);
5654
+ spherical.setFromVector3(offset);
5655
+ if (scope.autoRotate && state === STATE.NONE) {
5656
+ rotateLeft(getAutoRotationAngle());
5657
+ }
5658
+ if (scope.enableDamping) {
5659
+ spherical.theta += sphericalDelta.theta * scope.dampingFactor;
5660
+ spherical.phi += sphericalDelta.phi * scope.dampingFactor;
5661
+ } else {
5662
+ spherical.theta += sphericalDelta.theta;
5663
+ spherical.phi += sphericalDelta.phi;
5664
+ }
5665
+ let min = scope.minAzimuthAngle;
5666
+ let max = scope.maxAzimuthAngle;
5667
+ if (isFinite(min) && isFinite(max)) {
5668
+ if (min < -Math.PI) min += twoPI;
5669
+ else if (min > Math.PI) min -= twoPI;
5670
+ if (max < -Math.PI) max += twoPI;
5671
+ else if (max > Math.PI) max -= twoPI;
5672
+ if (min <= max) {
5673
+ spherical.theta = Math.max(min, Math.min(max, spherical.theta));
5674
+ } else {
5675
+ spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
5676
+ }
5677
+ }
5678
+ spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
5679
+ spherical.makeSafe();
5680
+ spherical.radius *= scale;
5681
+ spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius));
5682
+ if (scope.enableDamping === true) {
5683
+ scope.target.addScaledVector(panOffset, scope.dampingFactor);
5684
+ } else {
5685
+ scope.target.add(panOffset);
5686
+ }
5687
+ offset.setFromSpherical(spherical);
5688
+ offset.applyQuaternion(quatInverse);
5689
+ position.copy(scope.target).add(offset);
5690
+ scope.object.lookAt(scope.target);
5691
+ if (scope.enableDamping === true) {
5692
+ sphericalDelta.theta *= 1 - scope.dampingFactor;
5693
+ sphericalDelta.phi *= 1 - scope.dampingFactor;
5694
+ panOffset.multiplyScalar(1 - scope.dampingFactor);
5695
+ } else {
5696
+ sphericalDelta.set(0, 0, 0);
5697
+ panOffset.set(0, 0, 0);
5698
+ }
5699
+ scale = 1;
5700
+ if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
5701
+ scope.dispatchEvent(_changeEvent);
5702
+ lastPosition.copy(scope.object.position);
5703
+ lastQuaternion.copy(scope.object.quaternion);
5704
+ zoomChanged = false;
5705
+ return true;
5706
+ }
5707
+ return false;
5708
+ };
5709
+ }();
5710
+ this.dispose = function() {
5711
+ scope.domElement.removeEventListener("contextmenu", onContextMenu);
5712
+ scope.domElement.removeEventListener("pointerdown", onPointerDown);
5713
+ scope.domElement.removeEventListener("pointercancel", onPointerCancel);
5714
+ scope.domElement.removeEventListener("wheel", onMouseWheel);
5715
+ scope.domElement.removeEventListener("pointermove", onPointerMove);
5716
+ scope.domElement.removeEventListener("pointerup", onPointerUp);
5717
+ if (scope._domElementKeyEvents !== null) {
5718
+ scope._domElementKeyEvents.removeEventListener("keydown", onKeyDown);
5719
+ }
5720
+ };
5721
+ const scope = this;
5722
+ const STATE = {
5723
+ NONE: -1,
5724
+ ROTATE: 0,
5725
+ DOLLY: 1,
5726
+ PAN: 2,
5727
+ TOUCH_ROTATE: 3,
5728
+ TOUCH_PAN: 4,
5729
+ TOUCH_DOLLY_PAN: 5,
5730
+ TOUCH_DOLLY_ROTATE: 6
5731
+ };
5732
+ let state = STATE.NONE;
5733
+ const EPS = 1e-6;
5734
+ const spherical = new Spherical();
5735
+ const sphericalDelta = new Spherical();
5736
+ let scale = 1;
5737
+ const panOffset = new Vector37();
5738
+ let zoomChanged = false;
5739
+ const rotateStart = new Vector23();
5740
+ const rotateEnd = new Vector23();
5741
+ const rotateDelta = new Vector23();
5742
+ const panStart = new Vector23();
5743
+ const panEnd = new Vector23();
5744
+ const panDelta = new Vector23();
5745
+ const dollyStart = new Vector23();
5746
+ const dollyEnd = new Vector23();
5747
+ const dollyDelta = new Vector23();
5748
+ const pointers = [];
5749
+ const pointerPositions = {};
5750
+ function getAutoRotationAngle() {
5751
+ return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
5362
5752
  }
5363
- this.init();
5364
- }
5365
- //<editor-fold desc="INIT">
5366
- createScene() {
5367
- return new MineRenderScene();
5368
- }
5369
- createCamera() {
5370
- switch (this.options.camera.type) {
5371
- case "perspective":
5372
- default:
5373
- return new PerspectiveCamera(
5374
- this.options.camera.perspective.fov,
5375
- this.options.camera.perspective.aspect ?? this.viewWidth / this.viewHeight,
5376
- this.options.camera.near,
5377
- this.options.camera.far
5378
- );
5379
- case "orthographic":
5380
- return new OrthographicCamera(
5381
- this.options.camera.orthographic.left ?? this.viewWidth / -2,
5382
- this.options.camera.orthographic.right ?? this.viewWidth / 2,
5383
- this.options.camera.orthographic.top ?? this.viewHeight / 2,
5384
- this.options.camera.orthographic.bottom ?? this.viewHeight / -2,
5385
- this.options.camera.near,
5386
- this.options.camera.far
5387
- );
5753
+ function getZoomScale() {
5754
+ return Math.pow(0.95, scope.zoomSpeed);
5388
5755
  }
5389
- }
5390
- createRenderer() {
5391
- const renderer = new WebGLRenderer({
5392
- antialias: this.options.render.antialias,
5393
- alpha: true,
5394
- powerPreference: "high-performance",
5395
- depth: true
5396
- });
5397
- renderer.setClearColor(0, 0);
5398
- renderer.shadowMap.enabled = true;
5399
- renderer.shadowMap.type = PCFSoftShadowMap;
5400
- renderer.outputEncoding = LinearEncoding;
5401
- renderer.setSize(this.viewWidth, this.viewHeight);
5402
- return renderer;
5403
- }
5404
- createComposer() {
5405
- const composer = new EffectComposer(this.renderer);
5406
- if (!this.options.composer.enabled) return composer;
5407
- composer.setSize(this.viewWidth, this.viewHeight);
5408
- composer.addPass(new RenderPass(this.scene, this.camera));
5409
- return composer;
5410
- }
5411
- //</editor-fold>
5412
- init() {
5413
- if (typeof window["__THREE_DEVTOOLS__"] !== "undefined") {
5414
- window["__THREE_DEVTOOLS__"].dispatchEvent(new CustomEvent("observe", { detail: this.scene }));
5756
+ function rotateLeft(angle) {
5757
+ sphericalDelta.theta -= angle;
5415
5758
  }
5416
- if (this.options.debug.grid) {
5417
- const gridHelper = new GridHelper(128, 16);
5418
- this.scene.add(gridHelper);
5419
- const gridHelper2 = new GridHelper(128, 16);
5420
- gridHelper2.rotation.x = 90 * (Math.PI / 180);
5421
- this.scene.add(gridHelper2);
5422
- const gridHelper3 = new GridHelper(128, 16);
5423
- gridHelper3.rotation.z = 90 * (Math.PI / 180);
5424
- this.scene.add(gridHelper3);
5759
+ function rotateUp(angle) {
5760
+ sphericalDelta.phi -= angle;
5425
5761
  }
5426
- if (this.options.debug.axes) {
5427
- const axesHelper = new AxesHelper3(64);
5428
- this.scene.add(axesHelper);
5429
- }
5430
- if (this.options.camera.position) {
5431
- if (isVector3(this.options.camera.position)) {
5432
- this.camera.position.set(this.options.camera.position.x, this.options.camera.position.y, this.options.camera.position.z);
5433
- } else if (isTripleArray(this.options.camera.position)) {
5434
- this.camera.position.set(this.options.camera.position[0], this.options.camera.position[1], this.options.camera.position[2]);
5762
+ const panLeft = function() {
5763
+ const v = new Vector37();
5764
+ return function panLeft2(distance, objectMatrix) {
5765
+ v.setFromMatrixColumn(objectMatrix, 0);
5766
+ v.multiplyScalar(-distance);
5767
+ panOffset.add(v);
5768
+ };
5769
+ }();
5770
+ const panUp = function() {
5771
+ const v = new Vector37();
5772
+ return function panUp2(distance, objectMatrix) {
5773
+ if (scope.screenSpacePanning === true) {
5774
+ v.setFromMatrixColumn(objectMatrix, 1);
5775
+ } else {
5776
+ v.setFromMatrixColumn(objectMatrix, 0);
5777
+ v.crossVectors(scope.object.up, v);
5778
+ }
5779
+ v.multiplyScalar(distance);
5780
+ panOffset.add(v);
5781
+ };
5782
+ }();
5783
+ const pan = function() {
5784
+ const offset = new Vector37();
5785
+ return function pan2(deltaX, deltaY) {
5786
+ const element = scope.domElement;
5787
+ if (scope.object.isPerspectiveCamera) {
5788
+ const position = scope.object.position;
5789
+ offset.copy(position).sub(scope.target);
5790
+ let targetDistance = offset.length();
5791
+ targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180);
5792
+ panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
5793
+ panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
5794
+ } else if (scope.object.isOrthographicCamera) {
5795
+ panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
5796
+ panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
5797
+ } else {
5798
+ console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
5799
+ scope.enablePan = false;
5800
+ }
5801
+ };
5802
+ }();
5803
+ function dollyOut(dollyScale) {
5804
+ if (scope.object.isPerspectiveCamera) {
5805
+ scale /= dollyScale;
5806
+ } else if (scope.object.isOrthographicCamera) {
5807
+ scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
5808
+ scope.object.updateProjectionMatrix();
5809
+ zoomChanged = true;
5810
+ } else {
5811
+ console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
5812
+ scope.enableZoom = false;
5435
5813
  }
5436
5814
  }
5437
- if (this.options.camera.lookingAt) {
5438
- if (isVector3(this.options.camera.lookingAt)) {
5439
- this.camera.lookAt(this.options.camera.lookingAt);
5440
- } else if (isTripleArray(this.options.camera.lookingAt)) {
5441
- this.camera.lookAt(this.options.camera.lookingAt[0], this.options.camera.lookingAt[1], this.options.camera.lookingAt[2]);
5815
+ function dollyIn(dollyScale) {
5816
+ if (scope.object.isPerspectiveCamera) {
5817
+ scale *= dollyScale;
5818
+ } else if (scope.object.isOrthographicCamera) {
5819
+ scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
5820
+ scope.object.updateProjectionMatrix();
5821
+ zoomChanged = true;
5822
+ } else {
5823
+ console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
5824
+ scope.enableZoom = false;
5442
5825
  }
5443
5826
  }
5444
- if (this.options.render.autoResize) {
5445
- this._resizeListener = () => {
5446
- this.resize(this.viewWidth, this.viewHeight);
5447
- };
5448
- window.addEventListener("resize", this._resizeListener);
5449
- }
5450
- }
5451
- get element() {
5452
- return this._element;
5453
- }
5454
- appendTo(element) {
5455
- this._element = element;
5456
- this._element.appendChild(this.renderer.domElement);
5457
- if (this.viewWidth == 0) {
5458
- console.warn("0 element width");
5827
+ function handleMouseDownRotate(event) {
5828
+ rotateStart.set(event.clientX, event.clientY);
5459
5829
  }
5460
- if (this.viewHeight == 0) {
5461
- console.warn("0 element height");
5830
+ function handleMouseDownDolly(event) {
5831
+ dollyStart.set(event.clientX, event.clientY);
5462
5832
  }
5463
- this.resize(this.viewWidth, this.viewHeight);
5464
- }
5465
- /**
5466
- * Register an EventDispatcher which may update the scene or renderer in order to redraw the scene
5467
- */
5468
- registerEventDispatcher(dispatcher, changeEvent2 = "change") {
5469
- dispatcher.addEventListener(changeEvent2, (event) => {
5470
- this._dirty = true;
5471
- });
5472
- }
5473
- resize(width, height) {
5474
- if (isPerspectiveCamera(this.camera)) {
5475
- this.camera.aspect = width / height;
5476
- this.camera.updateProjectionMatrix();
5477
- } else if (isOrthographicCamera(this.camera)) {
5478
- this.camera.left = width / -2;
5479
- this.camera.right = width / 2;
5480
- this.camera.top = height / 2;
5481
- this.camera.bottom = height / -2;
5482
- this.camera.updateProjectionMatrix();
5833
+ function handleMouseDownPan(event) {
5834
+ panStart.set(event.clientX, event.clientY);
5483
5835
  }
5484
- this.renderer.setSize(width, height);
5485
- this.composer.setSize(width, height);
5486
- }
5487
- //<editor-fold desc="RENDER">
5488
- get dirty() {
5489
- return this._dirty || this.scene.dirty;
5490
- }
5491
- set dirty(dirty) {
5492
- this._dirty = dirty;
5493
- this.scene.dirty = dirty;
5494
- }
5495
- start() {
5496
- stop();
5497
- this.renderer.setAnimationLoop(this._animationLoop);
5498
- }
5499
- stop() {
5500
- this.renderer.setAnimationLoop(null);
5501
- if (this._animationTimer)
5502
- clearTimeout(this._animationTimer);
5503
- this._animationTimer = void 0;
5504
- if (this._animationFrame)
5505
- cancelAnimationFrame(this._animationFrame);
5506
- this._animationFrame = void 0;
5507
- }
5508
- animate(t) {
5509
- if (this._stats) {
5510
- this._stats.begin();
5836
+ function handleMouseMoveRotate(event) {
5837
+ rotateEnd.set(event.clientX, event.clientY);
5838
+ rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
5839
+ const element = scope.domElement;
5840
+ rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight);
5841
+ rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
5842
+ rotateStart.copy(rotateEnd);
5843
+ scope.update();
5511
5844
  }
5512
- if (this.dirty || this.options.render.renderAlways) {
5513
- if (this.options.composer.enabled) {
5514
- this.composer.render();
5515
- } else {
5516
- this.renderer.render(this.scene, this.camera);
5845
+ function handleMouseMoveDolly(event) {
5846
+ dollyEnd.set(event.clientX, event.clientY);
5847
+ dollyDelta.subVectors(dollyEnd, dollyStart);
5848
+ if (dollyDelta.y > 0) {
5849
+ dollyOut(getZoomScale());
5850
+ } else if (dollyDelta.y < 0) {
5851
+ dollyIn(getZoomScale());
5517
5852
  }
5853
+ dollyStart.copy(dollyEnd);
5854
+ scope.update();
5518
5855
  }
5519
- this.dirty = false;
5520
- if (this._stats) {
5521
- this._stats.end();
5856
+ function handleMouseMovePan(event) {
5857
+ panEnd.set(event.clientX, event.clientY);
5858
+ panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
5859
+ pan(panDelta.x, panDelta.y);
5860
+ panStart.copy(panEnd);
5861
+ scope.update();
5522
5862
  }
5523
- }
5524
- //</editor-fold>
5525
- toImage() {
5526
- return this.renderer.domElement.toDataURL();
5527
- }
5528
- ///
5529
- get attachedToBody() {
5530
- return this.element === document.body;
5531
- }
5532
- get viewWidth() {
5533
- var _a;
5534
- return this.attachedToBody ? window.innerWidth : ((_a = this.element) == null ? void 0 : _a.offsetWidth) || 0;
5535
- }
5536
- get viewHeight() {
5537
- var _a;
5538
- return this.attachedToBody ? window.innerHeight : ((_a = this.element) == null ? void 0 : _a.offsetHeight) || 0;
5539
- }
5540
- get scene() {
5541
- return this._scene;
5542
- }
5543
- get camera() {
5544
- return this._camera;
5545
- }
5546
- get renderer() {
5547
- return this._renderer;
5548
- }
5549
- get composer() {
5550
- return this._composer;
5551
- }
5552
- ///
5553
- };
5554
- _Renderer.DEFAULT_OPTIONS = (0, import_ts_deepmerge10.default)({}, {
5555
- camera: {
5556
- type: "perspective",
5557
- near: 1,
5558
- far: 5e3,
5559
- perspective: {
5560
- aspect: void 0,
5561
- fov: 50
5562
- },
5563
- orthographic: {
5564
- left: void 0,
5565
- right: void 0,
5566
- top: void 0,
5567
- bottom: void 0
5568
- },
5569
- position: new Vector37(50, 50, 50),
5570
- lookingAt: new Vector37(0, 0, 0)
5571
- },
5572
- render: {
5573
- fpsLimit: 60,
5574
- stats: false,
5575
- antialias: true,
5576
- shade: true,
5577
- autoResize: true,
5578
- renderAlways: false
5579
- },
5580
- composer: {
5581
- enabled: true
5582
- },
5583
- debug: {
5584
- grid: false,
5585
- axes: false
5586
- }
5587
- });
5588
- var Renderer = _Renderer;
5589
-
5590
- // src/skin/Skins.ts
5591
- var Skins = class {
5592
- //<editor-fold desc="Skins">
5593
- static async fromUuidOrUsername(uuidOrUsername) {
5594
- if (uuidOrUsername.length === 32 || uuidOrUsername.length === 36) {
5595
- return this.fromUuid(uuidOrUsername);
5863
+ function handleMouseUp() {
5596
5864
  }
5597
- return this.fromUsername(uuidOrUsername);
5598
- }
5599
- static async fromUuid(uuid) {
5600
- return this.getSkinProxySkinUrl(uuid);
5601
- }
5602
- static async fromUsername(username) {
5603
- return this.usernameToUuid(username).then((uuid) => {
5604
- if (uuid) {
5605
- return this.fromUuid(uuid);
5865
+ function handleMouseWheel(event) {
5866
+ if (event.deltaY < 0) {
5867
+ dollyIn(getZoomScale());
5868
+ } else if (event.deltaY > 0) {
5869
+ dollyOut(getZoomScale());
5606
5870
  }
5607
- return void 0;
5608
- });
5609
- }
5610
- static async fromMineSkin(mineskinId) {
5611
- return this.getMineSkin(mineskinId).then((mineskin) => {
5612
- if (mineskin) {
5613
- return mineskin["data"]["texture"]["value"]["urls"]["skins"];
5614
- }
5615
- return void 0;
5616
- });
5617
- }
5618
- //</editor-fold>
5619
- //<editor-fold desc="Capes">
5620
- static async capeFromUuidOrUsername(uuidOrUsername) {
5621
- if (uuidOrUsername.length === 32 || uuidOrUsername.length === 36) {
5622
- return this.capeFromUuid(uuidOrUsername);
5623
- }
5624
- return this.capeFromUsername(uuidOrUsername);
5625
- }
5626
- static async capeFromUuid(uuid) {
5627
- return this.getSkinProxyCapeUrl(uuid);
5628
- }
5629
- static async capeFromUsername(username) {
5630
- return this.usernameToUuid(username).then((uuid) => {
5631
- if (uuid) {
5632
- return this.capeFromUuid(uuid);
5633
- }
5634
- return void 0;
5635
- });
5636
- }
5637
- static async capeFromCapesDev(uuid, capeType = "minecraft") {
5638
- return this.getCapesDev(uuid, capeType).then((cape) => {
5639
- if (cape) {
5640
- return cape == null ? void 0 : cape.stillImageUrl;
5641
- }
5642
- return void 0;
5643
- });
5644
- }
5645
- //</editor-fold>
5646
- //<editor-fold desc="Helpers">
5647
- static async usernameToUuid(username) {
5648
- return this.usernameToUuidSkinProxy(username);
5649
- }
5650
- static async usernameToUuidSkinProxy(username) {
5651
- return Requests.genericRequest({
5652
- baseURL: "https://minecraft-skin-proxy.inventive.workers.dev",
5653
- url: "/uuid/" + username
5654
- }).then((res) => {
5655
- if (res.status === 200) {
5656
- return res.data["id"];
5657
- }
5658
- return void 0;
5659
- }).catch((err) => {
5660
- console.warn(err);
5661
- return void 0;
5662
- });
5663
- }
5664
- static async usernameToUuidMineTools(username) {
5665
- return Requests.genericRequest({
5666
- baseURL: "https://api.minetools.eu",
5667
- url: "/uuid/" + username
5668
- }).then((res) => {
5669
- if (res.status === 200) {
5670
- return res.data["id"];
5671
- }
5672
- return void 0;
5673
- }).catch((err) => {
5674
- console.warn(err);
5675
- return void 0;
5676
- });
5677
- }
5678
- static async getProfileFromMinetools(uuid) {
5679
- return Requests.genericRequest({
5680
- baseURL: "https://api.minetools.eu",
5681
- url: "/profile/" + uuid
5682
- }).then((res) => {
5683
- if (res.status === 200) {
5684
- return res.data;
5685
- }
5686
- });
5687
- }
5688
- static async getMineSkin(mineskinId) {
5689
- return Requests.genericRequest({
5690
- baseURL: "https://api.mineskin.org",
5691
- url: "/get/uuid/" + mineskinId
5692
- }).then((res) => {
5693
- if (res.status === 200) {
5694
- return res.data;
5695
- }
5696
- return void 0;
5697
- }).catch((err) => {
5698
- console.warn(err);
5699
- return void 0;
5700
- });
5701
- }
5702
- static async getCapesDev(uuid, type = "all") {
5703
- return Requests.genericRequest({
5704
- baseURL: "https://api.capes.dev",
5705
- url: "/load/" + uuid + "/" + type
5706
- }).then((res) => {
5707
- if (res.status === 200) {
5708
- return res.data;
5709
- }
5710
- return void 0;
5711
- }).catch((err) => {
5712
- console.warn(err);
5713
- return void 0;
5714
- });
5715
- }
5716
- static getCrafatarSkinUrl(uuid) {
5717
- return "https://crafatar.com/skins/" + uuid;
5718
- }
5719
- static getCrafatarCapeUrl(uuid) {
5720
- return "https://crafatar.com/capes/" + uuid;
5721
- }
5722
- static getMcHeadsSkinUrl(uuid) {
5723
- return "https://mc-heads.net/skin/" + uuid;
5724
- }
5725
- static getMineSkinPlayerSkinUrl(uuid) {
5726
- return "https://mineskin.org/skin/player/" + uuid;
5727
- }
5728
- static getSkinProxySkinUrl(uuid) {
5729
- return "https://minecraft-skin-proxy.inventive.workers.dev/skin/" + uuid;
5730
- }
5731
- static getSkinProxyCapeUrl(uuid) {
5732
- return "https://minecraft-skin-proxy.inventive.workers.dev/cape/" + uuid;
5733
- }
5734
- //</editor-fold>
5735
- };
5736
-
5737
- // src/three/OrbitControls.js
5738
- import {
5739
- EventDispatcher as EventDispatcher2,
5740
- MOUSE,
5741
- Quaternion as Quaternion3,
5742
- Spherical,
5743
- TOUCH,
5744
- Vector2 as Vector23,
5745
- Vector3 as Vector38
5746
- } from "three";
5747
- var _changeEvent = { type: "change" };
5748
- var _startEvent = { type: "start" };
5749
- var _endEvent = { type: "end" };
5750
- var OrbitControls = class extends EventDispatcher2 {
5751
- constructor(object, domElement) {
5752
- super();
5753
- if (domElement === void 0) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
5754
- if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
5755
- this.object = object;
5756
- this.domElement = domElement;
5757
- this.domElement.style.touchAction = "none";
5758
- this.enabled = true;
5759
- this.target = new Vector38();
5760
- this.minDistance = 0;
5761
- this.maxDistance = Infinity;
5762
- this.minZoom = 0;
5763
- this.maxZoom = Infinity;
5764
- this.minPolarAngle = 0;
5765
- this.maxPolarAngle = Math.PI;
5766
- this.minAzimuthAngle = -Infinity;
5767
- this.maxAzimuthAngle = Infinity;
5768
- this.enableDamping = false;
5769
- this.dampingFactor = 0.05;
5770
- this.enableZoom = true;
5771
- this.zoomSpeed = 1;
5772
- this.enableRotate = true;
5773
- this.rotateSpeed = 1;
5774
- this.enablePan = true;
5775
- this.panSpeed = 1;
5776
- this.screenSpacePanning = true;
5777
- this.keyPanSpeed = 7;
5778
- this.autoRotate = false;
5779
- this.autoRotateSpeed = 2;
5780
- this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" };
5781
- this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
5782
- this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
5783
- this.target0 = this.target.clone();
5784
- this.position0 = this.object.position.clone();
5785
- this.zoom0 = this.object.zoom;
5786
- this._domElementKeyEvents = null;
5787
- this.getPolarAngle = function() {
5788
- return spherical.phi;
5789
- };
5790
- this.getAzimuthalAngle = function() {
5791
- return spherical.theta;
5792
- };
5793
- this.getDistance = function() {
5794
- return this.object.position.distanceTo(this.target);
5795
- };
5796
- this.saveState = function() {
5797
- scope.target0.copy(scope.target);
5798
- scope.position0.copy(scope.object.position);
5799
- scope.zoom0 = scope.object.zoom;
5800
- };
5801
- this.reset = function() {
5802
- scope.target.copy(scope.target0);
5803
- scope.object.position.copy(scope.position0);
5804
- scope.object.zoom = scope.zoom0;
5805
- scope.object.updateProjectionMatrix();
5806
- scope.dispatchEvent(_changeEvent);
5807
- scope.update();
5808
- state = STATE.NONE;
5809
- };
5810
- this.update = function() {
5811
- const offset = new Vector38();
5812
- const quat = new Quaternion3().setFromUnitVectors(object.up, new Vector38(0, 1, 0));
5813
- const quatInverse = quat.clone().invert();
5814
- const lastPosition = new Vector38();
5815
- const lastQuaternion = new Quaternion3();
5816
- const twoPI = 2 * Math.PI;
5817
- return function update() {
5818
- const position = scope.object.position;
5819
- offset.copy(position).sub(scope.target);
5820
- offset.applyQuaternion(quat);
5821
- spherical.setFromVector3(offset);
5822
- if (scope.autoRotate && state === STATE.NONE) {
5823
- rotateLeft(getAutoRotationAngle());
5824
- }
5825
- if (scope.enableDamping) {
5826
- spherical.theta += sphericalDelta.theta * scope.dampingFactor;
5827
- spherical.phi += sphericalDelta.phi * scope.dampingFactor;
5828
- } else {
5829
- spherical.theta += sphericalDelta.theta;
5830
- spherical.phi += sphericalDelta.phi;
5831
- }
5832
- let min = scope.minAzimuthAngle;
5833
- let max = scope.maxAzimuthAngle;
5834
- if (isFinite(min) && isFinite(max)) {
5835
- if (min < -Math.PI) min += twoPI;
5836
- else if (min > Math.PI) min -= twoPI;
5837
- if (max < -Math.PI) max += twoPI;
5838
- else if (max > Math.PI) max -= twoPI;
5839
- if (min <= max) {
5840
- spherical.theta = Math.max(min, Math.min(max, spherical.theta));
5841
- } else {
5842
- spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
5843
- }
5844
- }
5845
- spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
5846
- spherical.makeSafe();
5847
- spherical.radius *= scale;
5848
- spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius));
5849
- if (scope.enableDamping === true) {
5850
- scope.target.addScaledVector(panOffset, scope.dampingFactor);
5851
- } else {
5852
- scope.target.add(panOffset);
5853
- }
5854
- offset.setFromSpherical(spherical);
5855
- offset.applyQuaternion(quatInverse);
5856
- position.copy(scope.target).add(offset);
5857
- scope.object.lookAt(scope.target);
5858
- if (scope.enableDamping === true) {
5859
- sphericalDelta.theta *= 1 - scope.dampingFactor;
5860
- sphericalDelta.phi *= 1 - scope.dampingFactor;
5861
- panOffset.multiplyScalar(1 - scope.dampingFactor);
5862
- } else {
5863
- sphericalDelta.set(0, 0, 0);
5864
- panOffset.set(0, 0, 0);
5865
- }
5866
- scale = 1;
5867
- if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
5868
- scope.dispatchEvent(_changeEvent);
5869
- lastPosition.copy(scope.object.position);
5870
- lastQuaternion.copy(scope.object.quaternion);
5871
- zoomChanged = false;
5872
- return true;
5873
- }
5874
- return false;
5875
- };
5876
- }();
5877
- this.dispose = function() {
5878
- scope.domElement.removeEventListener("contextmenu", onContextMenu);
5879
- scope.domElement.removeEventListener("pointerdown", onPointerDown);
5880
- scope.domElement.removeEventListener("pointercancel", onPointerCancel);
5881
- scope.domElement.removeEventListener("wheel", onMouseWheel);
5882
- scope.domElement.removeEventListener("pointermove", onPointerMove);
5883
- scope.domElement.removeEventListener("pointerup", onPointerUp);
5884
- if (scope._domElementKeyEvents !== null) {
5885
- scope._domElementKeyEvents.removeEventListener("keydown", onKeyDown);
5886
- }
5887
- };
5888
- const scope = this;
5889
- const STATE = {
5890
- NONE: -1,
5891
- ROTATE: 0,
5892
- DOLLY: 1,
5893
- PAN: 2,
5894
- TOUCH_ROTATE: 3,
5895
- TOUCH_PAN: 4,
5896
- TOUCH_DOLLY_PAN: 5,
5897
- TOUCH_DOLLY_ROTATE: 6
5898
- };
5899
- let state = STATE.NONE;
5900
- const EPS = 1e-6;
5901
- const spherical = new Spherical();
5902
- const sphericalDelta = new Spherical();
5903
- let scale = 1;
5904
- const panOffset = new Vector38();
5905
- let zoomChanged = false;
5906
- const rotateStart = new Vector23();
5907
- const rotateEnd = new Vector23();
5908
- const rotateDelta = new Vector23();
5909
- const panStart = new Vector23();
5910
- const panEnd = new Vector23();
5911
- const panDelta = new Vector23();
5912
- const dollyStart = new Vector23();
5913
- const dollyEnd = new Vector23();
5914
- const dollyDelta = new Vector23();
5915
- const pointers = [];
5916
- const pointerPositions = {};
5917
- function getAutoRotationAngle() {
5918
- return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
5919
- }
5920
- function getZoomScale() {
5921
- return Math.pow(0.95, scope.zoomSpeed);
5922
- }
5923
- function rotateLeft(angle) {
5924
- sphericalDelta.theta -= angle;
5925
- }
5926
- function rotateUp(angle) {
5927
- sphericalDelta.phi -= angle;
5928
- }
5929
- const panLeft = function() {
5930
- const v = new Vector38();
5931
- return function panLeft2(distance, objectMatrix) {
5932
- v.setFromMatrixColumn(objectMatrix, 0);
5933
- v.multiplyScalar(-distance);
5934
- panOffset.add(v);
5935
- };
5936
- }();
5937
- const panUp = function() {
5938
- const v = new Vector38();
5939
- return function panUp2(distance, objectMatrix) {
5940
- if (scope.screenSpacePanning === true) {
5941
- v.setFromMatrixColumn(objectMatrix, 1);
5942
- } else {
5943
- v.setFromMatrixColumn(objectMatrix, 0);
5944
- v.crossVectors(scope.object.up, v);
5945
- }
5946
- v.multiplyScalar(distance);
5947
- panOffset.add(v);
5948
- };
5949
- }();
5950
- const pan = function() {
5951
- const offset = new Vector38();
5952
- return function pan2(deltaX, deltaY) {
5953
- const element = scope.domElement;
5954
- if (scope.object.isPerspectiveCamera) {
5955
- const position = scope.object.position;
5956
- offset.copy(position).sub(scope.target);
5957
- let targetDistance = offset.length();
5958
- targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180);
5959
- panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
5960
- panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
5961
- } else if (scope.object.isOrthographicCamera) {
5962
- panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
5963
- panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
5964
- } else {
5965
- console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
5966
- scope.enablePan = false;
5967
- }
5968
- };
5969
- }();
5970
- function dollyOut(dollyScale) {
5971
- if (scope.object.isPerspectiveCamera) {
5972
- scale /= dollyScale;
5973
- } else if (scope.object.isOrthographicCamera) {
5974
- scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
5975
- scope.object.updateProjectionMatrix();
5976
- zoomChanged = true;
5977
- } else {
5978
- console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
5979
- scope.enableZoom = false;
5980
- }
5981
- }
5982
- function dollyIn(dollyScale) {
5983
- if (scope.object.isPerspectiveCamera) {
5984
- scale *= dollyScale;
5985
- } else if (scope.object.isOrthographicCamera) {
5986
- scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
5987
- scope.object.updateProjectionMatrix();
5988
- zoomChanged = true;
5989
- } else {
5990
- console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
5991
- scope.enableZoom = false;
5992
- }
5993
- }
5994
- function handleMouseDownRotate(event) {
5995
- rotateStart.set(event.clientX, event.clientY);
5996
- }
5997
- function handleMouseDownDolly(event) {
5998
- dollyStart.set(event.clientX, event.clientY);
5999
- }
6000
- function handleMouseDownPan(event) {
6001
- panStart.set(event.clientX, event.clientY);
6002
- }
6003
- function handleMouseMoveRotate(event) {
6004
- rotateEnd.set(event.clientX, event.clientY);
6005
- rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
6006
- const element = scope.domElement;
6007
- rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight);
6008
- rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
6009
- rotateStart.copy(rotateEnd);
6010
- scope.update();
6011
- }
6012
- function handleMouseMoveDolly(event) {
6013
- dollyEnd.set(event.clientX, event.clientY);
6014
- dollyDelta.subVectors(dollyEnd, dollyStart);
6015
- if (dollyDelta.y > 0) {
6016
- dollyOut(getZoomScale());
6017
- } else if (dollyDelta.y < 0) {
6018
- dollyIn(getZoomScale());
6019
- }
6020
- dollyStart.copy(dollyEnd);
6021
- scope.update();
6022
- }
6023
- function handleMouseMovePan(event) {
6024
- panEnd.set(event.clientX, event.clientY);
6025
- panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
6026
- pan(panDelta.x, panDelta.y);
6027
- panStart.copy(panEnd);
6028
- scope.update();
6029
- }
6030
- function handleMouseUp() {
6031
- }
6032
- function handleMouseWheel(event) {
6033
- if (event.deltaY < 0) {
6034
- dollyIn(getZoomScale());
6035
- } else if (event.deltaY > 0) {
6036
- dollyOut(getZoomScale());
6037
- }
6038
- scope.update();
6039
- }
6040
- function handleKeyDown(event) {
6041
- let needsUpdate = false;
6042
- switch (event.code) {
6043
- case scope.keys.UP:
6044
- pan(0, scope.keyPanSpeed);
6045
- needsUpdate = true;
6046
- break;
6047
- case scope.keys.BOTTOM:
6048
- pan(0, -scope.keyPanSpeed);
6049
- needsUpdate = true;
6050
- break;
6051
- case scope.keys.LEFT:
6052
- pan(scope.keyPanSpeed, 0);
6053
- needsUpdate = true;
6054
- break;
6055
- case scope.keys.RIGHT:
6056
- pan(-scope.keyPanSpeed, 0);
6057
- needsUpdate = true;
6058
- break;
6059
- }
6060
- if (needsUpdate) {
6061
- event.preventDefault();
6062
- scope.update();
5871
+ scope.update();
5872
+ }
5873
+ function handleKeyDown(event) {
5874
+ let needsUpdate = false;
5875
+ switch (event.code) {
5876
+ case scope.keys.UP:
5877
+ pan(0, scope.keyPanSpeed);
5878
+ needsUpdate = true;
5879
+ break;
5880
+ case scope.keys.BOTTOM:
5881
+ pan(0, -scope.keyPanSpeed);
5882
+ needsUpdate = true;
5883
+ break;
5884
+ case scope.keys.LEFT:
5885
+ pan(scope.keyPanSpeed, 0);
5886
+ needsUpdate = true;
5887
+ break;
5888
+ case scope.keys.RIGHT:
5889
+ pan(-scope.keyPanSpeed, 0);
5890
+ needsUpdate = true;
5891
+ break;
5892
+ }
5893
+ if (needsUpdate) {
5894
+ event.preventDefault();
5895
+ scope.update();
6063
5896
  }
6064
5897
  }
6065
5898
  function handleTouchStartRotate() {
@@ -6333,55 +6166,538 @@ var OrbitControls = class extends EventDispatcher2 {
6333
6166
  state = STATE.NONE;
6334
6167
  }
6335
6168
  }
6336
- function onTouchEnd(event) {
6337
- handleTouchEnd(event);
6338
- scope.dispatchEvent(_endEvent);
6339
- state = STATE.NONE;
6169
+ function onTouchEnd(event) {
6170
+ handleTouchEnd(event);
6171
+ scope.dispatchEvent(_endEvent);
6172
+ state = STATE.NONE;
6173
+ }
6174
+ function onContextMenu(event) {
6175
+ if (scope.enabled === false) return;
6176
+ event.preventDefault();
6177
+ }
6178
+ function addPointer(event) {
6179
+ pointers.push(event);
6180
+ }
6181
+ function removePointer(event) {
6182
+ delete pointerPositions[event.pointerId];
6183
+ for (let i = 0; i < pointers.length; i++) {
6184
+ if (pointers[i].pointerId == event.pointerId) {
6185
+ pointers.splice(i, 1);
6186
+ return;
6187
+ }
6188
+ }
6189
+ }
6190
+ function trackPointer(event) {
6191
+ let position = pointerPositions[event.pointerId];
6192
+ if (position === void 0) {
6193
+ position = new Vector23();
6194
+ pointerPositions[event.pointerId] = position;
6195
+ }
6196
+ position.set(event.pageX, event.pageY);
6197
+ }
6198
+ function getSecondPointerPosition(event) {
6199
+ const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0];
6200
+ return pointerPositions[pointer.pointerId];
6201
+ }
6202
+ scope.domElement.addEventListener("contextmenu", onContextMenu);
6203
+ scope.domElement.addEventListener("pointerdown", onPointerDown);
6204
+ scope.domElement.addEventListener("pointercancel", onPointerCancel);
6205
+ scope.domElement.addEventListener("wheel", onMouseWheel, { passive: false });
6206
+ this.update();
6207
+ }
6208
+ };
6209
+ var MapControls = class extends OrbitControls {
6210
+ constructor(object, domElement) {
6211
+ super(object, domElement);
6212
+ this.screenSpacePanning = false;
6213
+ this.mouseButtons.LEFT = MOUSE.PAN;
6214
+ this.mouseButtons.RIGHT = MOUSE.ROTATE;
6215
+ this.touches.ONE = TOUCH.PAN;
6216
+ this.touches.TWO = TOUCH.DOLLY_ROTATE;
6217
+ }
6218
+ };
6219
+
6220
+ // src/renderer/Renderer.ts
6221
+ var Renderer = class _Renderer {
6222
+ constructor(options) {
6223
+ this._dirty = true;
6224
+ this._resizeListener = void 0;
6225
+ this._disposed = false;
6226
+ this._debugHelpers = [];
6227
+ this._eventDispatchers = /* @__PURE__ */ new Map();
6228
+ this._changeListener = () => {
6229
+ this._dirty = true;
6230
+ };
6231
+ this.options = (0, import_ts_deepmerge9.default)({}, _Renderer.DEFAULT_OPTIONS, options ?? {});
6232
+ this._animationLoop = this.animate.bind(this);
6233
+ this._frameInterval = this.options.render.fpsLimit > 0 ? 1e3 / this.options.render.fpsLimit : void 0;
6234
+ this._scene = this.createScene();
6235
+ this._camera = this.createCamera();
6236
+ this._renderer = this.createRenderer();
6237
+ this._composer = this.createComposer();
6238
+ if (this.options.render.stats) {
6239
+ this._stats = new Stats();
6240
+ document.body.appendChild(this._stats.dom);
6241
+ }
6242
+ this.init();
6243
+ this._controls = this.createControls();
6244
+ }
6245
+ static {
6246
+ this.DEFAULT_OPTIONS = (0, import_ts_deepmerge9.default)({}, {
6247
+ camera: {
6248
+ type: "perspective",
6249
+ near: 1,
6250
+ far: 5e3,
6251
+ perspective: {
6252
+ aspect: void 0,
6253
+ fov: 50
6254
+ },
6255
+ orthographic: {
6256
+ left: void 0,
6257
+ right: void 0,
6258
+ top: void 0,
6259
+ bottom: void 0
6260
+ },
6261
+ position: new Vector38(50, 50, 50),
6262
+ lookingAt: new Vector38(0, 0, 0)
6263
+ },
6264
+ render: {
6265
+ fpsLimit: 60,
6266
+ stats: false,
6267
+ antialias: true,
6268
+ shade: true,
6269
+ autoResize: true,
6270
+ renderAlways: false
6271
+ },
6272
+ composer: {
6273
+ enabled: true
6274
+ },
6275
+ controls: {
6276
+ enabled: false
6277
+ },
6278
+ debug: {
6279
+ grid: false,
6280
+ axes: false
6281
+ }
6282
+ });
6283
+ }
6284
+ //<editor-fold desc="INIT">
6285
+ createScene() {
6286
+ return new MineRenderScene();
6287
+ }
6288
+ createCamera() {
6289
+ switch (this.options.camera.type) {
6290
+ case "perspective":
6291
+ default:
6292
+ return new PerspectiveCamera(
6293
+ this.options.camera.perspective.fov,
6294
+ this.options.camera.perspective.aspect ?? this.viewWidth / this.viewHeight,
6295
+ this.options.camera.near,
6296
+ this.options.camera.far
6297
+ );
6298
+ case "orthographic":
6299
+ return new OrthographicCamera(
6300
+ this.options.camera.orthographic.left ?? this.viewWidth / -2,
6301
+ this.options.camera.orthographic.right ?? this.viewWidth / 2,
6302
+ this.options.camera.orthographic.top ?? this.viewHeight / 2,
6303
+ this.options.camera.orthographic.bottom ?? this.viewHeight / -2,
6304
+ this.options.camera.near,
6305
+ this.options.camera.far
6306
+ );
6307
+ }
6308
+ }
6309
+ createRenderer() {
6310
+ const renderer = new WebGLRenderer({
6311
+ antialias: this.options.render.antialias,
6312
+ alpha: true,
6313
+ powerPreference: "high-performance",
6314
+ depth: true
6315
+ });
6316
+ renderer.setClearColor(0, 0);
6317
+ renderer.shadowMap.enabled = true;
6318
+ renderer.shadowMap.type = PCFSoftShadowMap;
6319
+ renderer.outputColorSpace = SRGBColorSpace3;
6320
+ renderer.setSize(this.viewWidth, this.viewHeight);
6321
+ return renderer;
6322
+ }
6323
+ createComposer() {
6324
+ if (!this.options.composer.enabled) return void 0;
6325
+ const composer = new EffectComposer(this.renderer);
6326
+ composer.setSize(this.viewWidth, this.viewHeight);
6327
+ composer.addPass(new RenderPass(this.scene, this.camera));
6328
+ return composer;
6329
+ }
6330
+ createControls() {
6331
+ if (!this.options.controls?.enabled) return void 0;
6332
+ const position = this.camera.position.clone();
6333
+ const controls = new OrbitControls(this.camera, this.renderer.domElement);
6334
+ this.camera.position.copy(position);
6335
+ const target = this.options.camera.lookingAt;
6336
+ if (isVector3(target)) {
6337
+ controls.target.copy(target);
6338
+ } else if (isTripleArray(target)) {
6339
+ controls.target.set(target[0], target[1], target[2]);
6340
+ }
6341
+ controls.update();
6342
+ controls.saveState();
6343
+ this.registerEventDispatcher(controls);
6344
+ return controls;
6345
+ }
6346
+ //</editor-fold>
6347
+ init() {
6348
+ if (this._disposed) return;
6349
+ if (typeof window["__THREE_DEVTOOLS__"] !== "undefined") {
6350
+ window["__THREE_DEVTOOLS__"].dispatchEvent(new CustomEvent("observe", { detail: this.scene }));
6351
+ }
6352
+ if (this.options.debug.grid) {
6353
+ const gridHelper = new GridHelper(128, 16);
6354
+ this._debugHelpers.push(gridHelper);
6355
+ this.scene.add(gridHelper);
6356
+ const gridHelper2 = new GridHelper(128, 16);
6357
+ this._debugHelpers.push(gridHelper2);
6358
+ gridHelper2.rotation.x = 90 * (Math.PI / 180);
6359
+ this.scene.add(gridHelper2);
6360
+ const gridHelper3 = new GridHelper(128, 16);
6361
+ this._debugHelpers.push(gridHelper3);
6362
+ gridHelper3.rotation.z = 90 * (Math.PI / 180);
6363
+ this.scene.add(gridHelper3);
6364
+ }
6365
+ if (this.options.debug.axes) {
6366
+ const axesHelper = new AxesHelper3(64);
6367
+ this._debugHelpers.push(axesHelper);
6368
+ this.scene.add(axesHelper);
6369
+ }
6370
+ if (this.options.camera.position) {
6371
+ if (isVector3(this.options.camera.position)) {
6372
+ this.camera.position.set(this.options.camera.position.x, this.options.camera.position.y, this.options.camera.position.z);
6373
+ } else if (isTripleArray(this.options.camera.position)) {
6374
+ this.camera.position.set(this.options.camera.position[0], this.options.camera.position[1], this.options.camera.position[2]);
6375
+ }
6376
+ }
6377
+ if (this.options.camera.lookingAt) {
6378
+ if (isVector3(this.options.camera.lookingAt)) {
6379
+ this.camera.lookAt(this.options.camera.lookingAt);
6380
+ } else if (isTripleArray(this.options.camera.lookingAt)) {
6381
+ this.camera.lookAt(this.options.camera.lookingAt[0], this.options.camera.lookingAt[1], this.options.camera.lookingAt[2]);
6382
+ }
6383
+ }
6384
+ if (this.options.render.autoResize && !this._resizeListener) {
6385
+ this._resizeListener = () => {
6386
+ this.resize(this.viewWidth, this.viewHeight);
6387
+ };
6388
+ window.addEventListener("resize", this._resizeListener);
6389
+ }
6390
+ }
6391
+ get element() {
6392
+ return this._element;
6393
+ }
6394
+ appendTo(element) {
6395
+ if (this._disposed) return;
6396
+ this._element = element;
6397
+ this._element.appendChild(this.renderer.domElement);
6398
+ if (this.viewWidth == 0) {
6399
+ console.warn("0 element width");
6400
+ }
6401
+ if (this.viewHeight == 0) {
6402
+ console.warn("0 element height");
6403
+ }
6404
+ this.resize(this.viewWidth, this.viewHeight);
6405
+ }
6406
+ /**
6407
+ * Redraws when the dispatcher emits the selected event. Registering the same pair twice has no effect.
6408
+ * The renderer removes its listener on disposal; the caller retains ownership of the dispatcher.
6409
+ */
6410
+ registerEventDispatcher(dispatcher, changeEvent2 = "change") {
6411
+ if (this._disposed) return;
6412
+ let events = this._eventDispatchers.get(dispatcher);
6413
+ if (!events) {
6414
+ events = /* @__PURE__ */ new Set();
6415
+ this._eventDispatchers.set(dispatcher, events);
6340
6416
  }
6341
- function onContextMenu(event) {
6342
- if (scope.enabled === false) return;
6343
- event.preventDefault();
6417
+ if (events.has(changeEvent2)) return;
6418
+ events.add(changeEvent2);
6419
+ dispatcher.addEventListener(changeEvent2, this._changeListener);
6420
+ }
6421
+ resize(width, height) {
6422
+ if (this._disposed) return;
6423
+ if (isPerspectiveCamera(this.camera)) {
6424
+ this.camera.aspect = width / height;
6425
+ this.camera.updateProjectionMatrix();
6426
+ } else if (isOrthographicCamera(this.camera)) {
6427
+ this.camera.left = width / -2;
6428
+ this.camera.right = width / 2;
6429
+ this.camera.top = height / 2;
6430
+ this.camera.bottom = height / -2;
6431
+ this.camera.updateProjectionMatrix();
6344
6432
  }
6345
- function addPointer(event) {
6346
- pointers.push(event);
6433
+ this.renderer.setSize(width, height);
6434
+ this.composer?.setSize(width, height);
6435
+ this._dirty = true;
6436
+ }
6437
+ //<editor-fold desc="RENDER">
6438
+ get dirty() {
6439
+ return this._dirty || this.scene.dirty;
6440
+ }
6441
+ set dirty(dirty) {
6442
+ this._dirty = dirty;
6443
+ this.scene.dirty = dirty;
6444
+ }
6445
+ start() {
6446
+ if (this._disposed) return;
6447
+ this.stop();
6448
+ this.renderer.setAnimationLoop(this._animationLoop);
6449
+ }
6450
+ stop() {
6451
+ if (this._disposed) return;
6452
+ this.renderer.setAnimationLoop(null);
6453
+ this._nextFrameTime = void 0;
6454
+ }
6455
+ /**
6456
+ * Stops rendering and releases owned resources. Repeated calls have no effect, and a disposed
6457
+ * renderer cannot be restarted. Scene objects are detached; shared assets and caller-owned
6458
+ * controls must be managed by their owners.
6459
+ */
6460
+ dispose() {
6461
+ if (this._disposed) return;
6462
+ this.stop();
6463
+ this._disposed = true;
6464
+ if (this._resizeListener) {
6465
+ window.removeEventListener("resize", this._resizeListener);
6466
+ this._resizeListener = void 0;
6467
+ }
6468
+ for (const [dispatcher, events] of this._eventDispatchers) {
6469
+ for (const event of events) {
6470
+ dispatcher.removeEventListener(event, this._changeListener);
6471
+ }
6472
+ }
6473
+ this._eventDispatchers.clear();
6474
+ this._stats?.dom.remove();
6475
+ this._stats = void 0;
6476
+ this.renderer.domElement.remove();
6477
+ this._element = void 0;
6478
+ if (this._controls) {
6479
+ const controls = this._controls;
6480
+ this._controls = void 0;
6481
+ controls.enabled = false;
6482
+ controls.dispose();
6483
+ }
6484
+ this.scene.clear();
6485
+ for (const helper of this._debugHelpers) {
6486
+ helper.geometry.dispose();
6487
+ const materials = Array.isArray(helper.material) ? helper.material : [helper.material];
6488
+ for (const material of materials) {
6489
+ material.dispose();
6490
+ }
6491
+ }
6492
+ this._debugHelpers.length = 0;
6493
+ this.composer?.dispose();
6494
+ this.renderer.dispose();
6495
+ this.renderer.forceContextLoss();
6496
+ }
6497
+ animate(t = performance.now()) {
6498
+ if (this._disposed) return;
6499
+ if (this._controls?.enabled) {
6500
+ this._controls.update();
6501
+ }
6502
+ if (this._disposed) return;
6503
+ if (!this.dirty && !this.options.render.renderAlways) return;
6504
+ const interval = this._frameInterval;
6505
+ if (interval) {
6506
+ const next = this._nextFrameTime;
6507
+ if (next !== void 0 && t + 0.1 < next) return;
6508
+ this._nextFrameTime = next !== void 0 && t - next < interval ? next + interval : t + interval;
6347
6509
  }
6348
- function removePointer(event) {
6349
- delete pointerPositions[event.pointerId];
6350
- for (let i = 0; i < pointers.length; i++) {
6351
- if (pointers[i].pointerId == event.pointerId) {
6352
- pointers.splice(i, 1);
6353
- return;
6354
- }
6355
- }
6510
+ if (this._stats) {
6511
+ this._stats.begin();
6356
6512
  }
6357
- function trackPointer(event) {
6358
- let position = pointerPositions[event.pointerId];
6359
- if (position === void 0) {
6360
- position = new Vector23();
6361
- pointerPositions[event.pointerId] = position;
6362
- }
6363
- position.set(event.pageX, event.pageY);
6513
+ if (this.options.composer.enabled && this.composer) {
6514
+ this.composer.render();
6515
+ } else {
6516
+ this.renderer.render(this.scene, this.camera);
6364
6517
  }
6365
- function getSecondPointerPosition(event) {
6366
- const pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0];
6367
- return pointerPositions[pointer.pointerId];
6518
+ this.dirty = false;
6519
+ if (this._stats) {
6520
+ this._stats.end();
6368
6521
  }
6369
- scope.domElement.addEventListener("contextmenu", onContextMenu);
6370
- scope.domElement.addEventListener("pointerdown", onPointerDown);
6371
- scope.domElement.addEventListener("pointercancel", onPointerCancel);
6372
- scope.domElement.addEventListener("wheel", onMouseWheel, { passive: false });
6373
- this.update();
6374
6522
  }
6523
+ //</editor-fold>
6524
+ toImage() {
6525
+ return this.renderer.domElement.toDataURL();
6526
+ }
6527
+ ///
6528
+ get attachedToBody() {
6529
+ return this.element === document.body;
6530
+ }
6531
+ get viewWidth() {
6532
+ return this.attachedToBody ? window.innerWidth : this.element?.offsetWidth || 0;
6533
+ }
6534
+ get viewHeight() {
6535
+ return this.attachedToBody ? window.innerHeight : this.element?.offsetHeight || 0;
6536
+ }
6537
+ get scene() {
6538
+ return this._scene;
6539
+ }
6540
+ get camera() {
6541
+ return this._camera;
6542
+ }
6543
+ get renderer() {
6544
+ return this._renderer;
6545
+ }
6546
+ get composer() {
6547
+ return this._composer;
6548
+ }
6549
+ /** Renderer-owned controls, or undefined when disabled at construction or after disposal. */
6550
+ get controls() {
6551
+ return this._controls;
6552
+ }
6553
+ ///
6375
6554
  };
6376
- var MapControls = class extends OrbitControls {
6377
- constructor(object, domElement) {
6378
- super(object, domElement);
6379
- this.screenSpacePanning = false;
6380
- this.mouseButtons.LEFT = MOUSE.PAN;
6381
- this.mouseButtons.RIGHT = MOUSE.ROTATE;
6382
- this.touches.ONE = TOUCH.PAN;
6383
- this.touches.TWO = TOUCH.DOLLY_ROTATE;
6555
+
6556
+ // src/skin/Skins.ts
6557
+ var Skins = class {
6558
+ //<editor-fold desc="Skins">
6559
+ static async fromUuidOrUsername(uuidOrUsername) {
6560
+ if (uuidOrUsername.length === 32 || uuidOrUsername.length === 36) {
6561
+ return this.fromUuid(uuidOrUsername);
6562
+ }
6563
+ return this.fromUsername(uuidOrUsername);
6564
+ }
6565
+ static async fromUuid(uuid) {
6566
+ return this.getSkinProxySkinUrl(uuid);
6567
+ }
6568
+ static async fromUsername(username) {
6569
+ return this.usernameToUuid(username).then((uuid) => {
6570
+ if (uuid) {
6571
+ return this.fromUuid(uuid);
6572
+ }
6573
+ return void 0;
6574
+ });
6575
+ }
6576
+ static async fromMineSkin(mineskinId) {
6577
+ return this.getMineSkin(mineskinId).then((mineskin) => {
6578
+ if (mineskin) {
6579
+ return mineskin["data"]["texture"]["value"]["urls"]["skins"];
6580
+ }
6581
+ return void 0;
6582
+ });
6583
+ }
6584
+ //</editor-fold>
6585
+ //<editor-fold desc="Capes">
6586
+ static async capeFromUuidOrUsername(uuidOrUsername) {
6587
+ if (uuidOrUsername.length === 32 || uuidOrUsername.length === 36) {
6588
+ return this.capeFromUuid(uuidOrUsername);
6589
+ }
6590
+ return this.capeFromUsername(uuidOrUsername);
6591
+ }
6592
+ static async capeFromUuid(uuid) {
6593
+ return this.getSkinProxyCapeUrl(uuid);
6594
+ }
6595
+ static async capeFromUsername(username) {
6596
+ return this.usernameToUuid(username).then((uuid) => {
6597
+ if (uuid) {
6598
+ return this.capeFromUuid(uuid);
6599
+ }
6600
+ return void 0;
6601
+ });
6602
+ }
6603
+ static async capeFromCapesDev(uuid, capeType = "minecraft") {
6604
+ return this.getCapesDev(uuid, capeType).then((cape) => {
6605
+ if (cape) {
6606
+ return cape?.stillImageUrl;
6607
+ }
6608
+ return void 0;
6609
+ });
6610
+ }
6611
+ //</editor-fold>
6612
+ //<editor-fold desc="Helpers">
6613
+ static async usernameToUuid(username) {
6614
+ return this.usernameToUuidSkinProxy(username);
6615
+ }
6616
+ static async usernameToUuidSkinProxy(username) {
6617
+ return Requests.genericRequest({
6618
+ baseURL: "https://minecraft-skin-proxy.inventive.workers.dev",
6619
+ url: "/uuid/" + username
6620
+ }).then((res) => {
6621
+ if (res.status === 200) {
6622
+ return res.data["id"];
6623
+ }
6624
+ return void 0;
6625
+ }).catch((err) => {
6626
+ console.warn(err);
6627
+ return void 0;
6628
+ });
6629
+ }
6630
+ static async usernameToUuidMineTools(username) {
6631
+ return Requests.genericRequest({
6632
+ baseURL: "https://api.minetools.eu",
6633
+ url: "/uuid/" + username
6634
+ }).then((res) => {
6635
+ if (res.status === 200) {
6636
+ return res.data["id"];
6637
+ }
6638
+ return void 0;
6639
+ }).catch((err) => {
6640
+ console.warn(err);
6641
+ return void 0;
6642
+ });
6643
+ }
6644
+ static async getProfileFromMinetools(uuid) {
6645
+ return Requests.genericRequest({
6646
+ baseURL: "https://api.minetools.eu",
6647
+ url: "/profile/" + uuid
6648
+ }).then((res) => {
6649
+ if (res.status === 200) {
6650
+ return res.data;
6651
+ }
6652
+ });
6653
+ }
6654
+ static async getMineSkin(mineskinId) {
6655
+ return Requests.genericRequest({
6656
+ baseURL: "https://api.mineskin.org",
6657
+ url: "/get/uuid/" + mineskinId
6658
+ }).then((res) => {
6659
+ if (res.status === 200) {
6660
+ return res.data;
6661
+ }
6662
+ return void 0;
6663
+ }).catch((err) => {
6664
+ console.warn(err);
6665
+ return void 0;
6666
+ });
6667
+ }
6668
+ static async getCapesDev(uuid, type = "all") {
6669
+ return Requests.genericRequest({
6670
+ baseURL: "https://api.capes.dev",
6671
+ url: "/load/" + uuid + "/" + type
6672
+ }).then((res) => {
6673
+ if (res.status === 200) {
6674
+ return res.data;
6675
+ }
6676
+ return void 0;
6677
+ }).catch((err) => {
6678
+ console.warn(err);
6679
+ return void 0;
6680
+ });
6681
+ }
6682
+ static getCrafatarSkinUrl(uuid) {
6683
+ return "https://crafatar.com/skins/" + uuid;
6384
6684
  }
6685
+ static getCrafatarCapeUrl(uuid) {
6686
+ return "https://crafatar.com/capes/" + uuid;
6687
+ }
6688
+ static getMcHeadsSkinUrl(uuid) {
6689
+ return "https://mc-heads.net/skin/" + uuid;
6690
+ }
6691
+ static getMineSkinPlayerSkinUrl(uuid) {
6692
+ return "https://mineskin.org/skin/player/" + uuid;
6693
+ }
6694
+ static getSkinProxySkinUrl(uuid) {
6695
+ return "https://minecraft-skin-proxy.inventive.workers.dev/skin/" + uuid;
6696
+ }
6697
+ static getSkinProxyCapeUrl(uuid) {
6698
+ return "https://minecraft-skin-proxy.inventive.workers.dev/cape/" + uuid;
6699
+ }
6700
+ //</editor-fold>
6385
6701
  };
6386
6702
 
6387
6703
  // src/world/Chunk.ts
@@ -6444,7 +6760,7 @@ var MineRenderWorld = class {
6444
6760
  console.log("CHUNKS", this._chunks);
6445
6761
  for (let chunk of this._chunks.values()) {
6446
6762
  console.log("dispose chunk", chunk);
6447
- await (chunk == null ? void 0 : chunk.dispose());
6763
+ await chunk?.dispose();
6448
6764
  }
6449
6765
  this._chunks.clear();
6450
6766
  }
@@ -6673,6 +6989,7 @@ export {
6673
6989
  OrbitControls,
6674
6990
  PersistentCache,
6675
6991
  Renderer,
6992
+ RequestError,
6676
6993
  Requests,
6677
6994
  SKIN_PARTS,
6678
6995
  SceneInspector,