Skip to content

ASSET-495: Preserve embedded PNG textures when importing ped GLBs - #5824

Open
Hiiva wants to merge 3 commits into
ItsNotRexed:mainfrom
Hiiva:fix/ped-glb-embedded-textures
Open

Hiiva wants to merge 3 commits into
ItsNotRexed:mainfrom
Hiiva:fix/ped-glb-embedded-textures

Conversation

@Hiiva

@Hiiva Hiiva commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ped_assemble silently dropped every embedded material texture when reading GLB parts. A valid synthetic GLB written by the project's own writer contained three PNG images for base color, normal and metallic/roughness. Reading it returned None for all three MaterialSpec fields, and the actual assembly CLI exited successfully with zero output images or textures.

Change

Resolve the three existing material slots through the texture, image and bufferView tables. For embedded image/png data in GLB buffer 0, preserve the exact PNG bytes after checking both the declared buffer extent and the actual BIN chunk bounds. The existing writer retains its byte-based image deduplication and material factors.

This is limited to the existing embedded PNG path. External image/buffer URIs are not opened, and unsupported image formats retain their previous behavior.

Validation

Windows, Python 3.14.6, current main 561b65a832218fbb9e6d2effd392a8eef093a3f8. Synthetic fixtures only; no game files or GPU.

  • The original five regression methods produce nine failing subcases against unchanged main. They remain covered by the current nine-method texture suite.
  • Actual writer/importer and assembly CLI roundtrips preserve all three PNG slots, material factors, positions and UVs. The CLI output contains three shared images/textures for two materials, and the input remains unchanged.
  • Independent texture/image index permutations and an exact declared-buffer boundary pass. Out-of-bounds and negative embedded-view metadata are rejected.
  • Untextured and external-URI controls preserve existing behavior.
  • Existing ped assembly tests: 14 passed.
  • CI registration: 14 passed. Text-write line endings: 3 passed.
  • Full compileall, make_game.py --help, and git diff --check passed.
  • An independent reviewer inspected the source and tests and reran all five new methods successfully.

Follow-up: reuse embedded PNG payloads within one import

Addresses #5824 (comment).

A per-import cache now shares immutable PNG bytes by validated buffer-0 span across repeated nodes and material slots. All reference, URI and bounds checks still execute before cache lookup. A later import starts with a new cache.

For the reviewer's synthetic 262,548-byte image and 64 nodes, distinct payload copies fall from 64 to one, retained PNG data from 16,803,072 to 262,548 bytes, and live traced Python allocation after import from 16,983,991 to 428,602 bytes. This measures that synthetic import, not total scene memory.

Three added methods cover repeated nodes/shared slots, cache lifetime and validation/URI behavior after a cache hit. Eight texture and 14 existing assembly methods pass; exact #5764 f9e2ff3 combined integration passes eight plus 15. Required compileall/help and diff checks pass. Independent source review and eight-method rerun are clear.

Follow-up: embedded image input contract

At ffc26593, empty embedded buffer views and unsupported texture coordinate references raise contextual PedAssembleError diagnostics before cache lookup. Implicit or explicit texCoord: 0 remains supported. The importer docstring also records the existing repeat/linear/mipmap sampler defaults.

The same final nine-method fixture has four failing subcases at the preceding 782f52a3 head and passes after this change: one empty image and all three texture slots referencing a valid second UV set on a later material. All 14 existing assembly methods pass. The exact #5764 integration now passes nine texture plus 15 assembly methods. Full compileall, make_game help, diff checks and an independent source/evidence review pass.

Coordination and integration

ASSET-495, claimed at #5581 (comment) and carried to #5781.

Adjacent #5764 owns CLI error/output-path handling. Its exact head f9e2ff3ebec61a632a7aed51b57413fa368f196d has separate source hunks; our patch applies cleanly. The latest combined checkout at ffc26593 passes all nine texture methods and all 15 of that PR's ped assembly methods. No dependency on #5764 is needed.

Open #5141 and #5238 affect separate ped-kit/skinned exporters and do not modify this importer.

AI-assisted: yes.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The importer keeps a full copy of the same embedded PNG for each node that uses the mesh. On c17b62e, 64 nodes that reference mesh 0 retain 64 distinct bytes objects for one 262,548-byte base-color image. All copies contain the correct pixels. The copies alone occupy 16,803,072 bytes of payload.

