Files

95 lines
4.3 KiB
Python

"""Extract the original male Gnome's skin-colored bald crown for atlas projection."""
import argparse
from hashlib import sha256
from pathlib import Path
import struct
from m2_format_compare import model, skin
SOURCE_MODEL = '80040efa187e3f2db684923ac6119d1cae87fe8edf7384c25e724451f50d642c'
def crown_triangles(raw):
"""Return packed float32 XYZ and UV at each triangle corner, in source winding order."""
if sha256(raw).hexdigest() != SOURCE_MODEL:
raise ValueError('Expected the original male Gnome model')
parsed = model(raw)
side = skin(parsed)
sections = list(struct.iter_unpack('<10H3f', side['arrays'][3]))
section_id, = [i for i, section in enumerate(sections) if section[0] == 1]
batches = [row for row in side['summary']['batch_rows'] if row[3] == section_id]
texture_count, textures_at = struct.unpack_from('<II', raw, 92)
lookup_count, lookup_at = struct.unpack_from('<II', raw, 148)
for row in batches:
if row[9] >= lookup_count:
raise ValueError('Invalid crown texture lookup')
texture, = struct.unpack_from('<H', raw, lookup_at + 2*row[9])
if texture >= texture_count or struct.unpack_from('<I', raw, textures_at + 16*texture)[0] != 1:
raise ValueError('Expected a body texture on the bald scalp')
if not batches:
raise ValueError('Bald scalp is missing its material')
section = sections[section_id]
start, count = (section[1] << 16) + section[4], section[5]
indices = side['arrays'][0]
corners = struct.unpack_from(f'<{count}H', side['arrays'][1], start*2)
result = bytearray()
for corner in corners:
index, = struct.unpack_from('<H', indices, 2*corner)
vertex = parsed['vertices'][index]
result.extend(vertex[:12])
result.extend(vertex[32:40])
return bytes(result)
def project_colors(destination, source, weights, visible, reference_rgb, face_rgb, guarded):
"""Project the visible source crown onto its HD face while keeping HD surface detail.
Each correspondence contains a flat 512-square destination index, a flat
128-by-96 source index and a depth-agreement weight. Visible counts include
samples where the HD surface had no corresponding source crown.
"""
import numpy as np
if face_rgb.shape != (512, 512, 3) or reference_rgb.shape != (96, 128, 3):
raise ValueError('Expected 70334 HD face and original upper/lower face layers')
if visible.shape != (512, 512) or guarded.shape != visible.shape:
raise ValueError('Mesh masks must cover the HD face atlas')
if (destination.shape != source.shape or weights.shape != source.shape or not source.size
or np.any((destination < 0) | (destination >= 512**2))
or np.any((source < 0) | (source >= 128*96))
or not np.all(np.isfinite(weights) & (weights >= 0))):
raise ValueError('Invalid crown correspondences')
def smooth(grid, sigma):
radius = round(4*sigma)
kernel = np.exp(-.5*(np.arange(-radius, radius+1)/sigma)**2)
kernel /= sum(kernel)
for axis in (0, 1):
padding = [(0, 0)] * grid.ndim
padding[axis] = (radius, radius)
padded = np.pad(grid, padding, mode='symmetric')
indices = np.arange(grid.shape[axis])
grid = sum(w*np.take(padded, indices+j, axis=axis) for j, w in enumerate(kernel))
return grid
def scatter(samples):
values = np.bincount(destination, weights=weights*samples[source], minlength=512**2)
return smooth(values.reshape(512, 512), 1.7)
mass = scatter(np.ones(128*96))
confidence = np.clip(mass / np.maximum(smooth(visible, 1.7)*.38, .01), 0, 1)
confidence[guarded] = 0
mapped = np.stack([scatter(v) for v in reference_rgb.reshape(-1, 3).T], axis=2)
mapped /= np.maximum(1.e-8, mass[:, :, None])
base = face_rgb.astype(float)
delta = mapped - smooth(base, 2)
return np.rint(base + delta*confidence[:, :, None]).clip(0, 255).astype('uint8')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original_m2', type=Path)
parser.add_argument('output_xyz_uv', type=Path)
args = parser.parse_args()
args.output_xyz_uv.write_bytes(crown_triangles(args.original_m2.read_bytes()))