File size: 10,118 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""RHG-side DDS color conversion, before package sealing or installation."""
import json
from pathlib import Path


def _hdr_dimensions(path):
    import re
    import struct
    if path.suffix.lower() == '.hdr':
        with path.open('rb') as stream:
            header = stream.read(65536)
        match = re.search(rb'([+-][XY])\s+(\d+)\s+([+-][XY])\s+(\d+)', header)
        if not match:
            raise ValueError('Missing Radiance HDR dimensions: ' + str(path))
        axes = {match[1][-1:]: int(match[2]), match[3][-1:]: int(match[4])}
        return axes[b'X'], axes[b'Y']
    with path.open('rb') as stream:
        if stream.read(4) != b'\x76\x2f\x31\x01':
            raise ValueError('Invalid OpenEXR magic: ' + str(path))
        stream.read(4)
        def cstring():
            result = bytearray()
            while True:
                char = stream.read(1)
                if not char:
                    raise ValueError('Truncated OpenEXR header')
                if char == b'\0':
                    return bytes(result)
                result.extend(char)
                if len(result) > 4096:
                    raise ValueError('Invalid OpenEXR attribute name')
        while True:
            name = cstring()
            if not name:
                break
            kind = cstring()
            size = struct.unpack('<I', stream.read(4))[0]
            if size > 16 * 1024**2:
                raise ValueError('Oversized OpenEXR header attribute')
            value = stream.read(size)
            if name == b'dataWindow' and kind == b'box2i' and size == 16:
                xmin, ymin, xmax, ymax = struct.unpack('<4i', value)
                return xmax - xmin + 1, ymax - ymin + 1
    raise ValueError('Missing OpenEXR data window: ' + str(path))


def _encode_asset(job):
    import hashlib
    import os
    import sys
    import PIL
    from PIL import Image
    from .rparena_v16 import sha, intern
    sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts/source_transfer'))
    source_name, space, policy, package_name, shared_name = job
    source, package, shared = map(Path, (source_name, package_name, shared_name))
    with Image.open(source) as header:
        width, height = header.size
    requested_color = space == 'sRGB' and policy == 'bc7'
    # Isaac 6.0.1 rejects BC textures whose base dimensions are not multiples
    # of four, even though a general DDS decoder can read the padded blocks.
    color = requested_color and width % 4 == 0 and height % 4 == 0
    cache_policy = 'png-unaligned-bc7-fallback' if requested_color and not color else policy
    suffix = '.dds' if color else '.png'
    source_digest = sha(source)
    encoder = Path(__file__).resolve().parents[2] / 'scripts/source_transfer/dds_textures.py'
    cache_key = hashlib.sha256(json.dumps(dict(source_sha256=source_digest, space=space,
        policy=cache_policy, encoder_sha256=sha(encoder), pillow=PIL.__version__), sort_keys=True).encode()).hexdigest()
    index_dir = shared / 'texture-encoding-v1'
    index_dir.mkdir(parents=True, exist_ok=True)
    index = index_dir / (cache_key + '.json')
    if index.exists():
        cached = json.loads(index.read_text())
        payload = shared / cached['filename']
        if not payload.is_file() or sha(payload) != cached['sha256']:
            raise ValueError('Encoded texture cache hash mismatch: ' + str(index))
        relative = 'assets/' + cached['filename']
        intern(payload, package / relative, payload)
        return relative
    temporary = package / ('resident-' + source_digest + '-' + str(os.getpid()) + suffix)
    with Image.open(source) as image:
        if color:
            from dds_textures import encode
            temporary.write_bytes(encode(image, 'BC7', True))
        else:
            image.save(temporary, format='PNG')
    identity = sha(temporary)
    relative = 'assets/' + identity + suffix
    intern(temporary, package / relative, shared / (identity + suffix))
    temporary.unlink()
    pending = index.with_name(index.name + '.' + str(os.getpid()) + '.tmp')
    pending.write_text(json.dumps(dict(filename=identity + suffix, sha256=identity,
                                      source_sha256=source_digest), indent=2))
    pending.replace(index)
    return relative


def compress_colors(stage, package, shared, policy):
    from pxr import Sdf, UsdShade
    from PIL import Image
    from .rparena_v16 import sha, intern
    if policy == 'preserve':
        return dict(policy=policy, converted=[], normal_format='PNG')
    if policy not in ('bc7', 'png'):
        raise ValueError('Unknown texture compression policy')
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts/source_transfer'))
    rows = []
    cache = {}
    plans = []
    for prim in stage.Traverse():
        if not prim.IsA(UsdShade.Shader):
            continue
        shader = UsdShade.Shader(prim)
        for attribute in prim.GetAttributes():
            if attribute.GetTypeName() != Sdf.ValueTypeNames.Asset:
                continue
            value = attribute.Get()
            if value is None or not value.path.lower().endswith('.png'):
                continue
            space = attribute.GetColorSpace()
            color_space = shader.GetInput('sourceColorSpace')
            space = color_space.Get() if color_space else space
            # Never compress scalar/normal maps or infer sRGB from a filename.
            source = (package / value.path).resolve()
            if not source.is_relative_to(package.resolve()):
                raise ValueError('Color asset escapes package')
            cache_key = (source, space)
            if cache_key not in cache:
                cache[cache_key] = None
            plans.append((attribute, value.path, cache_key, str(prim.GetPath())))
    import concurrent.futures
    import multiprocessing
    import os
    workers = max(1, min(8, int(os.environ.get('RHG_TEXTURE_COMPRESSION_WORKERS', '4'))))
    keys = list(cache)
    jobs = [(str(source), space, policy, str(package), str(shared)) for source, space in keys]
    # Spawn independent CPU encoders; never fork an initialized USD thread pool.
    with concurrent.futures.ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context('spawn')) as pool:
        for index, (key, relative) in enumerate(zip(keys, pool.map(_encode_asset, jobs))):
            cache[key] = relative
            if index % 16 == 0:
                print(json.dumps(dict(texture_encoding_completed=index+1, total=len(keys), workers=workers)), flush=True)
    for attribute, original, cache_key, shader_path in plans:
            relative = cache[cache_key]
            space = cache_key[1]
            attribute.Set(Sdf.AssetPath(relative))
            rows.append(dict(shader=shader_path, input=attribute.GetName(),
                             original=original, path=relative, format='DDS BC7 sRGB' if relative.endswith('.dds') else 'PNG8',
                             fallback_reason='Isaac BC7 base dimensions must be multiples of 4' if space == 'sRGB' and policy == 'bc7' and relative.endswith('.png') else None,
                             mip_chain=relative.endswith('.dds'), sha256=sha(package / relative)))
    # Only remove superseded files in this new, unsealed package. The source
    # bake and content-addressed shared cache remain immutable.
    live = set()
    for prim in stage.Traverse():
        for attribute in prim.GetAttributes():
            if attribute.GetTypeName() == Sdf.ValueTypeNames.Asset:
                value = attribute.Get()
                if value and value.path.startswith('assets/'):
                    live.add(value.path)
    removed = []
    for source in {key[0] for key in cache}:
        relative = source.relative_to(package.resolve()).as_posix()
        if relative not in live:
            source.unlink()
            removed.append(relative)
    result = dict(policy=policy, encoder_profile='basic', workers=workers, converted=rows, unique_converted_textures=len(cache),
                  removed_superseded_package_files=removed,
                  normal_format='PNG',
                  normal_fallback_reason='BC5 direct sampling failed the frozen 5/255 native USD/RTX probe; no implicit Z reconstruction')
    from texture_budget import mip_bytes
    ledger = []
    for relative in sorted(live):
        path = package / relative
        if path.suffix.lower() not in ('.png', '.dds', '.jpg', '.jpeg', '.exr', '.hdr'):
            continue
        if path.suffix.lower() in ('.exr', '.hdr'):
            size = _hdr_dimensions(path)
            fmt = 'HDR unchanged; RGBA32F reserve'
            resident = 4 * mip_bytes(*size)
        else:
            image = Image.open(path)
            size = image.size
            fmt = 'BC7' if path.suffix.lower() == '.dds' else 'PNG'
            resident = mip_bytes(*size, fmt)
        if min(size) <= 0:
            raise ValueError('Invalid delivered texture dimensions: ' + str(path))
        ledger.append(dict(path=relative, resolution=list(size), format=fmt,
                           estimated_resident_bytes=resident,
                           file_bytes=path.stat().st_size, sha256=sha(path)))
    budget_path = package / 'texture-budget.json'
    if budget_path.exists():
        budget = json.loads(budget_path.read_text())
        budget['source_png_estimated_resident_bytes'] = budget['estimated_resident_bytes']
        budget['estimated_resident_bytes'] = sum(r['estimated_resident_bytes'] for r in ledger)
        budget['delivered_textures'] = ledger
        budget['compression_policy'] = policy
        if budget['estimated_resident_bytes'] > budget['budget_bytes']:
            raise ValueError('Delivered texture allocation exceeds the configured scene budget')
        budget_path.write_text(json.dumps(budget, indent=2))
        result['delivered_estimated_resident_bytes'] = budget['estimated_resident_bytes']
    (package / 'texture-compression.json').write_text(json.dumps(result, indent=2))
    return result