RoboHome / code /robohome /src /engine /tests /test_gravity_settle_v2.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame
7.53 kB
"""Real CPU Bullet regressions; fixtures are synthetic, never acceptance evidence.
Run on H200 with RHG_GRAVITY_BLENDER=/absolute/local/blender python3 -B -m
unittest discover -s tests -p test_gravity_settle_v2.py -v.
"""
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
RUNNER = ROOT / 'real_test/gravity_settle_v2.py'
BLENDER = os.environ.get('RHG_GRAVITY_BLENDER', '')
FIXTURE = r'''
import bpy, json, sys
from pathlib import Path
root, scenario = Path(sys.argv[-2]), sys.argv[-1]
bpy.ops.wm.read_factory_settings(use_empty=True)
def cube(name, location, scale, entity):
bpy.ops.mesh.primitive_cube_add(size=1, location=location)
obj = bpy.context.object
obj.name = name
obj.scale = scale
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
obj['entity_id'] = entity
return obj
if scenario == 'hole':
for x,y,sx,sy in [(-.6,0,.8,2),(.6,0,.8,2),(0,-.6,.4,.8),(0,.6,.4,.8)]:
cube('ring', (x,y,.9), (sx,sy,.2), 'support')
else:
cube('support', (0,0,.9), (2,2,.2), 'support')
z = 1.05 if scenario == 'penetration' else 1.3
child = cube('prop', (0,0,z), (.2,.2,.2), 'prop')
if scenario == 'open':
import bmesh
bm = bmesh.new(); bm.from_mesh(child.data)
bmesh.ops.delete(bm, geom=[max(bm.faces, key=lambda f:f.normal.z)], context='FACES')
bm.to_mesh(child.data); bm.free()
cube('wall', (1.2,0,1.5), (.1,3,3), None)
bpy.ops.object.light_add(type='AREA', location=(0,0,3))
bpy.ops.object.camera_add(location=(3,3,3))
bpy.ops.wm.save_as_mainfile(filepath=str(root/'fixture.blend'))
(root/'manifest.json').write_text(json.dumps(dict(scene_id='fixture', entities=[
dict(entity_id='prop',role='cup',supported_by_entity_id='support'),
dict(entity_id='support',role='table') ])))
'''
@unittest.skipUnless(BLENDER and Path(BLENDER).is_file(), 'Set RHG_GRAVITY_BLENDER for actual CPU Bullet tests')
class GravityBulletTests(unittest.TestCase):
def run_scenario(self, scenario, *, invalid_support=False):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
root = Path(temporary.name)/'saved'
root.mkdir()
fixture = subprocess.run([BLENDER, '--background', '--factory-startup', '--disable-autoexec',
'--threads', '2', '--python-expr', FIXTURE, '--', str(root), scenario],
text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=45)
self.assertEqual(fixture.returncode, 0, fixture.stdout)
if invalid_support:
path = root/'manifest.json'
manifest = json.loads(path.read_text())
manifest['entities'][0]['support_entity_id'] = 'other'
path.write_text(json.dumps(manifest))
pins = {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in (root/'fixture.blend', root/'manifest.json')}
output = root.parent/'evidence/report.json'
run = subprocess.run([BLENDER, '--background', '--factory-startup', '--disable-autoexec',
'--threads', '2', '--python-exit-code', '1', '--python', str(RUNNER), '--',
'--scene', str(root/'fixture.blend'), '--manifest', str(root/'manifest.json'),
'--entity-id', 'prop', '--mass-kg', '.3', '--frames', '181', '--output', str(output)],
text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
self.assertTrue(output.is_file(), 'Missing real engine report: '+run.stdout)
report = json.loads(output.read_text())
self.assertEqual(pins, {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in (root/'fixture.blend', root/'manifest.json')})
self.assertTrue(report['source_unchanged'])
self.assertFalse(report['physics_qualified'])
self.assertFalse(report['source_blend_saved'])
return report, run
def test_actual_bullet_drop_trace_and_settle(self):
report, run = self.run_scenario('drop')
self.assertEqual(run.returncode, 0, run.stdout)
self.assertEqual(report['engine']['name'], 'Blender/Bullet')
self.assertTrue(report['engine_executed'])
self.assertEqual(len(report['trajectory']), 181)
self.assertLess(report['trajectory'][12]['position_m'][2], report['trajectory'][0]['position_m'][2]-.02)
self.assertGreater(max(row['linear_speed_m_s'] for row in report['trajectory']), .1)
self.assertTrue(report['settling_passed'], report.get('failures'))
self.assertFalse(report['initial_placement_passed'])
self.assertGreater(report['after']['support_contact_samples'], 0)
self.assertLess(report['summary']['final_window_max_linear_speed_m_s'], .02)
self.assertEqual(report['summary']['fixed_body_max_translation_drift_m'], 0.)
self.assertEqual(report['summary']['fixed_body_max_rotation_drift_rad'], 0.)
self.assertEqual(report['saved_nonmesh_objects_untouched'], 2)
self.assertTrue(all(r['type']=='PASSIVE' for r in report['colliders'] if r['entity_id']!='prop'))
self.assertTrue(all(r['collision_shape']=='MESH' for r in report['colliders']))
def test_real_mesh_hole_is_not_filled_by_bbox_or_convex_hull(self):
report, run = self.run_scenario('hole')
self.assertNotEqual(run.returncode, 0)
self.assertTrue(report['engine_executed'])
self.assertFalse(report['settling_passed'])
self.assertEqual(report['after']['support_contact_samples'], 0)
self.assertLess(report['trajectory'][-1]['position_m'][2], 0)
def test_initial_intersection_is_diagnosed_and_not_accepted(self):
report, _ = self.run_scenario('penetration')
self.assertGreater(report['before']['triangle_surface_intersections'], 0)
self.assertFalse(report['initial_placement_passed'])
def test_open_dynamic_mesh_cannot_claim_fidelity(self):
report, run = self.run_scenario('open')
self.assertNotEqual(run.returncode, 0)
self.assertFalse(report['collider_fidelity_verified'])
self.assertFalse(report['settling_passed'])
self.assertIn('dynamic_mesh_not_closed_or_consistently_oriented', report['failures'])
def test_ambiguous_manifest_support_rejected_without_engine(self):
report, run = self.run_scenario('drop', invalid_support=True)
self.assertNotEqual(run.returncode, 0)
self.assertFalse(report['engine_executed'])
self.assertIn('ambiguous support', report['error'])
def test_tiny_angular_velocity_and_quaternion_sign(self):
code = r'''
import importlib.util, math
from mathutils import Quaternion
spec = importlib.util.spec_from_file_location('gravity', RUNNER)
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
before = Quaternion((1,0,0,0))
after = Quaternion((math.cos(5e-7),0,0,math.sin(5e-7)))
speed = module.angular_speed(before, after, 60)
assert abs(speed-6e-5) < 1e-7, speed
assert module.angular_speed(before, Quaternion((-1,0,0,0)), 60) == 0
'''.replace('RUNNER', repr(str(RUNNER)))
run = subprocess.run([BLENDER, '--background', '--factory-startup', '--disable-autoexec',
'--threads', '2', '--python-exit-code', '1', '--python-expr', code],
text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout)
if __name__ == '__main__':
unittest.main()