Texture#lock swaps the mip and face indices on cubemaps
Texture#lock looks up cubemap data as _levels[face][level], but cubemap levels are stored as _levels[mip][face]. So lock({ face, level }) on a cubemap only works for face 0 at level 0. Every other face either throws or reads and writes the wrong mip or face.
Where
- The lookup: https://github.com/playcanvas/engine/blob/61d79c09788da1300ee4cfad727743235717f7ef/src/platform/graphics/texture.js#L1219-L1232
- The layout everywhere else,
[mip][face]:_clearLevels(https://github.com/playcanvas/engine/blob/61d79c09788da1300ee4cfad727743235717f7ef/src/platform/graphics/texture.js#L495-L497), the DDS parser (https://github.com/playcanvas/engine/blob/61d79c09788da1300ee4cfad727743235717f7ef/src/framework/parsers/texture/dds.js#L156) and glb-parser (https://github.com/playcanvas/engine/blob/61d79c09788da1300ee4cfad727743235717f7ef/src/framework/parsers/glb-parser.js#L193)
What's wrong
this._lockedMode = options.mode;
this._lockedLevel = options.level;
const levels = this.cubemap ? this._levels[options.face] : this._levels;
if (!levels[options.level]) {
// allocate storage for this mip level
...
levels[options.level] = new (getPixelFormatArrayType(this._format))(data);
}
return levels[options.level];For a cubemap, this._levels[options.face] is the face array of mip face, which is then indexed by level. The face option was documented earlier, but lock only started to use it in #5332 (1.64), with the indices in this order.
Impact
Reproduced on the null device:
| Call | Result |
|---|---|
lock({ face: 3 }) on a new 8x8 cubemap |
TypeError: Cannot read properties of undefined (reading '0'), and the texture stays locked, because _lockedMode is set before the lookup |
lock({ face: 1 }) on a cubemap created with levels: [[f0, ..., f5]] |
the same TypeError |
lock({ face: 0 }) on the same cubemap |
face 0's data (correct) |
lock({ face: 0, level: 1 }) on a new 8x8 cubemap |
returns a 4x4 buffer but stores it in _levels[0][1], the slot for mip 0 of face 1, and mip 1 is never allocated. The next upload then tries to use that 4x4 buffer as face 1's 8x8 top level. |
Fix
For cubemaps, index by mip first, and allocate the face array when a mip level has none yet:
const levels = this._cubemap ? (this._levels[options.level] ??= [null, null, null, null, null, null]) : this._levels;
const index = this._cubemap ? options.face : options.level;Then allocate and return levels[index]. Set _lockedMode and _lockedLevel only once the lookup has succeeded. A test that locks each face of a mipmapped cubemap and checks the slot it lands in would cover it.
Found in passing while triaging texture issues (#4290, #6004).
Source: playcanvas/engine