Swapping a texture's image without marking its materials dirty or dropping it while the new one loads

Playground: https://playground.babylonjs.com/#71RRJM#0

When a streamed world changes the level of its textures, it swaps the images of many textures at once. Texture.updateURL does two things that cost us there:

  • It releases the old image right away, so every mesh using the texture is not drawn until the new one has loaded.
  • For each texture, it marks dirty every material of the scene that has it: Scene.markAllMaterialsAsDirty walks all the scene’s materials, so swapping N textures makes N × materials hasTexture calls, and each of those materials is evaluated again.

What we do instead: load the new image in a separate Texture, and once it has loaded, point the old texture at its image, the way the engine’s texture cache shares one InternalTexture among textures (incrementReferences(), then dispose() on the old image). The material keeps the same texture, no material is marked dirty, and the meshes stay drawn with the old image until the new one is there.

The Playground swaps the textures of 600 materials both ways, in alternate rounds. Measured on 9.32.0 (Chromium 147, RTX 3080 Laptop GPU, Windows 11), the medians of 3 rounds, in two runs:

Swap calls hasTexture calls Frames with boxes missing Frames until the new images show
updateURL, WebGPU 161 and 179 ms 360,000 2, with none of the 600 drawn 3
Pointed at the loaded image, WebGPU 136 and 151 ms 0 0 3
updateURL, WebGL2 96 and 89 ms 360,000 0 1
Pointed at the loaded image, WebGL2 52 and 49 ms 0 0 1

The swap calls include starting the loads of the 600 images, both ways. On WebGL2, these small images load within a frame, so no box goes missing there.

In our world, this took the dirty marking from about 1 ms per frame to nothing and the 95th percentile of the frame time down by 16.5 %, and the hitch we had every half second went away.

The Playground does it with internals (_texture), which an application should not rely on. Would you welcome a public way to do it, for example an option of updateURL that keeps the current image until the new one has loaded and swaps it without marking the materials, or a method that points a texture at the image of another one? We can prepare the PR either way.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

Thanks for the detailed repro! Both points are valid: updateURL releases the current internal texture before loading the replacement, and it scans all scene materials to find those using the texture. When updating many textures at once, those repeated scans can add up.

Keeping the same Texture object and replacing its backing image once the new one is ready makes sense for texture streaming. I’d be open to a PR exposing this through a supported API.

The main caveat is that skipping material invalidation is only safe when the replacement has compatible shader-facing properties. For example, changing the internal texture can change the effective gammaSpace or RGBD state, which affects shader defines. A resolution-only replacement with the same interpretation should not need that reevaluation, but we shouldn’t skip it unconditionally for arbitrary textures.

Of the two proposals, I’d lean toward a method that replaces the backing image with that of an already-loaded texture. This separates loading from replacement and lets applications manage preloading and scheduling themselves. It would need to handle reference counting, keep the texture’s URL/loading metadata consistent, and clearly define the compatibility requirements for avoiding material invalidation.

One small qualification regarding the benchmark: the readiness and draw-count checks are useful, but “frames until the new images show” is really measuring readiness plus draw submission rather than verifying the displayed pixels. It would also help to alternate which image set each method loads, not just alternate the methods, to reduce cache/order bias. That doesn’t invalidate the underlying observation about the repeated material scans.

1 Like

Thanks, both points taken. We reran it as you suggest: https://playground.babylonjs.com/#6E1OAE#0. The method order now alternates between rounds, so each method loads each of the two image sets as often. The materials are unlit, so a box shows its texture as is, and every frame the canvas is read back: the pixel at the center of each box says whether it shows its new image, its old one or nothing.

Measured on 9.32.1 (Chromium 147, RTX 3080 Laptop GPU, Windows 11), 4 swaps with each method, two to each image set (ranges over the 4):

Swap calls hasTexture calls Frames with boxes missing on screen Frames until every box shows its new image
updateURL, WebGPU 122-160 ms 360,000 1-2, with none of the 600 shown 2-3
Pointed at the loaded image, WebGPU 89-121 ms 0 0 2
updateURL, WebGL2 79-95 ms 360,000 0 1
Pointed at the loaded image, WebGL2 44-50 ms 0 0 1

The pixels agree with the draw counts. On WebGPU, updateURL leaves the screen without the boxes for 1 or 2 frames, and the new images show on the next one; pointed at the loaded image, a box shows its old image until the frame where it shows the new one. Every sampled pixel was one of the two images or the clear color. The swap calls still include starting the loads of the 600 images.

On the API, a method that replaces the backing image with that of an already loaded texture fits our streaming well, since it already loads ahead and schedules the swaps. For the PR we would propose texture.replaceImage(source):

  • source must be ready. The texture takes a reference to the source’s internal texture and releases its own, and the source keeps its reference until the application disposes of it.
  • The texture takes the source’s URL and loading metadata (url, invertY, mimeType, forced extension, and no buffer), so it reports, serializes and reloads the image it shows.
  • The materials that use the texture are marked dirty, as updateURL does, unless the two images match in what reaches the shader defines: gammaSpace, RGBD, invertY, and the kind of texture (2D, cube, array, 3D). A resolution change alone marks nothing.

Is that list of properties the right one for skipping the invalidation, or would you add some?

(Sorry for answering all four topics at once: I had them ready and preferred to send them together.)

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

Thanks for updating the repro! Alternating the method order and checking the pixels addresses the main limitations of the first version. The readbacks add synchronization overhead, so I’d keep these results separate from normal frame-time measurements, but they provide stronger evidence for the missing-box behavior.

