152 lines
7.6 KiB
Python
152 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Recover supplied 3DS Max ASE mesh animation samples into OMT coordinates."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
|
|
from omt import FormatError
|
|
|
|
NUMBER = r'[-+\d.eE]+'
|
|
|
|
|
|
def blocks(text: str, tag: str):
|
|
for match in re.finditer(r'\*'+re.escape(tag)+r'\s*\{', text):
|
|
start, depth = match.end(), 1
|
|
cursor = start
|
|
while cursor < len(text) and depth:
|
|
if text[cursor] == '{': depth += 1
|
|
elif text[cursor] == '}': depth -= 1
|
|
cursor += 1
|
|
if depth: raise FormatError(f'Unclosed {tag} block')
|
|
yield match.start(), text[start:cursor-1]
|
|
|
|
|
|
def vector_table(text: str, tag: str):
|
|
values = {}
|
|
pattern = r'\*'+tag+r'\s+(\d+)\s+('+NUMBER+r')\s+('+NUMBER+r')\s+('+NUMBER+r')'
|
|
for match in re.finditer(pattern, text):
|
|
index = int(match[1])
|
|
if index in values: raise FormatError(f'Duplicate {tag} index {index}')
|
|
values[index] = tuple(float(match[i]) for i in (2,3,4))
|
|
if set(values) != set(range(len(values))): raise FormatError(f'Noncontiguous {tag} indices')
|
|
if any(not math.isfinite(v) for p in values.values() for v in p): raise FormatError('Nonfinite ASE value')
|
|
return [values[i] for i in range(len(values))]
|
|
|
|
|
|
def read_mesh(text: str) -> dict:
|
|
vertices = vector_table(text, 'MESH_VERTEX')
|
|
tvertices = vector_table(text, 'MESH_TVERT')
|
|
faces, tfaces = {}, {}
|
|
for match in re.finditer(r'\*MESH_FACE\s+(\d+):\s+A:\s*(\d+)\s+B:\s*(\d+)\s+C:\s*(\d+)', text):
|
|
faces[int(match[1])] = tuple(int(match[i]) for i in (2,3,4))
|
|
for match in re.finditer(r'\*MESH_TFACE\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)', text):
|
|
tfaces[int(match[1])] = tuple(int(match[i]) for i in (2,3,4))
|
|
for key, count in (('MESH_NUMVERTEX',len(vertices)),('MESH_NUMFACES',len(faces))):
|
|
match = re.search(r'\*'+key+r'\s+(\d+)', text)
|
|
if not match or int(match[1]) != count: raise FormatError(f'{key} does not match data')
|
|
if set(faces) != set(range(len(faces))): raise FormatError('Noncontiguous face indices')
|
|
if tfaces and set(tfaces) != set(faces): raise FormatError('Texture faces do not match faces')
|
|
if any(i>=len(vertices) for face in faces.values() for i in face): raise FormatError('ASE vertex outside table')
|
|
if any(i>=len(tvertices) for face in tfaces.values() for i in face): raise FormatError('ASE UV outside table')
|
|
time = re.search(r'\*TIMEVALUE\s+(-?\d+)',text)
|
|
return {'time': int(time[1]) if time else 0,
|
|
'vertices': [(x,z,y) for x,y,z in vertices],
|
|
'uvs': [(u,-v) for u,v,_ in tvertices],
|
|
'faces': [faces[i] for i in range(len(faces))],
|
|
'textureFaces': [tfaces[i] for i in range(len(tfaces))] if tfaces else []}
|
|
|
|
|
|
def read_ase(path: Path | str) -> dict:
|
|
path = Path(path)
|
|
data = path.read_bytes()
|
|
text = data.decode('latin1')
|
|
if not text.lstrip().startswith('*3DSMAX_ASCIIEXPORT'): raise FormatError('Expected ASE signature')
|
|
objects = []
|
|
for _, geom in blocks(text, 'GEOMOBJECT'):
|
|
name = re.search(r'\*NODE_NAME\s+"([^"]+)"', geom)
|
|
meshes = []
|
|
animations = list(blocks(geom, 'MESH_ANIMATION'))
|
|
if animations:
|
|
for _, animation in animations: meshes.extend(read_mesh(body) for _,body in blocks(animation,'MESH'))
|
|
else: meshes = [read_mesh(body) for _,body in blocks(geom,'MESH')]
|
|
objects.append({'name': name[1] if name else '', 'samples': meshes})
|
|
if not objects: raise FormatError('No geometry in ASE')
|
|
def setting(name):
|
|
match = re.search(r'\*'+name+r'\s+(\d+)',text)
|
|
if not match: raise FormatError(f'Missing ASE scene setting {name}')
|
|
return int(match[1])
|
|
return {'source':path.name, 'sha256':hashlib.sha256(data).hexdigest(),
|
|
'framesPerSecond':setting('SCENE_FRAMESPEED'),
|
|
'ticksPerFrame':setting('SCENE_TICKSPERFRAME'), 'objects':objects,
|
|
'coordinates':'(ASE x,z,y), texture (u,-v); matched OMT duplicate assets'}
|
|
|
|
|
|
def expand_mesh(mesh: dict) -> dict:
|
|
result = {'vertices':[], 'uvs':[], 'indices':[], 'normals':[]}
|
|
for face_index, face in enumerate(mesh['faces']):
|
|
a,b,c = [mesh['vertices'][i] for i in face]
|
|
ab,ac = [b[i]-a[i] for i in range(3)], [c[i]-a[i] for i in range(3)]
|
|
normal = [ab[1]*ac[2]-ab[2]*ac[1], ab[2]*ac[0]-ab[0]*ac[2], ab[0]*ac[1]-ab[1]*ac[0]]
|
|
length = math.sqrt(sum(v*v for v in normal))
|
|
normal = [v/length for v in normal] if length else [0.,0.,0.]
|
|
for corner,index in enumerate(face):
|
|
result['indices'].append(len(result['vertices']))
|
|
result['vertices'].append(mesh['vertices'][index])
|
|
result['uvs'].append(mesh['uvs'][mesh['textureFaces'][face_index][corner]] if mesh['textureFaces'] else [0.,0.])
|
|
result['normals'].append(normal)
|
|
return result
|
|
|
|
|
|
def export_ase(path: Path, output: Path, base_path: Path | None = None):
|
|
if output.resolve().is_relative_to(path.parent.resolve()) or path.resolve().is_relative_to(output.resolve()):
|
|
raise ValueError('Output must be separate from original inputs')
|
|
animation = read_ase(path)
|
|
base_animation = read_ase(base_path) if base_path else None
|
|
if base_animation and len(base_animation['objects']) != len(animation['objects']):
|
|
raise FormatError('Morph base and animation object counts differ')
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
frames = []
|
|
for object_index,item in enumerate(animation['objects']):
|
|
for sample in item['samples']:
|
|
if base_animation:
|
|
base = base_animation['objects'][object_index]['samples'][0]
|
|
if len(base['vertices']) != len(sample['vertices']):
|
|
raise FormatError('Morph sample vertex count differs from base shape')
|
|
# Original OMedia3DMorphAnim supplies only per-index vectors to a
|
|
# base shape; its polygon/UV topology remains unchanged.
|
|
sample = {**sample, 'faces':base['faces'], 'textureFaces':base['textureFaces'],
|
|
'uvs':base['uvs']}
|
|
if not sample['textureFaces']:
|
|
raise FormatError('Mesh has no UVs; supply --base with the original textured morph base')
|
|
filename = f"frame_{len(frames):04d}.json"
|
|
mesh = expand_mesh(sample)
|
|
mesh['meshes'] = [{'name': item['name'],'firstIndex':0,'indexCount':len(mesh['indices']),'material':-1}]
|
|
(output/filename).write_text(json.dumps(mesh,separators=(',',':'))+'\n', encoding='utf-8')
|
|
frames.append({'node':item['name'],'time':sample['time'], 'path':filename})
|
|
manifest = {key:value for key,value in animation.items() if key != 'objects'}
|
|
manifest['frames'] = frames
|
|
if base_animation:
|
|
manifest['morphBase'] = {'source':base_animation['source'], 'sha256':base_animation['sha256'],
|
|
'mode':'Original base topology and UV, sample positions by vertex index'}
|
|
manifest['normalMode'] = 'Flat normals reconstructed from geometry; original smoothing not yet replicated'
|
|
(output/'animation.json').write_text(json.dumps(manifest,indent=2)+'\n', encoding='utf-8')
|
|
return manifest
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('ase',type=Path)
|
|
p.add_argument('--output',type=Path,required=True)
|
|
p.add_argument('--base',type=Path,help='Original textured shape whose topology a morph retains')
|
|
args = p.parse_args()
|
|
manifest = export_ase(args.ase,args.output,args.base)
|
|
print(f"{manifest['source']}: {len(manifest['frames'])} samples at {manifest['framesPerSecond']} fps")
|
|
|
|
|
|
if __name__ == '__main__': main()
|