File size: 14,129 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""Material continuity contracts using the native selection/application schema."""
import copy
import hashlib
import importlib.util
import json
import json
from pathlib import Path
import tempfile
import unittest
import sys
from unittest import mock


def api():
    path = Path(__file__).resolve().parents[1] / 'material_plan.py'
    if not path.exists():
        raise AssertionError('material_plan API is not implemented')
    spec = importlib.util.spec_from_file_location('isolated_material_plan', path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


class MaterialPlanTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.rooms = [{'room_id': 'living', 'room_type': 'living_room'},
                      {'room_id': 'bath', 'room_type': 'bathroom'}]
        roles, deps = {}, {}
        for role in ('interior_wall', 'door_leaf', 'door_frame', 'floor_dry', 'floor_wet'):
            identity = 'door' if role.startswith('door_') else role
            channels = {}
            for channel in ('baseColor', 'roughness', 'normal'):
                path = self.root / (identity + '_' + channel)
                path.write_bytes((identity + channel).encode())
                sha = hashlib.sha256(path.read_bytes()).hexdigest()
                channels[channel] = {'source_path': str(path), 'sha256': sha,
                                     'color_space': 'sRGB' if channel == 'baseColor' else 'raw'}
                deps[str(path)] = sha
            roles[role] = {'material_id': identity, 'family_id': identity,
                           'material_revision': identity + '-r1', 'channels': channels,
                           'required_channels': list(channels),
                           'stable_surface_suite': 'dwelling_' + identity + '_suite',
                           'uv_policy': 'world_box_metres', 'texture_scale_m': [1, 1],
                           'texture_scale_provenance': 'declared_engineering_mapping',
                           'normal_convention': 'OpenGL',
                           'normal_convention_provenance': 'provider_NormalGL'}
        self.structural = {'schema': 'rhg.structural_material_manifest.v1',
                           'scene_id': 'house', 'roles': roles,
                           'room_floor_roles': {'living': 'floor_dry', 'bath': 'floor_wet'},
                           'source_dependency_sha256': deps, 'assignments': [],
                           'furniture_materials_modified': False}
        for role, room in [('interior_wall', None), ('door_leaf', None),
                           ('door_frame', None), ('floor_dry', 'living'), ('floor_wet', 'bath')]:
            self.structural['assignments'].append({
                'role': role, 'room_id': room, 'object_name': 'floor__' + room if room else role,
                'material_slot_index': 0, 'material_id': roles[role]['material_id'],
                'family_id': roles[role]['family_id'], 'uv_policy': 'world_box_metres',
                'texture_scale_m': [1, 1]})
        self.manifest = {'floor_plan': {'rooms': self.rooms},
                         'structural_materials': self.structural,
                         'entities': [{'entity_id': 'sofa', 'material_id': 'original-fabric'}]}

    def compile(self, policy=None):
        return api().compile_material_plan(self.manifest, policy)

    def audit(self, structural=None, plan=None):
        return api().audit_material_plan(self.compile() if plan is None else plan,
                                         self.structural if structural is None else structural,
                                         self.root)

    def codes(self, report, field='issues'):
        return {row['code'] for row in report[field]}

    def test_preserves_selected_suite_and_inputs_deterministically(self):
        before = copy.deepcopy(self.manifest)
        plan = self.compile()
        self.assertEqual(plan['selected_suites'], self.structural['roles'])
        self.assertEqual(plan, self.compile())
        self.assertEqual(self.manifest, before)
        self.assertTrue(self.audit()['passed'])
        self.assertEqual(plan['schema'], 'rhg.wholehouse-material-plan.v1')
        json.dumps(plan, allow_nan=False)
        self.assertFalse(self.audit()['visual_fidelity_proven'])

    def test_wrong_floor_role_rejected_even_if_material_matches(self):
        self.structural['assignments'][-1]['role'] = 'floor_dry'
        self.assertIn('floor_role_mismatch', self.codes(self.audit()))

    def test_missing_selection_is_unknown_instead_of_invented_contradiction(self):
        plan = api().compile_material_plan(dict(floor_plan=dict(rooms=self.rooms), entities=[]))
        self.assertFalse(plan['passed'])
        self.assertFalse(plan['issues'])
        self.assertIn('floor_assignments_unknown', self.codes(plan, 'unknowns'))

    def generated_audit(self, *, change_furniture=False, stale=False, missing=False):
        from engine.wholehouse_pipeline import _audit_material_output
        generated = copy.deepcopy(self.manifest)
        generated['scene_id'] = 'house'
        if change_furniture:
            generated['entities'][0]['material_id'] = 'plastic'
        manifest_path, blend = self.root / 'generated.json', self.root / 'house.blend'
        manifest_path.write_text(json.dumps(generated))
        blend.write_text('Synthetic saved scene bytes; not a native scene')
        structural = copy.deepcopy(self.structural)
        if not missing:
            structural.update(source_manifest_sha256=hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
                              source_sha256='0'*64 if stale else hashlib.sha256(blend.read_bytes()).hexdigest())
        plan = self.compile({'furniture_requirements': {'sofa': {'material_id': 'original-fabric'}}})
        return _audit_material_output(plan, generated, structural, self.root, manifest_path, blend, {})

    def test_output_furniture_must_satisfy_material_pin(self):
        report = self.generated_audit(change_furniture=True)
        self.assertFalse(report['passed'])
        self.assertIn('explicit_requirement_mismatch', self.codes(report))

    def test_matching_current_material_receipt_and_furniture_pass(self):
        self.assertTrue(self.generated_audit()['passed'])

    def test_material_receipt_must_bind_current_saved_scene(self):
        report = self.generated_audit(stale=True)
        self.assertFalse(report['passed'])
        self.assertIn('material_saved_scene_binding_mismatch', self.codes(report))

    def test_missing_material_saved_scene_binding_remains_unknown(self):
        report = self.generated_audit(missing=True)
        self.assertFalse(report['passed'])
        self.assertIn('material_saved_scene_binding_missing', self.codes(report, 'unknowns'))

    def native_material_audit(self, pinned):
        from engine.wholehouse_pipeline import _audit_material_output
        structural_path = self.root / 'structural_material_manifest.json'
        structural_path.write_text(json.dumps(self.structural))
        generated = dict(self.manifest, scene_id='house', structural_material_manifest=dict(
            path=structural_path.name, sha256=hashlib.sha256(structural_path.read_bytes()).hexdigest()))
        manifest_path, blend = self.root / 'generated.json', self.root / 'house.blend'
        manifest_path.write_text(json.dumps(generated))
        blend.write_text('Synthetic saved scene bytes')
        receipt = self.root / 'saved_blend_verification.json'
        receipt.write_text(json.dumps(dict(passed=True, scene_id='house', entity_count=1,
            blend_sha256=hashlib.sha256(blend.read_bytes()).hexdigest())))
        inputs = {str(receipt): hashlib.sha256(receipt.read_bytes()).hexdigest()} if pinned else {}
        return _audit_material_output(self.compile(), generated, self.structural, self.root,
                                      manifest_path, blend, inputs)

    def test_frozen_native_reopen_can_bind_existing_structural_schema(self):
        self.assertTrue(self.native_material_audit(True)['passed'])

    def test_unbound_native_reopen_receipt_cannot_supply_material_identity(self):
        self.assertFalse(self.native_material_audit(False)['passed'])

    def test_door_family_mismatch(self):
        self.structural['roles']['door_frame']['family_id'] = 'other'
        self.assertIn('door_family_mismatch', self.codes(self.audit()))

    def test_changed_and_missing_texture_bytes(self):
        path = Path(next(iter(self.structural['source_dependency_sha256'])))
        path.write_bytes(b'changed')
        self.assertIn('dependency_hash_mismatch', self.codes(self.audit()))
        path.unlink()
        self.assertIn('dependency_missing', self.codes(self.audit()))

    def test_unknown_metadata_does_not_reject_original_furniture(self):
        report = api().audit_material_plan(self.compile({'style_traits': {'wood_tone': 'light'}}),
                                            self.structural, self.root)
        self.assertTrue(report['passed'])
        self.assertIn('style_metadata_unknown', self.codes(report, 'unknowns'))
        self.assertEqual(self.manifest['entities'][0]['material_id'], 'original-fabric')

    def test_explicit_pin_and_furniture_requirement_are_hard_constraints(self):
        plan = self.compile({'pins': {'door_family': {'family_id': 'required-oak'}},
                             'furniture_requirements': {'sofa': {'material_id': 'leather'}}})
        report = self.audit(plan=plan)
        self.assertIn('explicit_requirement_mismatch', self.codes(report))
        self.assertFalse(report['passed'])
        self.assertEqual(plan['furniture'][0]['material_id'], 'original-fabric')

    def test_exact_room_coverage_and_independent_wet_classification(self):
        self.structural['room_floor_roles']['bath'] = 'floor_dry'
        self.structural['room_floor_roles']['extra'] = 'floor_dry'
        report = self.audit()
        self.assertIn('room_coverage_mismatch', self.codes(report))
        self.assertIn('floor_role_mismatch', self.codes(report))

    def test_selected_identity_and_revision_drift(self):
        plan = self.compile()
        self.structural['roles']['interior_wall']['material_revision'] = 'changed'
        self.assertIn('selected_suite_mismatch', self.codes(self.audit(plan=plan)))

    def test_assignment_identity_and_missing_room(self):
        self.structural['assignments'][0]['material_id'] = 'other'
        self.structural['assignments'].pop()
        report = self.audit()
        self.assertIn('assignment_suite_mismatch', self.codes(report))
        self.assertIn('room_assignment_missing', self.codes(report))

    def test_unavailable_remote_evidence_never_passes(self):
        self.structural['source_dependency_sha256']['/unavailable_remote_host/a.png'] = '0' * 64
        report = api().audit_material_plan(self.compile(), self.structural)
        self.assertFalse(report['passed'])
        self.assertIn('dependency_unavailable', self.codes(report, 'unknowns'))

    def test_pbr_and_coordinate_provenance_and_normal(self):
        spec = self.structural['roles']['floor_wet']
        spec['channels'].pop('normal')
        spec['normal_convention'] = 'DirectX'
        spec.pop('texture_scale_provenance')
        report = self.audit()
        self.assertIn('pbr_channel_missing', self.codes(report))
        self.assertIn('normal_convention_mismatch', self.codes(report))
        self.assertIn('coordinate_provenance_unknown', self.codes(report, 'unknowns'))

    def test_nonfinite_input_rejected(self):
        with self.assertRaises(ValueError):
            self.compile({'style_traits': {'roughness': float('nan')}})

    def test_audit_cannot_inherit_forged_fidelity_claims(self):
        plan = self.compile()
        plan['visual_fidelity_proven'] = True
        plan['camera_fidelity_proven'] = True
        report = self.audit(plan=plan)
        self.assertFalse(report['visual_fidelity_proven'])
        self.assertFalse(report['camera_fidelity_proven'])

    def test_declared_native_explicit_selection_requirement(self):
        self.structural['roles']['interior_wall']['requested_material_or_family_id'] = 'required-plaster'
        self.assertIn('explicit_requirement_mismatch', self.codes(self.audit()))

    def test_actual_native_selector_suite_is_preserved_without_reselection(self):
        source = Path(__file__).resolve().parents[1] / 'source/scripts/internal/scene_generation/real_assets'
        spec = importlib.util.spec_from_file_location('native_material_selector_under_test', source / 'structural_material_selection.py')
        selector = importlib.util.module_from_spec(spec)
        with mock.patch.object(sys, 'path', [str(source), *sys.path]):
            spec.loader.exec_module(selector)
        pools = {}
        for native, selected in [('interior_wall', 'interior_wall'), ('door_family', 'door_leaf'),
                                  ('floor_dry', 'floor_dry'), ('floor_wet', 'floor_wet')]:
            item = copy.deepcopy(self.structural['roles'][selected])
            item.update(asset_id=item['material_id'], role=native)
            pools[native] = [item]
        catalog = self.root / 'catalog.json'
        catalog.write_text(json.dumps({'pools': pools}))
        selected = selector.select_structural_materials(catalog, 'house', 123, {},
                                                       floor_plan={'rooms': self.rooms})
        before = copy.deepcopy(selected)
        plan = api().compile_material_plan({'rooms': self.rooms, 'structural_materials': selected})
        self.assertEqual(plan['selected_suites'], selected['roles'])
        self.assertEqual(selected, before)
        report = api().audit_material_plan(plan, selected, self.root)
        self.assertFalse(report['passed'])  # Selection alone is not application evidence.
        self.assertIn('room_assignment_missing', self.codes(report))


if __name__ == '__main__':
    unittest.main()