replaceImage(source) sounds like a reasonable direction. I’d refine the compatibility rules in a few places:

  • Compare the effective gammaSpace and isRGBD values. In particular, account for the replacement’s sRGB-buffer state rather than comparing only the wrappers’ stored gamma setting.

  • invertY is not itself a material shader define. It describes upload orientation. There is also loader-specific orientation handling: KTX textures can require a UV correction through _invertVScale. Matching invertY alone therefore doesn’t establish matching orientation, and marking materials dirty won’t fix an incorrect orientation. The replacement needs to preserve the destination’s intended UV mapping.

  • If environment textures are supported, the list is broader. For example, linearSpecularLOD comes from the internal texture and affects shader defines. Replacing it can also change the associated irradiance texture, which affects the IBL shader configuration. I’d avoid promising general cube/environment-texture support in the first version.

  • Texture dimensionality should be a compatibility requirement, not just an invalidation trigger. Marking a material dirty does not necessarily make replacing a 2D image with a cube, array or 3D texture valid for that material’s sampler.

For a first PR, I’d suggest targeting ordinary loaded 2D image textures on the same engine, retaining the destination’s material-facing settings such as UV transforms, coordinates index, alpha usage and wrapping. Resolution-only changes should take the fast path. Specialized textures—render targets, video textures and environment textures—can remain outside the initial contract.

For loading metadata, please also consider mipmap settings, format, sRGB-buffer creation settings and loader options. I wouldn’t specify “no buffer” unconditionally: a source created from a supplied buffer may not be reconstructible from its URL alone. The goal should be that serialization and subsequent loading remain consistent with the adopted image.

Finally, skipping material dirtying must not skip the necessary texture rebinding. Please cover WebGL2 and WebGPU, including frozen materials, so the new backing image is picked up without requiring shader-define reevaluation.

The reference-counting ownership you describe is correct. With the scope above, this looks like a useful, manageable addition.

Thanks, that’s a clear scope. For the first PR:

  • Scope: ordinary loaded 2D image textures, with the source and the destination on the same engine. Render targets, video textures, and cube and environment textures stay outside the contract, and replaceImage refuses them: it returns false and changes nothing.
  • Requirements, checked before anything changes, refused otherwise rather than invalidated:
    • the same dimensionality (2D);
    • the same effective orientation, which compares invertY together with the internal texture’s _invertVScale, so the destination keeps its intended UV mapping.
  • Fast path or invalidation: the materials are marked dirty only when the effective gammaSpace or isRGBD differ, with the gamma taken from the internal texture’s sRGB-buffer state rather than from the wrappers’ stored setting. A resolution-only change takes the fast path.
  • What the destination keeps: its material-facing settings (UV transforms, coordinatesIndex, alpha usage and wrapping).
  • What it adopts: the source’s loading description as a whole, including mipmaps, format, sRGB-buffer creation and loader options, and the source’s buffer when it was created from one. Serializing it and loading it again then gives the image it shows. A source whose loading can’t be described that way is refused.
  • Rebinding: skipping the dirty marking doesn’t skip binding the new image. On WebGPU, the bind groups (and a recorded snapshot) must pick up the new internal texture. We’ll test that on WebGL2 and WebGPU, with frozen materials, checking the pixels.
  • Measurements: agreed, the pixel-checked rounds stay separate from frame-time numbers.

We’ll prepare the PR with that contract and those tests.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

That sounds good—please go ahead with the PR. The proposed scope and tests cover the main concerns.

One clarification on gamma: the effective value is not determined by the sRGB-buffer flag alone. The current getter combines the internal texture’s gamma state with !_useSRGBBuffer, initializing that gamma state from the wrapper when necessary. Please preserve the source’s effective interpretation when adopting its image, including when its internal gamma state hasn’t yet been initialized.

For orientation, rejecting incompatible replacements is a reasonable first-version restriction. Just remember that _invertVScale has already been applied to the source wrapper’s UV transform during loading; replacement should not apply that correction again or copy the source’s UV transform over the destination’s.

Please also include ownership edge cases in the tests: replacing with itself, two wrappers already sharing the same internal texture, and disposing the source after replacement. Rejected calls should leave both textures unchanged, and the documentation should explain what a false return means.

Otherwise, no further scope additions from me—we can review the implementation details in the PR.

Opened #19099: texture.replaceImage(source), with the contract from #5 and your points from #6:

  • Gamma: the effective value is the getter’s, the internal texture’s gamma state together with !_useSRGBBuffer. When the source’s image has no gamma state yet, it gets the source wrapper’s before the swap, as the getter would set it, so the image keeps the source’s interpretation. The materials are marked dirty only when the effective gamma or the RGBD encoding changes.
  • Orientation: a source whose invertY or _invertVScale differs is refused. The texture keeps its own UV transform and never copies the source’s, so the V-scale correction is not applied twice.
  • Ownership: a texture replacing itself, two wrappers already sharing the image, and the source disposed afterwards are in the tests. A refused call leaves both textures unchanged, and the doc comment says what false means.

Two things changed while testing it. The class name does not tell the textures apart (render target, procedural and raw textures report "Texture"), so the images themselves are checked: 2D, loaded from a url or a buffer, and ready. And a snapshot in STANDARD mode is recorded again too, not only a FAST one: it binds the new image to the materials but replays the bundles it recorded.

The Playground swaps the images of 300 textures shared by 600 boxes, with frozen materials, and reads the pixels every frame: https://playground.babylonjs.com/#2IS5NN#0 (it needs a build with the PR). On the PR’s build, all 600 boxes show their new images on the first frame after the calls, on WebGL2 and on WebGPU with compatibilityMode on and off and with snapshot rendering in STANDARD and FAST modes, and no material is marked dirty.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

1 Like