I measured live Python allocations just after read_glb_parts returned on Windows 11, CPython 3.14.7. The 1-, 16-, and 64-node cases retained 273,946, 4,245,295, and 16,974,231 bytes respectively. The input keeps the same image table in all three cases.

To reproduce, run this script from the repository root with py -3.14 -I:

import random
import runpy

t = runpy.run_path("tests/test_ped_glb_textures.py")
c = t["PedGlbTextureTests"]()
c.setUp()
try:
    png = t["dds_png"].encode_png(256, 256, random.Random(5824).randbytes(256*256*4))
    for part in c.parts:
        part.material.base_color_png = png
    t["pa"].write_assembled_glb(str(c.source), c.parts, apply_standing=False)
    doc, buf = t["split_glb"](c.source.read_bytes())
    doc["nodes"] = [{"mesh": 0} for _ in range(64)]
    doc["scenes"] = [{"nodes": list(range(64))}]
    c.source.write_bytes(t["container"](doc, buf))
    parts = t["pa"].read_glb_parts(str(c.source))
    blobs = [p.material.base_color_png for p in parts]
    assert all(b == png for b in blobs)
    print(len(set(map(id, blobs))))  # 64
finally:
    c.doCleanups()

Please cache the immutable PNG bytes by buffer view within one import. Each material can then reuse the same payload. The writer deduplicates images later, after these allocations have occurred.

All 19 importer and assembly tests pass on the head. Parent 561b65a drops the textures and fails nine subcases of the new suite. AI-assisted.

@Kev-Ball

Copy link
Copy Markdown

Round-tripped a 32 MiB material-heavy GLB through the actual assembly CLI on CachyOS. The project’s world writer generated the input from 194 synthetic triangle primitives and textures decoded from my Xbox 1.0.2.1 DDS pool. It contained 192 distinct embedded PNGs and two untextured primitives.

I ran assemble --source-space y-up --no-cull on the same input at parent 561b65a8 and head c17b62ea. Both produced 194 primitives. The parent output contained zero images. The head contained all 192. I independently followed each primitive’s material → base-color texture → image → BIN buffer view in the input and output, and compared SHA-256 of the referenced bytes. All 194 primitive slots matched in order, including the two empty slots.

This covers base-color preservation with many distinct images; the normal and metallic/roughness slots were absent from this input. CPU-only, AI-assisted.

@enzo-billis

Copy link
Copy Markdown
Contributor

Reviewed c17b62e (code read + CPU, Windows 11, Python 3.14.4): works as described, three notes below.

  • python -I tests/test_ped_glb_textures.py: 5 OK; python -I tests/test_ped_assemble.py: 14 OK.
  • Mutation check: main's tools/ped_assemble.py under this PR's tests fails 9 cases, as the description says.
  • 26 hand-built malformed GLBs (bool/float/missing indices, missing tables, negative or oversized bounds, a
    buffer with a uri, a non-PNG mimeType): every case in the new code is a PedAssembleError or the documented
    "leave the slot empty".

Notes, none blocking:

  1. A zero-length image view is imported as an empty PNG. With "byteLength": 0 on the image's bufferView,
    _read_glb_png returns b"", and assemble exits 0 with an image whose bufferView has byteLength 0 (not a
    valid bufferView, and not a PNG). Rejecting length 0 with the other bounds, or checking the 8-byte PNG
    signature, would cover it.
  2. texCoord is not carried. A baseColorTexture with "texCoord": 1 is kept but written back as
    {"index": 0}, so it lands on TEXCOORD_0. Before this PR the texture was absent; now it is present on the
    wrong UV set, with no message. Leaving the slot empty (or refusing) when texCoord != 0 would keep it honest.
  3. The source sampler is replaced by the writer's default (repeat, linear-mipmap); a clamp/nearest input comes
    out as repeat/linear. Fine as a known limit, worth a line in the docstring.

Pre-existing, not from this PR: a material or pbrMetallicRoughness that is not an object, and a BIN chunk
shorter than the accessors need, still raise uncaught AttributeError / struct.error in read_glb_parts.

AI-assisted review.

Cache immutable bytes only after validating each reference so repeated nodes and material slots share one payload without bypassing bounds or URI rules.

AI-assisted: yes.
@Hiiva

