@antha/asset 0.0.1

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.
package/LICENSE-CC0 ADDED
@@ -0,0 +1,121 @@
1
+ CC0 1.0 Universal
2
+
3
+ Creative Commons Legal Code
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 electrovir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @antha/asset
2
+
3
+ A pre-built [Antha](https://www.npmjs.com/package/antha) mod for handling asset loading.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm i @antha/asset
9
+ ```
@@ -0,0 +1,83 @@
1
+ import { type PartialWithUndefined } from '@augment-vir/common';
2
+ import { AssetLoader } from './asset-loader.js';
3
+ /**
4
+ * Engine state for the Antha asset mod loading screen.
5
+ *
6
+ * @category Internal
7
+ */
8
+ export type AnthaAssetModLoadingScreenState = {
9
+ /** The total number to load. Once `current` reaches this, loading is considered complete. */
10
+ total: number;
11
+ /**
12
+ * The current number of loaded assets. Once this reaches `total`, the loading is considered
13
+ * complete.
14
+ */
15
+ current: number;
16
+ currentResourceName?: string | undefined;
17
+ completedAt: DOMHighResTimeStamp | undefined;
18
+ };
19
+ /**
20
+ * State for {@link AnthaAssetMod}.
21
+ *
22
+ * @category Internal
23
+ */
24
+ export type AnthaAssetModState = {
25
+ assetLoader: AssetLoader;
26
+ isShowingLoadingScreen: boolean;
27
+ loadingScreenState: AnthaAssetModLoadingScreenState | undefined;
28
+ };
29
+ /**
30
+ * Configuration options for {@link createAnthaAssetMod}.
31
+ *
32
+ * @category Internal
33
+ */
34
+ export type AnthaAssetModOptions = PartialWithUndefined<{
35
+ /**
36
+ * If set to `true`, the default loading screen is not rendered. You should probably make your
37
+ * own loading screen in that case.
38
+ *
39
+ * @default false
40
+ */
41
+ hideLoadingScreen: boolean;
42
+ }>;
43
+ /**
44
+ * Duration in milliseconds for the loading screen fade-out animation.
45
+ *
46
+ * @category Internal
47
+ */
48
+ export declare const loadingScreenFadeMs = 1000;
49
+ /**
50
+ * Duration in milliseconds for the progress bar grow transition.
51
+ *
52
+ * @category Internal
53
+ */
54
+ export declare const loadingScreenProgressGrowMs = 200;
55
+ /**
56
+ * Default loading screen element rendered by the Antha asset mod while assets are being loaded.
57
+ *
58
+ * @category Internal
59
+ */
60
+ export declare const AnthaAssetLoadingScreen: import("element-vir").DeclarativeElementDefinition<"antha-asset-loading-screen", {
61
+ progressPercent: number;
62
+ dotCount: number;
63
+ completed: boolean;
64
+ currentResourceName: string | undefined;
65
+ }, {}, {}, "antha-asset-loading-screen-completed", "antha-asset-loading-screen-", readonly [], readonly []>;
66
+ /**
67
+ * The Antha Asset mod, created by {@link createAnthaAssetMod}.
68
+ *
69
+ * @category Pre-Built Mods
70
+ */
71
+ export type AnthaAssetMod = ReturnType<typeof createAnthaAssetMod>;
72
+ /**
73
+ * Name for the mod {@link AnthaAssetMod}.
74
+ *
75
+ * @category Internal
76
+ */
77
+ export declare const anthaAssetModName = "antha-asset";
78
+ /**
79
+ * Creates the Antha asset mod which manages asset loading and an optional loading screen overlay.
80
+ *
81
+ * @category Pre-Built Mods
82
+ */
83
+ export declare function createAnthaAssetMod(options?: Readonly<AnthaAssetModOptions>): import("@antha/engine").AnthaMod<NoInfer<AnthaAssetModState>>;
@@ -0,0 +1,175 @@
1
+ import { defineAnthaMod } from '@antha/engine';
2
+ import { css, defineElement, html } from 'element-vir';
3
+ import { AssetLoader, AssetLoaderProgressUpdateEvent } from './asset-loader.js';
4
+ /**
5
+ * Duration in milliseconds for the loading screen fade-out animation.
6
+ *
7
+ * @category Internal
8
+ */
9
+ export const loadingScreenFadeMs = 1000;
10
+ /**
11
+ * Duration in milliseconds for the progress bar grow transition.
12
+ *
13
+ * @category Internal
14
+ */
15
+ export const loadingScreenProgressGrowMs = 200;
16
+ /**
17
+ * Default loading screen element rendered by the Antha asset mod while assets are being loaded.
18
+ *
19
+ * @category Internal
20
+ */
21
+ export const AnthaAssetLoadingScreen = defineElement()({
22
+ tagName: 'antha-asset-loading-screen',
23
+ hostClasses: {
24
+ 'antha-asset-loading-screen-completed': ({ inputs }) => inputs.completed,
25
+ },
26
+ styles: ({ hostClasses }) => css `
27
+ :host {
28
+ position: fixed;
29
+ inset: 0;
30
+ display: flex;
31
+ flex-direction: column;
32
+ align-items: center;
33
+ justify-content: center;
34
+ background-color: black;
35
+ color: white;
36
+ z-index: 9999;
37
+ gap: 24px;
38
+ opacity: 1;
39
+ transition: opacity ${loadingScreenFadeMs}ms ease-in;
40
+ }
41
+
42
+ .loading-text {
43
+ font-size: 24px;
44
+ position: relative;
45
+ }
46
+
47
+ .dots {
48
+ font-family: monospace;
49
+ position: absolute;
50
+ left: 100%;
51
+ bottom: 0;
52
+ }
53
+
54
+ .progress-track {
55
+ width: 300px;
56
+ height: 1em;
57
+ overflow: hidden;
58
+ border: 4px solid white;
59
+ }
60
+
61
+ .current-resource-name {
62
+ font-size: 14px;
63
+ opacity: 0.7;
64
+ }
65
+
66
+ .progress-fill {
67
+ height: 100%;
68
+ background-color: white;
69
+ transition: width ${loadingScreenProgressGrowMs}ms ease-in;
70
+ }
71
+
72
+ ${hostClasses['antha-asset-loading-screen-completed'].selector} {
73
+ opacity: 0;
74
+ }
75
+ `,
76
+ render({ inputs }) {
77
+ const dotCount = inputs.dotCount % 4;
78
+ const dots = '.'.repeat(dotCount) + '\u00A0'.repeat(3 - dotCount);
79
+ return html `
80
+ <span class="loading-text">
81
+ Loading
82
+ <span class="dots">${dots}</span>
83
+ </span>
84
+ <div>
85
+ <span class="current-resource-name">
86
+ ${inputs.currentResourceName ||
87
+ html `
88
+ &nbsp;
89
+ `}
90
+ </span>
91
+ <div class="progress-track">
92
+ <div
93
+ class="progress-fill"
94
+ style=${css `
95
+ width: ${inputs.progressPercent}%;
96
+ `}
97
+ ></div>
98
+ </div>
99
+ </div>
100
+ `;
101
+ },
102
+ });
103
+ /**
104
+ * Name for the mod {@link AnthaAssetMod}.
105
+ *
106
+ * @category Internal
107
+ */
108
+ export const anthaAssetModName = 'antha-asset';
109
+ /**
110
+ * Creates the Antha asset mod which manages asset loading and an optional loading screen overlay.
111
+ *
112
+ * @category Pre-Built Mods
113
+ */
114
+ export function createAnthaAssetMod(options = {}) {
115
+ return defineAnthaMod({
116
+ modName: anthaAssetModName,
117
+ async cleanup({ state }) {
118
+ await state.assetLoader?.destroy();
119
+ state.loadingScreenState = undefined;
120
+ state.isShowingLoadingScreen = false;
121
+ },
122
+ execute({ state, engine }) {
123
+ if (!state.assetLoader) {
124
+ state.assetLoader = new AssetLoader({
125
+ logger: engine.log,
126
+ });
127
+ if (!options.hideLoadingScreen) {
128
+ state.assetLoader.listen(AssetLoaderProgressUpdateEvent, (event) => {
129
+ if (event.detail.complete) {
130
+ state.loadingScreenState = {
131
+ current: 1,
132
+ total: 1,
133
+ currentResourceName: event.detail.currentResourceName ||
134
+ state.loadingScreenState?.currentResourceName,
135
+ completedAt: engine.totalMs,
136
+ };
137
+ state.isShowingLoadingScreen = false;
138
+ }
139
+ else {
140
+ state.isShowingLoadingScreen = true;
141
+ state.loadingScreenState = {
142
+ current: event.detail.current,
143
+ total: event.detail.total,
144
+ currentResourceName: event.detail.currentResourceName,
145
+ completedAt: undefined,
146
+ };
147
+ }
148
+ });
149
+ }
150
+ }
151
+ if (options.hideLoadingScreen) {
152
+ return;
153
+ }
154
+ const shouldShowLoadingScreen = state.loadingScreenState?.completedAt
155
+ ? engine.totalMs <= state.loadingScreenState.completedAt + loadingScreenFadeMs
156
+ : true;
157
+ if (state.loadingScreenState && shouldShowLoadingScreen) {
158
+ const progressPercent = state.loadingScreenState.total > 0
159
+ ? (state.loadingScreenState.current / state.loadingScreenState.total) * 100
160
+ : 0;
161
+ return html `
162
+ <${AnthaAssetLoadingScreen.assign({
163
+ progressPercent,
164
+ dotCount: Math.floor(engine.totalMs / 500) % 4,
165
+ completed: !!state.loadingScreenState.completedAt,
166
+ currentResourceName: state.loadingScreenState.currentResourceName,
167
+ })}></${AnthaAssetLoadingScreen}>
168
+ `;
169
+ }
170
+ else {
171
+ return undefined;
172
+ }
173
+ },
174
+ });
175
+ }
@@ -0,0 +1,171 @@
1
+ import { type AnthaLogger } from '@antha/engine';
2
+ import { type MaybePromise, type PartialWithUndefined } from '@augment-vir/common';
3
+ import { ListenTarget } from 'typed-event-target';
4
+ /**
5
+ * Call this to increment the loading progress of this asset. It is expected that this gets called
6
+ * enough times to increment the progress count until the asset's `maxProgress` is reached.
7
+ *
8
+ * @category Internal
9
+ */
10
+ export type AssetIncrementProgressCallback = (
11
+ /** The amount that the progress should be incremented with this call. */
12
+ amount?: number | undefined) => void;
13
+ /**
14
+ * A callback for loading / creating an {@link Asset} value.
15
+ *
16
+ * @category Internal
17
+ */
18
+ export type AssetLoaderCallback<AssetValue> = (params: Readonly<{
19
+ /**
20
+ * Call this to increment the loading progress of this asset. It is expected that this gets
21
+ * called enough times to increment the progress count until the asset's `maxProgress` is
22
+ * reached.
23
+ */
24
+ incrementProgressCallback: AssetIncrementProgressCallback;
25
+ }>) => MaybePromise<AssetLoaderResult<AssetValue>>;
26
+ /**
27
+ * A loaded {@link Asset} result, returned from {@link AssetLoaderCallback}
28
+ *
29
+ * @category Internal
30
+ */
31
+ export type AssetLoaderResult<AssetValue = any> = {
32
+ value: AssetValue;
33
+ cleanup?: undefined | AssetCleanupCallback;
34
+ };
35
+ /**
36
+ * Cleanup callback for {@link Asset}.
37
+ *
38
+ * @category Internal
39
+ */
40
+ export type AssetCleanupCallback = () => MaybePromise<void>;
41
+ /**
42
+ * Extracts the loaded value type from an {@link Asset}.
43
+ *
44
+ * @category Internal
45
+ */
46
+ export type AssetValue<SpecificAsset extends Pick<Asset, 'load'>> = Awaited<ReturnType<SpecificAsset['load']>>['value'];
47
+ /**
48
+ * Defines a loadable asset.
49
+ *
50
+ * @category Asset
51
+ */
52
+ export type Asset<AssetValue = any> = {
53
+ name: string;
54
+ maxProgress: number;
55
+ load: AssetLoaderCallback<AssetValue>;
56
+ };
57
+ /**
58
+ * A helper for defining and inferring the value type of an {@link Asset}.
59
+ *
60
+ * @category Asset
61
+ */
62
+ export declare function defineAsset<AssetValue>(asset: Asset<AssetValue>): Asset<NoInfer<AssetValue>>;
63
+ /**
64
+ * Options for {@link AssetLoader.bulkLoadAssets}.
65
+ *
66
+ * @category Internal
67
+ */
68
+ export type AssetBulkLoaderLoadOptions = PartialWithUndefined<{
69
+ /**
70
+ * How many assets can be loaded in parallel at once.
71
+ *
72
+ * @default Infinity // no limit
73
+ */
74
+ maxParallelism: number;
75
+ /**
76
+ * If `true`, previous assets will not be unloaded. By default, when loading new bulk assets,
77
+ * all previous assets that are not included in the new asset list will be cleaned up.
78
+ *
79
+ * @default false
80
+ */
81
+ doNotUnload: boolean;
82
+ /**
83
+ * If `true`, the loading screen events will not be emitted.
84
+ *
85
+ * @default false
86
+ */
87
+ hideLoadingScreen: boolean;
88
+ }>;
89
+ /**
90
+ * Options for {@link AssetLoader}.
91
+ *
92
+ * @category Internal
93
+ */
94
+ export type AssetLoaderOptions = PartialWithUndefined<{
95
+ /**
96
+ * A custom logger to handle mod and engine logs. By default, this merely logs to the browser
97
+ * console.
98
+ */
99
+ logger: AnthaLogger;
100
+ }>;
101
+ declare const AssetLoaderProgressUpdateEvent_base: (new (eventInitDict: {
102
+ bubbles?: boolean;
103
+ cancelable?: boolean;
104
+ composed?: boolean;
105
+ detail: {
106
+ current: number;
107
+ total: number;
108
+ currentResourceName?: string | undefined;
109
+ /**
110
+ * Always check this complete field first, as any misconfigured assets ma not correctly
111
+ * increment `total` but complete will always reliably mark the end of loading.
112
+ */
113
+ complete: boolean;
114
+ };
115
+ }) => import("typed-event-target").TypedCustomEvent<{
116
+ current: number;
117
+ total: number;
118
+ currentResourceName?: string | undefined;
119
+ /**
120
+ * Always check this complete field first, as any misconfigured assets ma not correctly
121
+ * increment `total` but complete will always reliably mark the end of loading.
122
+ */
123
+ complete: boolean;
124
+ }, "antha-asset-loader-progress-update-event">) & Pick<{
125
+ new (type: string, eventInitDict?: EventInit): Event;
126
+ prototype: Event;
127
+ readonly NONE: 0;
128
+ readonly CAPTURING_PHASE: 1;
129
+ readonly AT_TARGET: 2;
130
+ readonly BUBBLING_PHASE: 3;
131
+ }, "prototype" | "NONE" | "CAPTURING_PHASE" | "AT_TARGET" | "BUBBLING_PHASE"> & Pick<import("typed-event-target").TypedCustomEvent<{
132
+ current: number;
133
+ total: number;
134
+ currentResourceName?: string | undefined;
135
+ /**
136
+ * Always check this complete field first, as any misconfigured assets ma not correctly
137
+ * increment `total` but complete will always reliably mark the end of loading.
138
+ */
139
+ complete: boolean;
140
+ }, "antha-asset-loader-progress-update-event">, "type">;
141
+ /**
142
+ * Custom event dispatched by {@link AssetLoader} whenever bulk loading progress changes. Used for
143
+ * loading screen progression.
144
+ *
145
+ * @category Internal
146
+ */
147
+ export declare class AssetLoaderProgressUpdateEvent extends AssetLoaderProgressUpdateEvent_base {
148
+ }
149
+ /**
150
+ * Manages loading, caching, and cleanup of game assets with progress tracking.
151
+ *
152
+ * @category Asset
153
+ */
154
+ export declare class AssetLoader extends ListenTarget<AssetLoaderProgressUpdateEvent> {
155
+ constructor(options?: Readonly<AssetLoaderOptions>);
156
+ /** Logs data. This will use the user's provided logger or default to browser logs. */
157
+ protected readonly log: AnthaLogger;
158
+ protected readonly assetCache: Map<Readonly<Asset<any>>, Promise<AssetLoaderResult<any>>>;
159
+ /** Loads a single asset, returning its cached value if already loaded. */
160
+ loadIndividualAsset<ThisAsset extends Asset>({ asset, incrementProgressCallback, }: Readonly<{
161
+ asset: Readonly<ThisAsset>;
162
+ incrementProgressCallback?: AssetIncrementProgressCallback | undefined;
163
+ }>): Promise<AssetValue<ThisAsset>>;
164
+ /** Runs cleanup callbacks for the given assets and removes them from the cache. */
165
+ unloadAssets(assets: ReadonlyArray<Asset>): Promise<void>;
166
+ destroy(): Promise<void>;
167
+ /** Loads multiple assets. */
168
+ bulkLoadAssets(assets: ReadonlyArray<Readonly<Asset>>, options?: Readonly<AssetBulkLoaderLoadOptions>): Promise<ReadonlyArray<unknown>>;
169
+ private dispatchProgressUpdate;
170
+ }
171
+ export {};
@@ -0,0 +1,172 @@
1
+ import { browserAnthaLogger } from '@antha/engine';
2
+ import { awaitedBlockingMap, awaitedForEach, chunkArray, DeferredPromise, ensureErrorAndPrependMessage, } from '@augment-vir/common';
3
+ import { defineTypedCustomEvent, ListenTarget } from 'typed-event-target';
4
+ /**
5
+ * A helper for defining and inferring the value type of an {@link Asset}.
6
+ *
7
+ * @category Asset
8
+ */
9
+ export function defineAsset(asset) {
10
+ return asset;
11
+ }
12
+ /**
13
+ * Custom event dispatched by {@link AssetLoader} whenever bulk loading progress changes. Used for
14
+ * loading screen progression.
15
+ *
16
+ * @category Internal
17
+ */
18
+ export class AssetLoaderProgressUpdateEvent extends defineTypedCustomEvent()('antha-asset-loader-progress-update-event') {
19
+ }
20
+ /**
21
+ * Manages loading, caching, and cleanup of game assets with progress tracking.
22
+ *
23
+ * @category Asset
24
+ */
25
+ export class AssetLoader extends ListenTarget {
26
+ constructor(options = {}) {
27
+ super();
28
+ this.log = options.logger || browserAnthaLogger;
29
+ }
30
+ /** Logs data. This will use the user's provided logger or default to browser logs. */
31
+ log;
32
+ assetCache = new Map();
33
+ /** Loads a single asset, returning its cached value if already loaded. */
34
+ async loadIndividualAsset({ asset, incrementProgressCallback, }) {
35
+ const cached = this.assetCache.get(asset);
36
+ if (cached) {
37
+ const assetResult = await cached;
38
+ return assetResult.value;
39
+ }
40
+ const deferredLoadPromise = new DeferredPromise();
41
+ this.assetCache.set(asset, deferredLoadPromise.promise);
42
+ const loadedAsset = await asset.load({
43
+ incrementProgressCallback(progressParams) {
44
+ incrementProgressCallback?.(progressParams);
45
+ },
46
+ });
47
+ deferredLoadPromise.resolve(loadedAsset);
48
+ return loadedAsset.value;
49
+ }
50
+ /** Runs cleanup callbacks for the given assets and removes them from the cache. */
51
+ async unloadAssets(assets) {
52
+ await awaitedForEach(assets, async (asset) => {
53
+ const entry = await this.assetCache.get(asset);
54
+ if (entry?.cleanup) {
55
+ try {
56
+ await entry.cleanup();
57
+ }
58
+ catch (error) {
59
+ this.log.error(ensureErrorAndPrependMessage(error, `Failed to cleanup asset: ${asset.name}`));
60
+ }
61
+ }
62
+ this.assetCache.delete(asset);
63
+ });
64
+ }
65
+ async destroy() {
66
+ super.destroy();
67
+ const entries = Array.from(this.assetCache.entries());
68
+ await awaitedForEach(entries, async ([asset, result,]) => {
69
+ await (await result).cleanup?.();
70
+ this.assetCache.delete(asset);
71
+ });
72
+ }
73
+ /** Loads multiple assets. */
74
+ async bulkLoadAssets(assets, options = {}) {
75
+ const assetsToCleanup = options.doNotUnload
76
+ ? []
77
+ : Array.from(this.assetCache.keys()).filter((asset) => {
78
+ return !assets.includes(asset);
79
+ });
80
+ const assetsToLoad = assets.filter((asset) => {
81
+ return !this.assetCache.has(asset);
82
+ });
83
+ const cleanupCount = assetsToCleanup.length ? 1 : 0;
84
+ const maxProgress = assetsToLoad.reduce((count, asset) => {
85
+ return count + asset.maxProgress;
86
+ }, 0) + cleanupCount;
87
+ let currentProgress = 0;
88
+ if (!options.hideLoadingScreen && assetsToLoad.length) {
89
+ this.dispatchProgressUpdate({
90
+ current: currentProgress,
91
+ total: maxProgress,
92
+ currentResourceName: assetsToLoad[0]?.name,
93
+ complete: false,
94
+ });
95
+ }
96
+ await this.unloadAssets(assetsToCleanup);
97
+ if (!assetsToLoad.length) {
98
+ return assets.map((asset) => this.assetCache.get(asset));
99
+ }
100
+ currentProgress += cleanupCount;
101
+ if (!options.hideLoadingScreen) {
102
+ this.dispatchProgressUpdate({
103
+ current: currentProgress,
104
+ total: maxProgress,
105
+ currentResourceName: assetsToLoad[0]?.name,
106
+ complete: false,
107
+ });
108
+ }
109
+ const chunkedAssets = options.maxParallelism
110
+ ? chunkArray(assets, {
111
+ chunkSize: options.maxParallelism,
112
+ })
113
+ : [[...assets]];
114
+ const createIncrementProgressCallback = (asset) => (amount) => {
115
+ currentProgress += amount ?? 1;
116
+ if (!options.hideLoadingScreen) {
117
+ this.dispatchProgressUpdate({
118
+ current: currentProgress,
119
+ total: maxProgress,
120
+ currentResourceName: asset.name,
121
+ complete: false,
122
+ });
123
+ }
124
+ };
125
+ const results = (await awaitedBlockingMap(chunkedAssets, async (assetChunk) => {
126
+ return await Promise.all(assetChunk.map(async (asset) => {
127
+ if (this.assetCache.has(asset)) {
128
+ return (await this.assetCache.get(asset))?.value;
129
+ }
130
+ if (!options.hideLoadingScreen) {
131
+ this.dispatchProgressUpdate({
132
+ current: currentProgress,
133
+ total: maxProgress,
134
+ currentResourceName: asset.name,
135
+ complete: false,
136
+ });
137
+ }
138
+ return await this.loadIndividualAsset({
139
+ incrementProgressCallback: createIncrementProgressCallback(asset),
140
+ asset,
141
+ });
142
+ }));
143
+ })).flat();
144
+ if (currentProgress !== maxProgress) {
145
+ this.log.error(new Error('Finished loading assets but did not reach max loading progress.'), {
146
+ context: {
147
+ currentProgress,
148
+ maxProgress,
149
+ assetCount: assetsToLoad.length,
150
+ assetNames: assetsToLoad.map((entry) => entry.name).filter(Boolean),
151
+ },
152
+ tags: {
153
+ mod: '@antha/asset',
154
+ },
155
+ });
156
+ }
157
+ if (!options.hideLoadingScreen) {
158
+ this.dispatchProgressUpdate({
159
+ current: maxProgress,
160
+ total: maxProgress,
161
+ currentResourceName: assetsToLoad[assetsToLoad.length - 1]?.name,
162
+ complete: true,
163
+ });
164
+ }
165
+ return results;
166
+ }
167
+ dispatchProgressUpdate(detail) {
168
+ this.dispatch(new AssetLoaderProgressUpdateEvent({
169
+ detail,
170
+ }));
171
+ }
172
+ }
@@ -0,0 +1,2 @@
1
+ export * from './antha-asset.mod.js';
2
+ export * from './asset-loader.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './antha-asset.mod.js';
2
+ export * from './asset-loader.js';
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@antha/asset",
3
+ "version": "0.0.1",
4
+ "description": "An Antha mod for handling asset loading.",
5
+ "keywords": [
6
+ "vir",
7
+ "antha",
8
+ "asset",
9
+ "loading"
10
+ ],
11
+ "homepage": "https://github.com/electrovir/antha",
12
+ "bugs": {
13
+ "url": "https://github.com/electrovir/antha/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/electrovir/antha.git"
18
+ },
19
+ "license": "(MIT OR CC0-1.0)",
20
+ "author": {
21
+ "name": "electrovir",
22
+ "url": "https://github.com/electrovir"
23
+ },
24
+ "sideEffects": false,
25
+ "type": "module",
26
+ "main": "dist/index.js",
27
+ "module": "dist/index.js",
28
+ "types": "dist/index.d.ts",
29
+ "scripts": {
30
+ "compile": "virmator compile",
31
+ "docs": "virmator docs",
32
+ "test": "virmator test web",
33
+ "test:coverage": "npm test coverage",
34
+ "test:docs": "virmator docs check"
35
+ },
36
+ "dependencies": {
37
+ "@augment-vir/assert": "^31.73.1",
38
+ "@augment-vir/common": "^31.73.1",
39
+ "typed-event-target": "^4.3.1"
40
+ },
41
+ "devDependencies": {
42
+ "@augment-vir/test": "^31.73.1",
43
+ "@web/dev-server-esbuild": "^1.0.5",
44
+ "@web/test-runner": "^0.20.2",
45
+ "@web/test-runner-playwright": "^0.11.1",
46
+ "istanbul-smart-text-reporter": "^1.1.5",
47
+ "pixi.js": "^8.19.0"
48
+ },
49
+ "peerDependencies": {
50
+ "@antha/engine": "*",
51
+ "element-vir": ">=26"
52
+ },
53
+ "engines": {
54
+ "node": ">=22"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public"
58
+ }
59
+ }