Files
Neutron/tests/test_scooter_resources.py

132 lines
8.4 KiB
Python

"""Exact original Scooter resources, material links and source-pivot expansion."""
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
sys.path.insert(0, str(ROOT/'tools/binary'))
from scooter_resources import (CANVASES, CLIPS, JIMMY_RGBA_SHA256, SOURCES, export_scooter)
from ase import expand_mesh, read_ase
from entities import resolve_asset
from omt import Database, FormatError, read_canvas, read_shape
from pe_inspect import PE
from checkpoint_script_state import read_va
@unittest.skipUnless(ORIGINAL.exists(), 'Original resources are local fixtures')
class ScooterResourceTests(unittest.TestCase):
def test_exact_omt_shapes_canvas_pixels_and_material_links(self):
with tempfile.TemporaryDirectory() as directory:
out = Path(directory)/'scooter'; manifest = export_scooter(ORIGINAL, out)
self.assertEqual(manifest, json.loads((out/'scooter.json').read_text()))
self.assertEqual(manifest['sources'], SOURCES)
for id_, name, offset, size, width, height, digest in CANVASES:
self.assertEqual(hashlib.sha256((out/f'canvas_{id_}.rgba').read_bytes()).hexdigest(), digest)
self.assertEqual((out/f'canvas_{id_}.rgba').stat().st_size, width*height*4)
body = json.loads((out/manifest['bodyMesh']).read_text())
wheel = json.loads((out/manifest['wheelMesh']).read_text())
self.assertEqual((len(body['vertices']), len(body['indices'])), (176*3, 176*3))
self.assertEqual((len(wheel['vertices']), len(wheel['indices'])), (56*3, 56*3))
for mesh in (body, wheel):
self.assertEqual({m['id']:m['texture']['id'] for m in mesh['materials']}, {0:1,1:0})
self.assertTrue(all((out/Path(manifest['bodyMesh']).parent/t['path']).is_file() for t in mesh['textures']))
self.assertEqual([s['materialPolygons'] for s in manifest['shapes']], [{'0':176},{'1':28,'null':28}])
self.assertEqual(sum(p['materialId'] is None for p in wheel['collisionPolygons']),28)
def test_original_mesh_pivots_vertices_uvs_normals_and_null_draws_preserved(self):
database = Database(resolve_asset(ORIGINAL, 'omt/scooter.omt'))
with tempfile.TemporaryDirectory() as directory:
out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out)
for metadata in m['shapes']:
entry=next(e for e in database.entries if e.type=='3DSh' and e.id==metadata['shapeId'])
source=read_shape(database.payload(entry));actual=json.loads((out/metadata['path']).read_text())
expected_vertices=[];expected_uvs=[];expected_normals=[]
for poly in source['polygons']:
for corner in poly['corners']:
expected_vertices.append(list(source['vertices'][corner['vertex']]))
expected_uvs.append(list(corner['uv']))
ni=corner['normal'];expected_normals.append(list(source['normals'][ni] if ni<len(source['normals']) else poly['normal']))
self.assertEqual(actual['vertices'],expected_vertices)
self.assertEqual(actual['uvs'],expected_uvs)
self.assertEqual(actual['normals'],expected_normals)
self.assertEqual(actual['indices'],list(range(len(expected_vertices))))
wheel=json.loads((out/m['wheelMesh']).read_text())
self.assertEqual(sum(d['indexCount'] for d in wheel['meshes'] if d['material']==-1),28*3)
def test_stored_source_spheres_are_not_actor_radius_or_visual_scale(self):
with tempfile.TemporaryDirectory() as directory:
m=export_scooter(ORIGINAL,Path(directory)/'scooter')
body,wheel=m['shapes']
self.assertEqual(body['storedSphere']['radius'],91.31170654296875)
self.assertEqual(wheel['storedSphere']['radius'],23.769514083862305)
self.assertEqual(body['storedSphere']['sourceRadiusOffset'],124)
self.assertEqual(wheel['storedSphere']['sourceRadiusOffset'],92324)
self.assertNotIn('actorScale',m['bindings'])
self.assertEqual(m['bindings']['bodyDatabaseShape'],0)
self.assertEqual(m['bindings']['wheelDatabaseShape'],1)
def test_two_rider_morphs_keep_exact_samples_topology_and_opaque_atlas(self):
base=read_ase(resolve_asset(ORIGINAL,'ASE/jimstop.ASE'))['objects'][0]['samples'][0]
with tempfile.TemporaryDirectory() as directory:
out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out)
self.assertEqual(hashlib.sha256((out/'jimycarl.rgba').read_bytes()).hexdigest(),JIMMY_RGBA_SHA256)
for stem in CLIPS:
animation=json.loads((out/stem/'animation.json').read_text())
self.assertEqual([f['time'] for f in animation['frames']],[0,480])
self.assertEqual(animation['texture']['path'],'../jimycarl.rgba')
source=read_ase(resolve_asset(ORIGINAL,f'ASE/{stem}.ASE'))['objects'][0]['samples']
for sample,frame in zip(source,animation['frames'],strict=True):
expected=expand_mesh({**sample,'faces':base['faces'],'textureFaces':base['textureFaces'],'uvs':base['uvs']})
actual=json.loads((out/stem/frame['path']).read_text())
self.assertEqual(actual['vertices'],[list(p) for p in expected['vertices']])
self.assertEqual(actual['uvs'],[list(p) for p in expected['uvs']])
self.assertEqual(actual['indices'],expected['indices'])
self.assertEqual((len(m['levels'][0]['entities']),len(m['levels'][1]['entities'])),(18,322))
self.assertEqual(m['goddardTransformation']['indexedVertices'],195)
self.assertEqual(m['goddardTransformation']['sourceTimes'],[0,161])
def test_original_binding_spans_and_alias_string_operands(self):
pe=PE(resolve_asset(ORIGINAL,'Neutron.exe'))
expected=[(0x4214f0,37,'3aa8cb83c0e81fa70622d540015517ecd60549945ace69b6cfe9357641dbd19b'),
(0x422c58,40,'92f233fbba67cc7eb63d29614f6d8a04da703169b91b86e53b36ee5d722b2929'),
(0x41cdf0,20,'1a0e33a555990de9d997d9fe5dc33af242c3994681e511b3b6f5134857659b82'),
(0x468270,42,'cacdf3e512e808601f753b22504a553da79de578b0a792a322ee43966119a838')]
for va,length,digest in expected:
self.assertEqual(hashlib.sha256(read_va(pe,va,length)).hexdigest(),digest)
self.assertEqual(pe.offset(va-pe.base),va-0x400000)
for va,string in [(0x4ef104,b'jimscooter.ase\0'),(0x4ef0f0,b'Jimscooterstop.ase\0'),
(0x4ee9ec,b'HISCOOT\0'),(0x4ef0e4,b'HISCOOTSTOP\0'),(0x4ee9f4,b'godscooter.ASE\0')]:
self.assertEqual(read_va(pe,va,len(string)),string)
def test_changed_original_or_contract_rejects_before_output(self):
with tempfile.TemporaryDirectory() as directory:
out=Path(directory)/'scooter'
with patch.dict(SOURCES,{'omt/scooter.omt':'0'*64}):
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
self.assertFalse(out.exists())
with tempfile.TemporaryDirectory() as directory:
out=Path(directory)/'scooter'
with patch('scooter_resources.CANVASES',((0,'changed',22568,3966,32,32,'0'*64),)):
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
self.assertFalse(out.exists())
def test_original_and_generated_symlink_paths_rejected(self):
for destination in (ORIGINAL, ORIGINAL/'ASE/generated', ORIGINAL.parent):
with self.assertRaises(ValueError):export_scooter(ORIGINAL,destination)
with tempfile.TemporaryDirectory() as directory:
out=Path(directory)/'scooter';out.mkdir();(out/'linked').symlink_to(ORIGINAL,target_is_directory=True)
with self.assertRaises(ValueError):export_scooter(ORIGINAL,out)
def test_export_is_deterministic(self):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);export_scooter(ORIGINAL,root/'a');export_scooter(ORIGINAL,root/'b')
a={str(p.relative_to(root/'a')):p.read_bytes() for p in (root/'a').rglob('*') if p.is_file()}
b={str(p.relative_to(root/'b')):p.read_bytes() for p in (root/'b').rglob('*') if p.is_file()}
self.assertEqual(a,b)