Hiiva commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 782f52a37d3cf1438f93d3c92d0c2467a8911f96.

The importer now keeps one immutable PNG payload per validated buffer-0 span for the duration of one import. Every texture/image/view/buffer reference, URI rule and bounds check still runs before cache lookup. Different image identities that use the same span share bytes, and a later import receives its own cache.

I reproduced your exact synthetic PNG and node-count setup on published c17b62e with Python 3.14.6:

Nodes Distinct PNG payloads before / after Live traced bytes before / after
1 1 / 1 278,354 / 278,482
16 16 / 1 4,258,159 / 316,546
64 64 / 1 16,983,991 / 428,602

The 64-node case retains 262,548 bytes of that PNG payload instead of 16,803,072. Geometry and per-node material data still scale with node count.

Three added regression methods cover 64 nodes sharing a PNG across three material slots and different image identities, a changed image at the same span in a later import, and URI/invalid-metadata references encountered after that span has been cached. The repeated-node/shared-slot case fails on c17b62e with 50,409,216 retained payload bytes and passes with 262,548. The existing CLI, material-factor, independent-index and boundary cases remain green.

All eight texture methods and 14 existing ped assembly methods pass. Exact adjacent #5764 f9e2ff3 still applies cleanly; the combined checkout passes eight texture and 15 assembly methods. Full compileall, make_game help and diff checks pass. An independent reviewer inspected the cache placement and reran all eight methods.

Synthetic inputs only, no game files or GPU. AI-assisted: yes.

Validate every embedded PNG reference before cache lookup and document the existing sampler defaults. Keep explicit TEXCOORD_0 roundtrips intact.

AI-assisted: yes.
@Hiiva

Hiiva commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed these input-contract notes in ffc26593d7e09285c602332ac3fbe9db6686883d.

  • Empty embedded image views now raise PedAssembleError with the source path and material slot. This matches the glTF bufferView minimum length of one byte.
  • Supported embedded PNG references require implicit or explicit integer texCoord: 0. A different coordinate set raises a contextual error. The check runs before cache lookup for every reference.
  • The importer docstring records that source sampler settings are not retained and that the writer uses repeat wrapping and linear filtering with mipmaps.

The regression supplies a valid TEXCOORD_1 accessor and checks all three slots on the second material after the first material has populated the image cache. Explicit zero still preserves the original materials and UVs. Together with the empty-view case, the same final fixture has four failing subcases on 782f52a3 and all nine methods passing now. All 14 existing assembly methods pass; exact #5764 f9e2ff3e integration passes nine texture plus 15 assembly methods. Full compileall, make_game help and diff checks pass, with an independent source/evidence review.

The bytes remain opaque PNG payloads; this is bounds and supported-coordinate validation, not a full PNG decoder. Synthetic inputs only, no game files or GPU. AI-assisted: yes.

@whattheflop

Copy link
Copy Markdown
Contributor

AI-assisted Windows CPU verification on ffc26593 with uv CPython 3.12.13. The focused embedded-texture suite passed 9/9.

A repeated-node input gave three parts and nine PNG references with only three distinct Python byte objects, confirming the per-import sharing fix. The actual ped_assemble CLI combined that file with a separate textured GLB and an untextured control. The two files shared two images by content. The result kept all three material texture slots, preserved the second material’s MASK cutoff of 0.33 and double-sided flag, left the control untextured, and stored exactly four distinct images and four textures. All input hashes stayed unchanged.

The probe used valid synthetic GLBs and checked assembly output and ownership on CPU. It did not measure browser or GPU memory.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at c17b62ea21 on Windows 11 / Python 3.13.

  • python -I -m pytest tests/test_ped_glb_textures.py -q: 5 passed, 5 subtests passed.
  • tests/test_ped_assemble.py: 14 passed. tests/test_ci_registration.py: 14 passed, 16 subtests passed.
  • Negative control on 561b65a83: the same new test file is 9 failed / 1 passed (the five regression methods), matching the PR description.
  • Checked the new resolution path: it follows texture -> image -> bufferView -> buffer 0, rejects declared-buffer and BIN-chunk overruns plus negative/non-int metadata, preserves the PNG bytes verbatim, and does not open external URIs. Untextured and external-URI controls keep the old behaviour.

Verdict: LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants