diff --git a/src/core/CoreNode.test.ts b/src/core/CoreNode.test.ts index a2cfefb13..5536ee719 100644 --- a/src/core/CoreNode.test.ts +++ b/src/core/CoreNode.test.ts @@ -22,7 +22,10 @@ import { CoreNode, type CoreNodeProps, UpdateType } from './CoreNode.js'; import { Stage } from './Stage.js'; import { CoreRenderer } from './renderers/CoreRenderer.js'; import { mock } from 'vitest-mock-extended'; -import { type TextureOptions } from './CoreTextureManager.js'; +import { + type CoreTextureManager, + type TextureOptions, +} from './CoreTextureManager.js'; import { createBound } from './lib/utils.js'; import { ImageTexture } from './textures/ImageTexture.js'; @@ -79,6 +82,7 @@ describe('CoreNode', () => { state: 'loaded', }, renderer: mock() as CoreRenderer, + txManager: mock({ frame: 0 }) as CoreTextureManager, }); describe('set color()', () => { diff --git a/src/core/CoreNode.ts b/src/core/CoreNode.ts index 059fcb0f4..b6f77bc99 100644 --- a/src/core/CoreNode.ts +++ b/src/core/CoreNode.ts @@ -1546,6 +1546,12 @@ export class CoreNode extends EventEmitter { const previous = this.renderState; this.renderState = renderState; + // An image coming on screen uploads ahead of preload-margin images. + const texture = this.props.texture; + if (renderState === CoreNodeRenderState.InViewport && texture) { + texture.lastOnScreen = this.stage.txManager.frame; + this.stage.txManager.prioritize(texture); + } const event = CoreNodeRenderStateMap.get(renderState); assertTruthy(event); this.emit(event, { diff --git a/src/core/CoreTextureManager.ts b/src/core/CoreTextureManager.ts index b54094ec9..4a85f73f6 100644 --- a/src/core/CoreTextureManager.ts +++ b/src/core/CoreTextureManager.ts @@ -241,8 +241,32 @@ export class CoreTextureManager extends EventEmitter { * * @param texture - The texture to upload */ + /** + * Frames drawn, advanced by the Stage: how recently a texture was on screen + * (upload order, memory cleanup order). + */ + public frame = 0; + + /** + * An image just came on screen: if its upload is queued, move it to the + * front, ahead of images preloading in the bounds margin. + */ + prioritize(texture: Texture): void { + const i = this.uploadTextureQueue.indexOf(texture); + if (i > 0) { + this.uploadTextureQueue.splice(i, 1); + this.uploadTextureQueue.unshift(texture); + } + } + enqueueUploadTexture(texture: Texture): void { if (this.uploadTextureQueue.includes(texture) === false) { + // On screen within the last ~second (it came into view while still + // fetching): upload it first. + if (this.frame - texture.lastOnScreen < 60) { + this.uploadTextureQueue.unshift(texture); + return; + } this.uploadTextureQueue.push(texture); } } diff --git a/src/core/Stage.ts b/src/core/Stage.ts index acc4f87ef..2bdab040c 100644 --- a/src/core/Stage.ts +++ b/src/core/Stage.ts @@ -468,6 +468,8 @@ export class Stage { root.update(this.deltaTime, root.clippingRect); } + this.txManager.frame++; + // Process some textures asynchronously but don't block the frame // Use a background task to prevent frame drops if (this.txManager.hasUpdates() === true) { diff --git a/src/core/TextureMemoryManager.ts b/src/core/TextureMemoryManager.ts index 7014fc421..d23188b5e 100644 --- a/src/core/TextureMemoryManager.ts +++ b/src/core/TextureMemoryManager.ts @@ -248,15 +248,28 @@ export class TextureMemoryManager { // Skip null entries, mark cleaned textures as null for later defrag let currentMemUsed = this.memUsed; - for (let i = 0; i < this.loadedTextures.length; i++) { + // Least recently on screen first, not oldest loaded: oldest-first freed a + // home page's posters (loaded first, still one Back press away) before a + // page's that would never be seen again. A texture owned by a node is in + // view now, so its age counts from now. Cleanup is rare, so the sort is + // cheap next to the GPU memory it frees. + const now = this.stage.txManager.frame; + const candidates: Texture[] = []; + for (const texture of this.loadedTextures) { + if (!texture) continue; // Skip null entries from previous deletions + if (texture.renderableOwners.length > 0) { + texture.lastOnScreen = now; + } + candidates.push(texture); + } + candidates.sort((a, b) => a.lastOnScreen - b.lastOnScreen); + + for (const texture of candidates) { // Early exit: target memory reached if (full === false && currentMemUsed < memTarget) { break; } - const texture = this.loadedTextures[i]; - if (!texture) continue; // Skip null entries from previous deletions - // Fast type check for cleanable textures const isCleanableType = texture.type === TextureType.image || diff --git a/src/core/platforms/web/WebPlatform.ts b/src/core/platforms/web/WebPlatform.ts index 93823204d..08fa006d9 100644 --- a/src/core/platforms/web/WebPlatform.ts +++ b/src/core/platforms/web/WebPlatform.ts @@ -45,6 +45,15 @@ interface FontFaceSetWithAdd extends FontFaceSet { add(font: FontFace): this; } +/** + * Deadline for one image request, in milliseconds. A poster is tens to a few + * hundred KB from a CDN, so a healthy request finishes well under a second; + * past 5s it has stalled, and the retry (1s, 2s, 4s...) recovers it sooner + * than waiting longer would. On a very slow link a large image that needs + * more than 5s will not load; raise this if that is seen on devices. + */ +const FETCH_TIMEOUT_MS = 5000; + export class WebPlatform extends Platform { private useImageWorker: boolean; private imageWorkerManager: ImageWorkerManager | null = null; @@ -213,6 +222,26 @@ export class WebPlatform extends Platform { } } }; + // A request that never completes (seen on tvOS NativeScript: the server + // answered, the XHR never heard back) would hold its image forever, never + // loaded and never retried. Past the deadline it fails like a network + // error, so the texture retries. + const timer = setTimeout(() => { + xhr.onreadystatechange = null; + try { + xhr.abort(); + } catch { + // rejected below either way + } + reject(new Error(`Timed out loading ${url}`)); + }, FETCH_TIMEOUT_MS); + const settle = xhr.onreadystatechange; + xhr.onreadystatechange = function (event) { + if (xhr.readyState === 4) { + clearTimeout(timer); + } + settle.call(this, event); + }; xhr.open('GET', url, true); xhr.send(null); }); diff --git a/src/core/textures/ImageTexture.ts b/src/core/textures/ImageTexture.ts index a6c699e20..22107c35b 100644 --- a/src/core/textures/ImageTexture.ts +++ b/src/core/textures/ImageTexture.ts @@ -101,9 +101,9 @@ export interface ImageTextureProps { /** * Maximum number of times to retry loading the image if it fails. * - * @default 5 + * @default the stage's `maxRetryCount` setting */ - maxRetryCount?: number; + maxRetryCount?: number | null; } export interface ImageResponse { @@ -139,7 +139,10 @@ export class ImageTexture extends Texture { this.platform = txManager.platform; this.props = props; - this.maxRetryCount = props.maxRetryCount as number; + // Only an explicit per-texture count overrides the stage's. + if (props.maxRetryCount !== null) { + this.maxRetryCount = props.maxRetryCount; + } } override async getTextureSource(): Promise { @@ -278,7 +281,10 @@ export class ImageTexture extends Texture { sy: props.sy ?? null, sw: props.sw ?? null, sh: props.sh ?? null, - maxRetryCount: props.maxRetryCount ?? 5, + // Unset stays unset, so the Texture keeps the stage's maxRetryCount from + // its constructor. The `src` setter passes none, so a hard default of 5 + // meant the app's setting never reached a single image. + maxRetryCount: props.maxRetryCount ?? null, }; } diff --git a/src/core/textures/Texture.ts b/src/core/textures/Texture.ts index fb8bc9edf..cd7d6c252 100644 --- a/src/core/textures/Texture.ts +++ b/src/core/textures/Texture.ts @@ -182,6 +182,16 @@ export abstract class Texture extends EventEmitter { * is loaded/freed. Set to 0 when texture is not loaded. */ public retryCount = 0; + /** Earliest time of the next load attempt after a failure. */ + public retryAt = 0; + private retryTimer: ReturnType | null = null; + static RETRY_FIRST_MS = 1000; + static RETRY_MAX_MS = 60000; + /** + * The texture manager frame at which a node showing this texture last came + * on screen: orders the upload queue and memory cleanup. + */ + public lastOnScreen = -Infinity; public maxRetryCount: number; /** @@ -322,6 +332,20 @@ export abstract class Texture extends EventEmitter { // We've exceeded the max retry count, do not attempt to load again return; } + // Still inside the retry wait: a timer brings it back, and loads only if + // a node still wants the texture by then. + const wait = this.retryAt - Date.now(); + if (wait > 0) { + if (this.retryTimer === null) { + this.retryTimer = setTimeout(() => { + this.retryTimer = null; + if (this.renderableOwners.length > 0) { + this.load(); + } + }, wait); + } + return; + } this.txManager.loadTexture(this); } @@ -430,6 +454,15 @@ export abstract class Texture extends EventEmitter { // this is used to compare against maxRetryCount, if set // to determine if we should try loading again this.retryCount += 1; + // The next attempt waits, doubling from 1s to 60s. Back-to-back retries + // spent the whole count in a few seconds of bad network, and the image + // then never loaded again for the session. + this.retryAt = + Date.now() + + Math.min( + Texture.RETRY_MAX_MS, + Texture.RETRY_FIRST_MS * 2 ** (this.retryCount - 1), + ); queueMicrotask(this.releaseTask); } else if (state === 'loading') {