Skip to content

Commit f4c5793

Browse files
snowyukittyobiotclaude
authored
TextureAtlas: compute quad UVs instead of adding a region for every drawn rectangle (#1734)
Drawing part of an image, a bitmap font glyph or a repeating pattern no longer adds a "x,y,w,h" region to the atlas, and identical rectangles on pages of different sizes no longer share UVs. drawImage and drawPattern work the UVs out from the image size, four divisions into a per-atlas scratch array: no string key, no allocation, nothing stored per rectangle. A page whose JSON size differs from its image keeps its frames' own UVs, through an index built by addUVs. The image size is read when its pixels go to the GPU (first draw, and after CanvasRenderTarget#invalidate through TextureCache#sizeChanged); videos are read every draw. getUVs no longer reads a "x,y,w,h" string, and frames no longer get "x,y,w,h" alias keys. Closes #1281 Co-authored-by: Olivier Biot <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SeWCkETjW35ZbXDRswV1hx
1 parent d63bcfd commit f4c5793

10 files changed

Lines changed: 1310 additions & 57 deletions

File tree

‎packages/melonjs/CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
# Changelog
22

3+
## [20.11.0] (melonJS 2) - _unreleased_
4+
5+
### Fixed
6+
- TextureAtlas: drawing part of an image, a bitmap font glyph or a repeating pattern no longer adds a region to the atlas for every new source rectangle. Those regions piled up for as long as the atlas lived, and turned up among the frames an animation is built from ([#1281](https://github.com/melonjs/melonJS/issues/1281), thanks @snowyukitty)
7+
- TextureAtlas: on an atlas with pages of different sizes, a source rectangle drawn from one page no longer reuses the UVs worked out for the same rectangle on another (thanks @snowyukitty)
8+
9+
### Performance
10+
- Rendering: drawing a sprite, a glyph or a pattern computes its UVs from the image size instead of looking them up, with no string built and nothing allocated or kept. On the platformer, text and Jungle Rabbit examples a lookup took 34 to 58 ns and now takes 6 to 10, in Chrome and WebKit: 1 to 2% of a frame's CPU time on the text example, and too little to measure on the platformer
11+
312
## [20.10.1] (melonJS 2) - _2026-10-21_
413

514
### Fixed

‎packages/melonjs/src/video/rendertarget/canvasrendertarget.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,9 @@ class CanvasRenderTarget extends RenderTarget {
314314
renderer.cache.get(this.canvas),
315315
);
316316
renderer.currentBatcher.markTextureDirty(this.glTextureUnit);
317+
// the new pixels may come at a new size, and UVs are worked out
318+
// from the size of the pixels on the GPU
319+
renderer.cache.sizeChanged(this.canvas);
317320
} else if (renderer.type === "WebGPU" && renderer.cache.has(this.canvas)) {
318321
// drain pending vertices, then re-upload the canvas. The store
319322
// gives the new pixels a fresh GPUTexture when draws recorded
@@ -324,6 +327,7 @@ class CanvasRenderTarget extends RenderTarget {
324327
renderer.textureStore.getBinding(renderer.cache.get(this.canvas), {
325328
force: true,
326329
});
330+
renderer.cache.sizeChanged(this.canvas);
327331
}
328332
}
329333

‎packages/melonjs/src/video/texture/atlas.js‎

Lines changed: 213 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import Texture2d from "./texture2d.ts";
1717
// (`on`, not `once`: a re-init — new Application after destroy — must
1818
// re-capture the new renderer).
1919
let _renderer;
20+
2021
on(VIDEO_INIT, (renderer) => {
2122
/**
2223
* @ignore
@@ -25,6 +26,28 @@ on(VIDEO_INIT, (renderer) => {
2526
_renderer = renderer;
2627
});
2728

29+
/**
30+
* The stored UVs of the frame at exactly this source rectangle of a page.
31+
* @param {object} page - a page's record from `TextureAtlas#_pageUVs`
32+
* @param {number} x - source x coordinate
33+
* @param {number} y - source y coordinate
34+
* @param {number} w - source width
35+
* @param {number} h - source height
36+
* @returns {Float32Array|undefined} the frame's UVs, if one is there
37+
* @ignore
38+
*/
39+
function frameUVs(page, x, y, w, h) {
40+
const corner = page.frames.get(x)?.get(y);
41+
if (corner !== undefined) {
42+
for (const f of corner) {
43+
if (f.width === w && f.height === h) {
44+
return f.uvs;
45+
}
46+
}
47+
}
48+
return undefined;
49+
}
50+
2851
/**
2952
* additional import for TypeScript
3053
* @import {CompressedImage} from "../../loader/parsers/compressed_textures/compressed_image.js";
@@ -180,11 +203,38 @@ export class TextureAtlas extends Texture2d {
180203
this.activeAtlas = undefined;
181204

182205
/**
183-
* UV lookup cache to avoid per-frame string allocation in drawImage
206+
* Per atlas page: the size its frames' UVs were normalized by, and
207+
* its frames by source rectangle (x, then y, then the frames at that
208+
* corner), kept out of the page dictionary that animation code
209+
* walks. See {@link TextureAtlas#addUVs}.
210+
* @ignore
211+
* @internal
212+
*/
213+
this._pageUVs = new WeakMap();
214+
215+
/**
216+
* What {@link TextureAtlas#_quadUVs} writes a computed rectangle into,
217+
* so a draw allocates nothing. Overwritten by the next call.
184218
* @ignore
185219
* @internal
186220
*/
187-
this._uvCache = { sx: -1, sy: -1, sw: -1, sh: -1, uvs: null };
221+
this._uvScratch = new Float32Array(4);
222+
223+
/**
224+
* The image and page last drawn from, their size, and whether that
225+
* page computes every UV from it, so a draw from the same page
226+
* decides nothing. See {@link TextureAtlas#_quadUVs}.
227+
* @ignore
228+
* @internal
229+
*/
230+
this._uvSizeCheck = {
231+
source: null,
232+
page: null,
233+
width: 0,
234+
height: 0,
235+
fixed: false,
236+
computed: true,
237+
};
188238

189239
// parse given atlas(es) paremeters
190240
if (typeof atlases !== "undefined") {
@@ -445,49 +495,144 @@ export class TextureAtlas extends Texture2d {
445495
}
446496

447497
/**
448-
* return the uvs mapping for the given region
498+
* Return the UVs of a named region, or of a source rectangle of the
499+
* active page.
500+
*
501+
* A rectangle that is one of the active page's frames returns that
502+
* frame's own UVs. Any other rectangle returns a new array, computed from
503+
* the size of the active page's image: nothing is cached and nothing is
504+
* added to the atlas.
449505
* @param {string|number} name - region (or frame) name, or sx when using numeric parameters
450506
* @param {number} [sy] - source y coordinate (when using numeric parameters)
451507
* @param {number} [sw] - source width (when using numeric parameters)
452508
* @param {number} [sh] - source height (when using numeric parameters)
453509
* @returns {Float32Array} region Uvs
510+
* @throws {Error} if no region has that name
454511
*/
455512
getUVs(name, sy, sw, sh) {
456513
if (typeof name === "number") {
457-
const sx = name;
458-
const cache = this._uvCache;
459-
// fast path: return cached UVs if coordinates match last lookup
460-
if (
461-
sx === cache.sx &&
462-
sy === cache.sy &&
463-
sw === cache.sw &&
464-
sh === cache.sh
465-
) {
466-
return cache.uvs;
467-
}
468-
// cache miss: fall back to string-keyed region lookup
469-
const key = sx + "," + sy + "," + sw + "," + sh;
470-
let region = this.getRegion(key);
471-
if (typeof region === "undefined") {
472-
region = this.addRegion(key, sx, sy, sw, sh);
473-
}
474-
cache.sx = sx;
475-
cache.sy = sy;
476-
cache.sw = sw;
477-
cache.sh = sh;
478-
cache.uvs = region.uvs;
514+
const page = this._pageUVs.get(this.getAtlas());
515+
const frame =
516+
page === undefined ? undefined : frameUVs(page, name, sy, sw, sh);
517+
return (
518+
frame ??
519+
Float32Array.from(this._quadUVs(this.getTexture(), name, sy, sw, sh))
520+
);
521+
}
522+
523+
const region = this.getRegion(name);
524+
if (typeof region?.uvs !== "undefined") {
479525
return region.uvs;
480526
}
527+
throw new Error("Texture - region for " + name + " not found");
528+
}
481529

482-
// string-based lookup (named regions)
483-
let region = this.getRegion(name);
530+
/**
531+
* The UVs a renderer draws a source rectangle of the active page with.
532+
*
533+
* Computed, not looked up: four divisions by the page's size. The
534+
* result is written into one scratch array, so a draw allocates nothing
535+
* and the next call overwrites it; read it straight away.
536+
*
537+
* A frame's UVs are normalized by the size its atlas file gives, which
538+
* is the page's own size unless the image was exported or loaded at
539+
* another scale than its file describes. On such a page a frame is drawn
540+
* with its own UVs, as it always was, and anything else with the page's
541+
* real size. Which kind of page this is gets decided once, and again
542+
* when another page or image is drawn from, or when the image's pixels
543+
* are replaced (see {@link TextureAtlas#_decideUVs}).
544+
* @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|OffscreenCanvas|CompressedImage} source - the active page's image, as drawn
545+
* @param {number} sx - source x coordinate
546+
* @param {number} sy - source y coordinate
547+
* @param {number} sw - source width
548+
* @param {number} sh - source height
549+
* @returns {Float32Array} the UVs, valid until the next call
550+
* @ignore
551+
* @internal
552+
*/
553+
_quadUVs(source, sx, sy, sw, sh) {
554+
const check = this._uvSizeCheck;
555+
// kept small so engines inline it into the draw: deciding a page and
556+
// reading a frame's own UVs are the rare work, out of line
557+
if (
558+
check.source !== source ||
559+
check.page !== this.activeAtlas ||
560+
!check.fixed
561+
) {
562+
this._decideUVs(source);
563+
}
564+
if (!check.computed) {
565+
const frame = frameUVs(
566+
this._pageUVs.get(this.getAtlas()),
567+
sx,
568+
sy,
569+
sw,
570+
sh,
571+
);
572+
if (frame !== undefined) {
573+
return frame;
574+
}
575+
}
576+
const width = check.width;
577+
const height = check.height;
578+
const uvs = this._uvScratch;
579+
uvs[0] = sx / width;
580+
uvs[1] = sy / height;
581+
uvs[2] = (sx + sw) / width;
582+
uvs[3] = (sy + sh) / height;
583+
return uvs;
584+
}
484585

485-
if (typeof region === "undefined") {
486-
// see https://github.com/melonjs/melonJS/issues/1281
487-
const keys = name.split(",");
488-
region = this.addRegion(name, +keys[0], +keys[1], +keys[2], +keys[3]);
586+
/**
587+
* The out-of-line half of {@link TextureAtlas#_quadUVs}: read the size
588+
* of the image drawn from, and decide whether the active page computes
589+
* every UV from it.
590+
*
591+
* The size is read when the image's pixels go to the GPU: the first
592+
* time it is drawn, and again after {@link TextureAtlas#_sizeChanged},
593+
* which a canvas render target's `invalidate()` calls when it hands the
594+
* GPU new pixels, maybe at a new size. Between those, a resized canvas
595+
* still shows its old pixels on the GPU, and the old size is the one
596+
* that samples them; reading a DOM image's size also costs more than the
597+
* whole computation. A video is read on every draw, as it uploads every
598+
* frame, and so is an image with no size yet, one still loading.
599+
* @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|OffscreenCanvas|CompressedImage} source - the active page's image, as drawn
600+
* @ignore
601+
* @internal
602+
*/
603+
_decideUVs(source) {
604+
const check = this._uvSizeCheck;
605+
const width = source.width || source.videoWidth;
606+
const height = source.height || source.videoHeight;
607+
if (
608+
check.source === source &&
609+
check.page === this.activeAtlas &&
610+
check.width === width &&
611+
check.height === height
612+
) {
613+
return;
489614
}
490-
return region.uvs;
615+
const page = this._pageUVs.get(this.getAtlas());
616+
check.source = source;
617+
check.page = this.activeAtlas;
618+
check.width = width;
619+
check.height = height;
620+
check.fixed =
621+
width > 0 && height > 0 && typeof source.videoWidth !== "number";
622+
check.computed =
623+
page === undefined ||
624+
(!page.mixed && page.width === width && page.height === height);
625+
}
626+
627+
/**
628+
* Read the image's size and decide its page again on the next draw:
629+
* the image's pixels are being replaced, maybe at another size, or a
630+
* new frame changed what its page needs.
631+
* @ignore
632+
* @internal
633+
*/
634+
_sizeChanged() {
635+
this._uvSizeCheck.source = null;
491636
}
492637

493638
/**
@@ -510,17 +655,39 @@ export class TextureAtlas extends Texture2d {
510655
(s.x + sw) / w, // u1 (right)
511656
(s.y + sh) / h, // v1 (bottom)
512657
]);
513-
// Cache source coordinates
514-
// see https://github.com/melonjs/melonJS/issues/1281
515-
// keyed by the REGION rect (x, y, width, height) — the same key shape
516-
// `getUVs(sx, sy, sw, sh)` builds for coordinate lookups. (Keying by
517-
// the texture dimensions instead made the alias unmatchable for any
518-
// sub-region AND poisoned full-image lookups whenever a frame sat at
519-
// (0,0): "0,0,texW,texH" pointed at that frame, not the whole image.)
520-
const key = `${s.x},${s.y},${sw},${sh}`;
521-
if (key !== name) {
522-
atlas[key] = atlas[name];
658+
// Indexed by source rectangle beside the page, not in it: animation
659+
// code walks the page dictionary, and a second key per frame would
660+
// show up there. Also note the size these UVs were normalized by:
661+
// a draw computes its UVs from the page's own size, and only a page
662+
// where that would differ needs a frame's stored UVs.
663+
let page = this._pageUVs.get(atlas);
664+
if (page === undefined) {
665+
page = { width: w, height: h, mixed: false, frames: new Map() };
666+
this._pageUVs.set(atlas, page);
667+
} else if (page.width !== w || page.height !== h) {
668+
page.mixed = true;
669+
}
670+
let column = page.frames.get(s.x);
671+
if (column === undefined) {
672+
column = new Map();
673+
page.frames.set(s.x, column);
674+
}
675+
let corner = column.get(s.y);
676+
if (corner === undefined) {
677+
corner = [];
678+
column.set(s.y, corner);
679+
}
680+
const entry = { width: sw, height: sh, uvs: atlas[name].uvs };
681+
const i = corner.findIndex((f) => {
682+
return f.width === sw && f.height === sh;
683+
});
684+
if (i === -1) {
685+
corner.push(entry);
686+
} else {
687+
corner[i] = entry;
523688
}
689+
// a new frame can change whether its page computes every UV
690+
this._sizeChanged();
524691

525692
return atlas[name].uvs;
526693
}
@@ -639,9 +806,8 @@ export class TextureAtlas extends Texture2d {
639806
const isArray = Array.isArray(names);
640807
const name = isArray ? names[i] : i;
641808
// in dictionary mode, only iterate real regions: a region's `name`
642-
// matches its dictionary key. This skips both the coordinate-alias
643-
// keys added by `addUVs` (#1281 — they'd duplicate every frame) and
644-
// non-region entries like the aseprite parser's `anims` dictionary
809+
// matches its dictionary key. This skips non-region entries like
810+
// the aseprite parser's `anims` dictionary
645811
// (whose value has no `name`, and which `getRegion` would otherwise
646812
// happily return as a NaN-sized pseudo-region).
647813
if (!isArray && (names[i] == null || names[i].name !== i)) {
@@ -704,8 +870,8 @@ export class TextureAtlas extends Texture2d {
704870
for (const i in names) {
705871
const isArray = Array.isArray(names);
706872
const name = isArray ? names[i] : i;
707-
// dictionary mode: skip coordinate-alias keys and non-region
708-
// entries (see getAnimationSettings for the full rationale)
873+
// dictionary mode: skip non-region entries (see
874+
// getAnimationSettings for the full rationale)
709875
if (!isArray && (names[i] == null || names[i].name !== i)) {
710876
continue;
711877
}

‎packages/melonjs/src/video/texture/cache.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,19 @@ class TextureCache {
289289
return this.cache.has(image);
290290
}
291291

292+
/**
293+
* @ignore
294+
* @internal
295+
* the image's pixels are being replaced, maybe at another size: every
296+
* atlas drawn from it reads its size again on its next draw (see
297+
* `TextureAtlas#_decideUVs`)
298+
*/
299+
sizeChanged(image) {
300+
for (const atlas of this.cache.get(image)) {
301+
atlas._sizeChanged?.();
302+
}
303+
}
304+
292305
/**
293306
* @ignore
294307
* @internal

0 commit comments

Comments
 (0)