File size: 6,857 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from __future__ import annotations

import json
import shutil
import struct
import subprocess
import tempfile
from pathlib import Path
from typing import Any


_GLB_MAGIC = b"glTF"
_JSON_CHUNK = 0x4E4F534A
_BIN_CHUNK = 0x004E4942
_PNG_MAGIC = b"\x89PNG\r\n\x1a\n"


class BasisuNormalizationError(RuntimeError):
    pass


def _read_glb(path: Path) -> tuple[dict[str, Any], bytes]:
    payload = path.read_bytes()
    if len(payload) < 20 or payload[:4] != _GLB_MAGIC:
        raise BasisuNormalizationError(f"invalid GLB header: {path}")
    version, declared_length = struct.unpack_from("<II", payload, 4)
    if version != 2 or declared_length != len(payload):
        raise BasisuNormalizationError(f"invalid GLB version or length: {path}")
    offset = 12
    document: dict[str, Any] | None = None
    binary = b""
    while offset + 8 <= len(payload):
        chunk_length, chunk_type = struct.unpack_from("<II", payload, offset)
        offset += 8
        end = offset + chunk_length
        if end > len(payload):
            raise BasisuNormalizationError(f"truncated GLB chunk: {path}")
        chunk = payload[offset:end]
        offset = end
        if chunk_type == _JSON_CHUNK:
            loaded = json.loads(chunk.rstrip(b" \t\r\n\0").decode("utf-8"))
            if not isinstance(loaded, dict):
                raise BasisuNormalizationError(f"GLB JSON root is not an object: {path}")
            document = loaded
        elif chunk_type == _BIN_CHUNK:
            binary = chunk
    if document is None:
        raise BasisuNormalizationError(f"GLB has no JSON chunk: {path}")
    return document, binary


def _buffer_view_bytes(document: dict[str, Any], binary: bytes, index: int) -> bytes:
    views = document.get("bufferViews")
    if not isinstance(views, list) or index < 0 or index >= len(views):
        raise BasisuNormalizationError(f"invalid BasisU image bufferView index: {index}")
    view = views[index]
    if not isinstance(view, dict) or int(view.get("buffer", 0)) != 0:
        raise BasisuNormalizationError("BasisU image must use GLB buffer 0")
    start = int(view.get("byteOffset", 0))
    length = int(view.get("byteLength", 0))
    end = start + length
    if start < 0 or length <= 0 or end > len(binary):
        raise BasisuNormalizationError(f"invalid BasisU image buffer range: {start}:{end}")
    return binary[start:end]


def normalize_basisu_glb(source: Path, output_dir: Path, *, ktx_tool: Path) -> Path:
    """Create a Blender-compatible glTF while preserving decoded BasisU textures."""

    source = source.resolve()
    if source.suffix.casefold() != ".glb" or b"KHR_texture_basisu" not in source.read_bytes():
        return source
    if not ktx_tool.is_file():
        raise BasisuNormalizationError(f"KTX tool is missing: {ktx_tool}")
    document, binary = _read_glb(source)
    textures = document.get("textures")
    images = document.get("images")
    if not isinstance(textures, list) or not isinstance(images, list):
        raise BasisuNormalizationError(f"BasisU GLB has no texture/image arrays: {source}")

    basisu_sources: set[int] = set()
    for texture in textures:
        if not isinstance(texture, dict):
            continue
        extensions = texture.get("extensions")
        basisu = extensions.get("KHR_texture_basisu") if isinstance(extensions, dict) else None
        if not isinstance(basisu, dict) or "source" not in basisu:
            continue
        image_index = int(basisu["source"])
        if image_index < 0 or image_index >= len(images):
            raise BasisuNormalizationError(f"invalid BasisU texture source index: {image_index}")
        basisu_sources.add(image_index)
        texture["source"] = image_index
        del extensions["KHR_texture_basisu"]
        if not extensions:
            texture.pop("extensions", None)
    if not basisu_sources:
        raise BasisuNormalizationError(f"BasisU extension declared without textures: {source}")

    output_dir = output_dir.resolve()
    output_dir.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=f".{output_dir.name}-", dir=output_dir.parent) as raw:
        staging = Path(raw)
        (staging / "buffer.bin").write_bytes(binary)
        for image_index in sorted(basisu_sources):
            image = images[image_index]
            if not isinstance(image, dict) or "bufferView" not in image:
                raise BasisuNormalizationError(
                    f"BasisU image {image_index} is not embedded in a bufferView"
                )
            encoded = staging / f"texture_{image_index:03d}.ktx2"
            decoded = staging / f"texture_{image_index:03d}.png"
            encoded.write_bytes(
                _buffer_view_bytes(document, binary, int(image["bufferView"]))
            )
            completed = subprocess.run(
                [
                    str(ktx_tool.resolve()),
                    "extract",
                    "--transcode",
                    "rgba8",
                    "--testrun",
                    str(encoded),
                    str(decoded),
                ],
                check=False,
                capture_output=True,
                text=True,
                timeout=120,
            )
            if completed.returncode or not decoded.is_file():
                raise BasisuNormalizationError(
                    f"KTX decode failed for image {image_index}: "
                    f"{(completed.stdout + completed.stderr)[-1000:]}"
                )
            if not decoded.read_bytes().startswith(_PNG_MAGIC):
                raise BasisuNormalizationError(f"KTX decoder did not produce PNG: {decoded}")
            encoded.unlink()
            images[image_index] = {
                **({"name": image["name"]} if isinstance(image.get("name"), str) else {}),
                "uri": decoded.name,
                "mimeType": "image/png",
            }

        buffers = document.get("buffers")
        if not isinstance(buffers, list) or not buffers or not isinstance(buffers[0], dict):
            raise BasisuNormalizationError(f"GLB has no buffer declaration: {source}")
        buffers[0]["uri"] = "buffer.bin"
        buffers[0]["byteLength"] = len(binary)
        for key in ("extensionsRequired", "extensionsUsed"):
            values = document.get(key)
            if isinstance(values, list):
                document[key] = [value for value in values if value != "KHR_texture_basisu"]
                if not document[key]:
                    document.pop(key)
        (staging / "asset.gltf").write_text(
            json.dumps(document, ensure_ascii=False, separators=(",", ":")),
            encoding="utf-8",
        )
        if output_dir.exists():
            shutil.rmtree(output_dir)
        staging.rename(output_dir)
    return output_dir / "asset.gltf"