vibrante-node-runtime 2.5.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (472) hide show
  1. src/__init__.py +1 -0
  2. src/runtime/__init__.py +187 -0
  3. src/runtime/agent_runtime.py +315 -0
  4. src/runtime/ai_planner.py +371 -0
  5. src/runtime/approval_pipeline.py +237 -0
  6. src/runtime/architectural_features/__init__.py +68 -0
  7. src/runtime/architectural_features/architectural_feature_realizer.py +279 -0
  8. src/runtime/architectural_features/architectural_plan.py +421 -0
  9. src/runtime/architectural_features/architectural_plan_builder.py +428 -0
  10. src/runtime/architectural_features/environment_architecture_review.py +398 -0
  11. src/runtime/asset_identity/__init__.py +103 -0
  12. src/runtime/asset_identity/asset_identity_auditor.py +532 -0
  13. src/runtime/asset_identity/identity_review.py +248 -0
  14. src/runtime/asset_identity/identity_serializer.py +76 -0
  15. src/runtime/asset_identity/identity_statistics.py +132 -0
  16. src/runtime/asset_identity/opaque_id_detector.py +167 -0
  17. src/runtime/asset_identity/role_engine_validator.py +134 -0
  18. src/runtime/asset_identity/role_geometry_validator.py +161 -0
  19. src/runtime/asset_knowledge_graph.py +505 -0
  20. src/runtime/asset_staging_manager.py +350 -0
  21. src/runtime/assets/__init__.py +310 -0
  22. src/runtime/assets/acquisition/__init__.py +109 -0
  23. src/runtime/assets/acquisition/acquisition_manager.py +431 -0
  24. src/runtime/assets/acquisition/download_registry.py +324 -0
  25. src/runtime/assets/acquisition/fab_library_scanner.py +384 -0
  26. src/runtime/assets/acquisition/library_index.py +379 -0
  27. src/runtime/assets/acquisition/library_watcher.py +362 -0
  28. src/runtime/assets/acquisition/megascans_scanner.py +551 -0
  29. src/runtime/assets/acquisition_online/__init__.py +211 -0
  30. src/runtime/assets/acquisition_online/acquisition_pipeline.py +279 -0
  31. src/runtime/assets/acquisition_online/asset_cache_manager.py +265 -0
  32. src/runtime/assets/acquisition_online/asset_fetcher.py +361 -0
  33. src/runtime/assets/acquisition_online/asset_provenance_tracker.py +231 -0
  34. src/runtime/assets/acquisition_online/download_queue.py +297 -0
  35. src/runtime/assets/acquisition_online/download_review.py +253 -0
  36. src/runtime/assets/acquisition_online/download_scheduler.py +188 -0
  37. src/runtime/assets/acquisition_online/download_serializer.py +116 -0
  38. src/runtime/assets/acquisition_online/download_statistics.py +145 -0
  39. src/runtime/assets/acquisition_online/fab_socket_receiver.py +449 -0
  40. src/runtime/assets/acquisition_online/megascans_auth.py +408 -0
  41. src/runtime/assets/acquisition_online/megascans_download.py +391 -0
  42. src/runtime/assets/acquisition_online/megascans_search.py +313 -0
  43. src/runtime/assets/acquisition_online/project_asset_staging.py +221 -0
  44. src/runtime/assets/acquisition_online/provider_session_manager.py +182 -0
  45. src/runtime/assets/acquisition_online/quixel_bridge_client.py +380 -0
  46. src/runtime/assets/assembly/__init__.py +288 -0
  47. src/runtime/assets/assembly/anchor_asset_engine.py +387 -0
  48. src/runtime/assets/assembly/architectural_templates.py +493 -0
  49. src/runtime/assets/assembly/asset_clustering_engine.py +343 -0
  50. src/runtime/assets/assembly/asset_placement_engine.py +553 -0
  51. src/runtime/assets/assembly/asset_scale_analyzer.py +278 -0
  52. src/runtime/assets/assembly/bounding_box_extractor.py +227 -0
  53. src/runtime/assets/assembly/clearance_validator.py +204 -0
  54. src/runtime/assets/assembly/collision_detector.py +208 -0
  55. src/runtime/assets/assembly/composition_constraints.py +291 -0
  56. src/runtime/assets/assembly/decorative_population_engine.py +419 -0
  57. src/runtime/assets/assembly/environment_blueprint.py +92 -0
  58. src/runtime/assets/assembly/environment_builder.py +401 -0
  59. src/runtime/assets/assembly/environment_completeness_review.py +500 -0
  60. src/runtime/assets/assembly/environment_review.py +454 -0
  61. src/runtime/assets/assembly/environment_scale_review.py +490 -0
  62. src/runtime/assets/assembly/environment_structure_builder.py +344 -0
  63. src/runtime/assets/assembly/environment_zones.py +332 -0
  64. src/runtime/assets/assembly/footprint_calculator.py +181 -0
  65. src/runtime/assets/assembly/layout_spacing_engine.py +350 -0
  66. src/runtime/assets/assembly/placement_optimizer.py +272 -0
  67. src/runtime/assets/assembly/placement_relationships.py +380 -0
  68. src/runtime/assets/assembly/placement_templates.py +1024 -0
  69. src/runtime/assets/assembly/scene_population_engine.py +351 -0
  70. src/runtime/assets/assembly/semantic_placement_rules.py +323 -0
  71. src/runtime/assets/assembly/spatial_metadata.py +118 -0
  72. src/runtime/assets/assembly/spatial_review.py +304 -0
  73. src/runtime/assets/assembly/storytelling_layout_engine.py +768 -0
  74. src/runtime/assets/assembly/unit_normalizer.py +192 -0
  75. src/runtime/assets/cache/__init__.py +39 -0
  76. src/runtime/assets/cache/asset_cache.py +330 -0
  77. src/runtime/assets/cache/asset_storage.py +234 -0
  78. src/runtime/assets/cache/asset_sync.py +280 -0
  79. src/runtime/assets/discovery/__init__.py +17 -0
  80. src/runtime/assets/discovery/asset_discovery_engine.py +223 -0
  81. src/runtime/assets/download/__init__.py +24 -0
  82. src/runtime/assets/download/asset_download_manager.py +275 -0
  83. src/runtime/assets/geometry/__init__.py +149 -0
  84. src/runtime/assets/geometry/asset_metrics.py +476 -0
  85. src/runtime/assets/geometry/bounding_box_extractor.py +478 -0
  86. src/runtime/assets/geometry/geometry_analyzer.py +251 -0
  87. src/runtime/assets/geometry/geometry_review.py +463 -0
  88. src/runtime/assets/geometry/geometry_serializer.py +121 -0
  89. src/runtime/assets/geometry/geometry_statistics.py +206 -0
  90. src/runtime/assets/geometry/ground_contact_detector.py +277 -0
  91. src/runtime/assets/geometry/pivot_detector.py +248 -0
  92. src/runtime/assets/geometry/support_surface_detector.py +299 -0
  93. src/runtime/assets/logging/__init__.py +17 -0
  94. src/runtime/assets/logging/asset_logger.py +153 -0
  95. src/runtime/assets/metadata/__init__.py +65 -0
  96. src/runtime/assets/metadata/asset_metadata_enricher.py +215 -0
  97. src/runtime/assets/metadata/asset_provenance.py +273 -0
  98. src/runtime/assets/metadata/asset_semantic_mapper.py +265 -0
  99. src/runtime/assets/metadata/provider_normalizer.py +364 -0
  100. src/runtime/assets/providers/__init__.py +38 -0
  101. src/runtime/assets/providers/base.py +218 -0
  102. src/runtime/assets/providers/local_library_provider.py +209 -0
  103. src/runtime/assets/providers/polyhaven_provider.py +268 -0
  104. src/runtime/assets/providers/provider_manager.py +229 -0
  105. src/runtime/assets/providers/quixel_provider.py +277 -0
  106. src/runtime/assets/providers/sketchfab_live_provider.py +515 -0
  107. src/runtime/assets/providers/sketchfab_provider.py +327 -0
  108. src/runtime/assets/providers/studio_library_provider.py +323 -0
  109. src/runtime/assets/providers/usd_library_provider.py +310 -0
  110. src/runtime/assets/ranking/__init__.py +17 -0
  111. src/runtime/assets/ranking/asset_ranking_engine.py +365 -0
  112. src/runtime/assets/real_world_scale.py +189 -0
  113. src/runtime/assets/realization/__init__.py +162 -0
  114. src/runtime/assets/realization/asset_converter.py +282 -0
  115. src/runtime/assets/realization/asset_dependency_resolver.py +285 -0
  116. src/runtime/assets/realization/asset_importer.py +298 -0
  117. src/runtime/assets/realization/asset_instancer.py +269 -0
  118. src/runtime/assets/realization/asset_material_mapper.py +337 -0
  119. src/runtime/assets/realization/asset_normalizer.py +319 -0
  120. src/runtime/assets/realization/asset_realization_review.py +416 -0
  121. src/runtime/assets/realization/asset_validation_pipeline.py +316 -0
  122. src/runtime/assets/realization/realization_serializer.py +172 -0
  123. src/runtime/assets/realization/realization_statistics.py +265 -0
  124. src/runtime/assets/realization/scene_asset_realizer.py +405 -0
  125. src/runtime/assets/realization/usd_builder.py +272 -0
  126. src/runtime/assets/recommendations/__init__.py +17 -0
  127. src/runtime/assets/recommendations/asset_recommendation_engine.py +260 -0
  128. src/runtime/assets/schema/__init__.py +38 -0
  129. src/runtime/assets/schema/asset_descriptor.py +484 -0
  130. src/runtime/assets/semantic/__init__.py +234 -0
  131. src/runtime/assets/semantic/asset_catalog.py +368 -0
  132. src/runtime/assets/semantic/asset_catalog_review.py +266 -0
  133. src/runtime/assets/semantic/asset_catalog_serializer.py +103 -0
  134. src/runtime/assets/semantic/asset_catalog_statistics.py +130 -0
  135. src/runtime/assets/semantic/asset_catalog_sync.py +248 -0
  136. src/runtime/assets/semantic/asset_cinematic_mapper.py +156 -0
  137. src/runtime/assets/semantic/asset_environment_mapper.py +459 -0
  138. src/runtime/assets/semantic/asset_knowledge_graph.py +257 -0
  139. src/runtime/assets/semantic/asset_lookdev_mapper.py +180 -0
  140. src/runtime/assets/semantic/asset_manifest_reader.py +236 -0
  141. src/runtime/assets/semantic/asset_metadata_extractor.py +167 -0
  142. src/runtime/assets/semantic/asset_metadata_provider.py +231 -0
  143. src/runtime/assets/semantic/asset_query_engine.py +240 -0
  144. src/runtime/assets/semantic/asset_role_classifier.py +193 -0
  145. src/runtime/assets/semantic/asset_storytelling_mapper.py +163 -0
  146. src/runtime/assets/semantic/megascans_metadata_client.py +345 -0
  147. src/runtime/assets/semantic/semantic_asset_enricher.py +232 -0
  148. src/runtime/assets/serialization/__init__.py +15 -0
  149. src/runtime/assets/serialization/asset_serializer.py +201 -0
  150. src/runtime/assets/suitability/__init__.py +115 -0
  151. src/runtime/assets/suitability/asset_suitability_engine.py +345 -0
  152. src/runtime/assets/suitability/asset_suitability_review.py +193 -0
  153. src/runtime/assets/suitability/asset_suitability_serializer.py +67 -0
  154. src/runtime/assets/suitability/asset_suitability_statistics.py +141 -0
  155. src/runtime/assets/suitability/environment_affinity.py +290 -0
  156. src/runtime/assets/suitability/material_affinity.py +247 -0
  157. src/runtime/assets/suitability/placement_affinity.py +153 -0
  158. src/runtime/assets/suitability/role_affinity.py +205 -0
  159. src/runtime/assets/suitability/scale_affinity.py +150 -0
  160. src/runtime/assets/suitability/story_affinity.py +235 -0
  161. src/runtime/assets/suitability/style_affinity.py +252 -0
  162. src/runtime/assets/validation/__init__.py +17 -0
  163. src/runtime/assets/validation/asset_validation_engine.py +281 -0
  164. src/runtime/assets/vector_search/__init__.py +193 -0
  165. src/runtime/assets/vector_search/asset_embedding_builder.py +132 -0
  166. src/runtime/assets/vector_search/asset_vector_store.py +264 -0
  167. src/runtime/assets/vector_search/catalog_vector_index_builder.py +155 -0
  168. src/runtime/assets/vector_search/embedding_provider.py +294 -0
  169. src/runtime/assets/vector_search/hybrid_ranking_engine.py +241 -0
  170. src/runtime/assets/vector_search/intent_embedding_engine.py +99 -0
  171. src/runtime/assets/vector_search/intent_parser.py +462 -0
  172. src/runtime/assets/vector_search/retrieval_pipeline.py +275 -0
  173. src/runtime/assets/vector_search/retrieval_review.py +281 -0
  174. src/runtime/assets/vector_search/retrieval_serializer.py +91 -0
  175. src/runtime/assets/vector_search/retrieval_statistics.py +133 -0
  176. src/runtime/assets/vector_search/semantic_similarity.py +116 -0
  177. src/runtime/assets/vector_search/vector_search_engine.py +246 -0
  178. src/runtime/atmosphere_orchestrator.py +412 -0
  179. src/runtime/audit_store.py +230 -0
  180. src/runtime/capability_catalog.py +2324 -0
  181. src/runtime/capability_registry.py +225 -0
  182. src/runtime/cinematic_camera_engine.py +497 -0
  183. src/runtime/cinematic_composition.py +399 -0
  184. src/runtime/cinematic_scene_review.py +539 -0
  185. src/runtime/contextual_reasoning.py +286 -0
  186. src/runtime/dependency_graph.py +205 -0
  187. src/runtime/distributed_runtime.py +348 -0
  188. src/runtime/environment/__init__.py +189 -0
  189. src/runtime/environment/anchor_asset_builder.py +389 -0
  190. src/runtime/environment/atmosphere_builder.py +307 -0
  191. src/runtime/environment/decorative_population.py +320 -0
  192. src/runtime/environment/environment_blueprint.py +107 -0
  193. src/runtime/environment/environment_completeness.py +234 -0
  194. src/runtime/environment/environment_requirements.py +224 -0
  195. src/runtime/environment/environment_review.py +320 -0
  196. src/runtime/environment/environment_serializer.py +100 -0
  197. src/runtime/environment/environment_statistics.py +149 -0
  198. src/runtime/environment/environment_structure_builder.py +391 -0
  199. src/runtime/environment/environment_template_library.py +388 -0
  200. src/runtime/environment/environment_zone_builder.py +334 -0
  201. src/runtime/environment/support_asset_builder.py +243 -0
  202. src/runtime/environment_realization/__init__.py +177 -0
  203. src/runtime/environment_realization/architectural_constraint_solver.py +230 -0
  204. src/runtime/environment_realization/beam_builder.py +221 -0
  205. src/runtime/environment_realization/ceiling_builder.py +186 -0
  206. src/runtime/environment_realization/environment_execution_engine.py +228 -0
  207. src/runtime/environment_realization/environment_realization_engine.py +119 -0
  208. src/runtime/environment_realization/environment_review.py +250 -0
  209. src/runtime/environment_realization/environment_serializer.py +77 -0
  210. src/runtime/environment_realization/environment_statistics.py +134 -0
  211. src/runtime/environment_realization/floor_builder.py +198 -0
  212. src/runtime/environment_realization/opening_builder.py +224 -0
  213. src/runtime/environment_realization/room_shell_builder.py +215 -0
  214. src/runtime/environment_realization/room_shell_completeness_validator.py +303 -0
  215. src/runtime/environment_realization/structural_attachment_enforcer.py +386 -0
  216. src/runtime/environment_realization/structural_builder.py +314 -0
  217. src/runtime/environment_realization/structural_elements.py +258 -0
  218. src/runtime/environment_realization/structural_routing_engine.py +390 -0
  219. src/runtime/environment_realization/wall_builder.py +199 -0
  220. src/runtime/environment_rules.py +239 -0
  221. src/runtime/environment_shell/__init__.py +187 -0
  222. src/runtime/environment_shell/environment_readiness_gate.py +187 -0
  223. src/runtime/environment_shell/environment_shell_audit.py +184 -0
  224. src/runtime/environment_shell/environment_shell_blueprint.py +267 -0
  225. src/runtime/environment_shell/environment_shell_builder.py +265 -0
  226. src/runtime/environment_shell/environment_shell_state.py +133 -0
  227. src/runtime/environment_shell/shell_ceiling_builder.py +114 -0
  228. src/runtime/environment_shell/shell_floor_builder.py +96 -0
  229. src/runtime/environment_shell/shell_phase_result.py +66 -0
  230. src/runtime/environment_shell/shell_review.py +241 -0
  231. src/runtime/environment_shell/shell_serializer.py +67 -0
  232. src/runtime/environment_shell/shell_statistics.py +141 -0
  233. src/runtime/environment_shell/shell_validator.py +138 -0
  234. src/runtime/environment_shell/shell_wall_builder.py +156 -0
  235. src/runtime/environment_shell/structural_anchor_generator.py +200 -0
  236. src/runtime/environment_shell/structural_element_placer.py +193 -0
  237. src/runtime/environments/__init__.py +67 -0
  238. src/runtime/environments/environment_registry.py +1139 -0
  239. src/runtime/environments/environment_statistics.py +219 -0
  240. src/runtime/execution_explainer.py +399 -0
  241. src/runtime/execution_quality.py +258 -0
  242. src/runtime/execution_review.py +221 -0
  243. src/runtime/execution_scheduler.py +263 -0
  244. src/runtime/failure_intelligence.py +341 -0
  245. src/runtime/goal_decomposer.py +532 -0
  246. src/runtime/houdini_asset_realizer.py +329 -0
  247. src/runtime/houdini_runtime.py +992 -0
  248. src/runtime/intent_parser.py +275 -0
  249. src/runtime/knowledge_graph.py +310 -0
  250. src/runtime/layout/__init__.py +172 -0
  251. src/runtime/layout/affordance_engine.py +384 -0
  252. src/runtime/layout/anchor_layout_engine.py +244 -0
  253. src/runtime/layout/decoration_layout_engine.py +325 -0
  254. src/runtime/layout/furniture_cluster_builder.py +381 -0
  255. src/runtime/layout/layout_review.py +265 -0
  256. src/runtime/layout/layout_serializer.py +77 -0
  257. src/runtime/layout/layout_statistics.py +123 -0
  258. src/runtime/layout/relationship_graph.py +165 -0
  259. src/runtime/layout/relationship_graph_builder.py +699 -0
  260. src/runtime/layout/relationship_layout_engine.py +1101 -0
  261. src/runtime/layout/relationship_realization_auditor.py +849 -0
  262. src/runtime/layout/semantic_layout_engine.py +327 -0
  263. src/runtime/layout/surface_placement_engine.py +270 -0
  264. src/runtime/layout/wall_attachment_engine.py +243 -0
  265. src/runtime/layout_realization/__init__.py +183 -0
  266. src/runtime/layout_realization/cluster_realizer.py +212 -0
  267. src/runtime/layout_realization/collision_solver.py +359 -0
  268. src/runtime/layout_realization/identity_metadata_writer.py +257 -0
  269. src/runtime/layout_realization/layout_application_engine.py +242 -0
  270. src/runtime/layout_realization/layout_realization_engine.py +293 -0
  271. src/runtime/layout_realization/layout_validator.py +315 -0
  272. src/runtime/layout_realization/metadata_application_engine.py +187 -0
  273. src/runtime/layout_realization/realization_review.py +268 -0
  274. src/runtime/layout_realization/realization_serializer.py +77 -0
  275. src/runtime/layout_realization/realization_statistics.py +151 -0
  276. src/runtime/layout_realization/relationship_metadata_writer.py +305 -0
  277. src/runtime/layout_realization/relationship_persistence_auditor.py +426 -0
  278. src/runtime/layout_realization/relationship_realizer.py +294 -0
  279. src/runtime/layout_realization/scene_constraint_solver.py +317 -0
  280. src/runtime/layout_realization/surface_realizer.py +195 -0
  281. src/runtime/layout_realization/transform_resolver.py +268 -0
  282. src/runtime/layout_realization/wall_attachment_realizer.py +182 -0
  283. src/runtime/layout_transform_engine.py +341 -0
  284. src/runtime/lighting/__init__.py +215 -0
  285. src/runtime/lighting/lighting_color_engine.py +252 -0
  286. src/runtime/lighting/lighting_environment_mapper.py +792 -0
  287. src/runtime/lighting/lighting_exposure_engine.py +213 -0
  288. src/runtime/lighting/lighting_hierarchy_engine.py +248 -0
  289. src/runtime/lighting/lighting_knowledge.py +342 -0
  290. src/runtime/lighting/lighting_language.py +239 -0
  291. src/runtime/lighting/lighting_mood_engine.py +230 -0
  292. src/runtime/lighting/lighting_patterns.py +522 -0
  293. src/runtime/lighting/lighting_plan_builder.py +320 -0
  294. src/runtime/lighting/lighting_readability_engine.py +273 -0
  295. src/runtime/lighting/lighting_recommendation_engine.py +205 -0
  296. src/runtime/lighting/lighting_review.py +370 -0
  297. src/runtime/lighting/lighting_serializer.py +71 -0
  298. src/runtime/lighting/lighting_statistics.py +142 -0
  299. src/runtime/lighting/lighting_strategy_engine.py +239 -0
  300. src/runtime/lighting/lighting_validation.py +183 -0
  301. src/runtime/llm_provider.py +340 -0
  302. src/runtime/lookdev/__init__.py +137 -0
  303. src/runtime/lookdev/lookdev_patterns.py +216 -0
  304. src/runtime/lookdev/lookdev_review.py +389 -0
  305. src/runtime/lookdev/lookdev_serializer.py +71 -0
  306. src/runtime/lookdev/lookdev_statistics.py +133 -0
  307. src/runtime/lookdev/lookdev_validation.py +203 -0
  308. src/runtime/lookdev/material_assignment_engine.py +331 -0
  309. src/runtime/lookdev/material_knowledge.py +244 -0
  310. src/runtime/lookdev/material_library.py +311 -0
  311. src/runtime/lookdev/material_recommendation.py +394 -0
  312. src/runtime/lookdev/renderer_profiles.py +281 -0
  313. src/runtime/mcp_runtime.py +357 -0
  314. src/runtime/mcp_server_runtime.py +386 -0
  315. src/runtime/mcp_session.py +261 -0
  316. src/runtime/mcp_tool_registry.py +2169 -0
  317. src/runtime/mcp_transport.py +206 -0
  318. src/runtime/multi_dcc_runtime.py +316 -0
  319. src/runtime/orchestration_heuristics.py +360 -0
  320. src/runtime/pattern_library.py +344 -0
  321. src/runtime/plan_validator.py +314 -0
  322. src/runtime/planning/__init__.py +103 -0
  323. src/runtime/planning/camera/__init__.py +1 -0
  324. src/runtime/planning/camera/camera_planner.py +179 -0
  325. src/runtime/planning/composition/__init__.py +1 -0
  326. src/runtime/planning/composition/composition_planner.py +223 -0
  327. src/runtime/planning/logging/__init__.py +1 -0
  328. src/runtime/planning/logging/planning_logger.py +109 -0
  329. src/runtime/planning/planners/__init__.py +1 -0
  330. src/runtime/planning/planners/asset_query_generator.py +265 -0
  331. src/runtime/planning/planners/scene_planner.py +199 -0
  332. src/runtime/planning/planners/zone_planner.py +271 -0
  333. src/runtime/planning/recommendations/__init__.py +1 -0
  334. src/runtime/planning/recommendations/scene_plan_recommendation_engine.py +228 -0
  335. src/runtime/planning/schema/__init__.py +23 -0
  336. src/runtime/planning/schema/scene_plan.py +569 -0
  337. src/runtime/planning/serialization/__init__.py +1 -0
  338. src/runtime/planning/serialization/plan_serializer.py +147 -0
  339. src/runtime/planning/validators/__init__.py +1 -0
  340. src/runtime/planning/validators/scene_plan_validator.py +210 -0
  341. src/runtime/planning_memory.py +242 -0
  342. src/runtime/predictive_execution.py +393 -0
  343. src/runtime/procedural_scene_assembler.py +415 -0
  344. src/runtime/production_memory.py +309 -0
  345. src/runtime/production_scoring.py +422 -0
  346. src/runtime/reality/__init__.py +197 -0
  347. src/runtime/reality/architectural_integrity_validator.py +220 -0
  348. src/runtime/reality/beam_connection_validator.py +205 -0
  349. src/runtime/reality/composition_engine.py +206 -0
  350. src/runtime/reality/correction_applier.py +159 -0
  351. src/runtime/reality/correction_pass_engine.py +253 -0
  352. src/runtime/reality/density_engine.py +145 -0
  353. src/runtime/reality/floating_object_detector.py +206 -0
  354. src/runtime/reality/functional_zone_builder.py +260 -0
  355. src/runtime/reality/geometry_inspector.py +229 -0
  356. src/runtime/reality/human_reasoning_engine.py +284 -0
  357. src/runtime/reality/reality_intelligence_engine.py +182 -0
  358. src/runtime/reality/reality_scene_model.py +351 -0
  359. src/runtime/reality/reality_serializer.py +75 -0
  360. src/runtime/reality/reality_statistics.py +145 -0
  361. src/runtime/reality/support_rule_engine.py +248 -0
  362. src/runtime/reality/visual_review_engine.py +217 -0
  363. src/runtime/recommendation_engine.py +358 -0
  364. src/runtime/render_preparation_engine.py +463 -0
  365. src/runtime/resource_estimator.py +256 -0
  366. src/runtime/resource_optimizer.py +343 -0
  367. src/runtime/review_engine.py +768 -0
  368. src/runtime/review_feedback.py +325 -0
  369. src/runtime/runtime_analytics.py +330 -0
  370. src/runtime/runtime_bootstrap.py +137 -0
  371. src/runtime/runtime_constraints.py +317 -0
  372. src/runtime/runtime_federation_api.py +297 -0
  373. src/runtime/runtime_identity.py +70 -0
  374. src/runtime/runtime_narration.py +493 -0
  375. src/runtime/runtime_prompt_context.py +682 -0
  376. src/runtime/scene_awareness.py +559 -0
  377. src/runtime/scene_cache.py +277 -0
  378. src/runtime/scene_hierarchy_builder.py +258 -0
  379. src/runtime/scene_layout_planner.py +292 -0
  380. src/runtime/scene_realization_review.py +452 -0
  381. src/runtime/scene_recommendation_engine.py +398 -0
  382. src/runtime/scene_validation/__init__.py +118 -0
  383. src/runtime/scene_validation/occupancy_validator.py +176 -0
  384. src/runtime/scene_validation/orphan_detector.py +205 -0
  385. src/runtime/scene_validation/plausibility_engine.py +236 -0
  386. src/runtime/scene_validation/relationship_validator.py +238 -0
  387. src/runtime/scene_validation/routing_audit.py +556 -0
  388. src/runtime/scene_validation/scene_reality_validator.py +229 -0
  389. src/runtime/scene_validation/support_surface_validator.py +155 -0
  390. src/runtime/scene_validation/validation_review.py +207 -0
  391. src/runtime/scene_validation/validation_serializer.py +74 -0
  392. src/runtime/scene_validation/validation_statistics.py +142 -0
  393. src/runtime/semantic/__init__.py +113 -0
  394. src/runtime/semantic/enrichers/__init__.py +12 -0
  395. src/runtime/semantic/enrichers/scene_intent_enricher.py +305 -0
  396. src/runtime/semantic/logging/__init__.py +18 -0
  397. src/runtime/semantic/logging/semantic_logger.py +298 -0
  398. src/runtime/semantic/prompts/__init__.py +12 -0
  399. src/runtime/semantic/prompts/intent_prompt_builder.py +317 -0
  400. src/runtime/semantic/recommendations/__init__.py +17 -0
  401. src/runtime/semantic/recommendations/intent_recommendation_engine.py +434 -0
  402. src/runtime/semantic/scene_intent_extractor.py +455 -0
  403. src/runtime/semantic/schema/__init__.py +40 -0
  404. src/runtime/semantic/schema/scene_intent_schema.py +349 -0
  405. src/runtime/semantic/serialization/__init__.py +16 -0
  406. src/runtime/semantic/serialization/intent_serializer.py +248 -0
  407. src/runtime/semantic/validators/__init__.py +14 -0
  408. src/runtime/semantic/validators/scene_intent_validator.py +284 -0
  409. src/runtime/semantic_execution.py +348 -0
  410. src/runtime/semantic_import_controller.py +408 -0
  411. src/runtime/semantic_lighting_engine.py +566 -0
  412. src/runtime/semantic_memory.py +257 -0
  413. src/runtime/semantic_registry.py +386 -0
  414. src/runtime/semantic_scene_templates.py +387 -0
  415. src/runtime/storage/__init__.py +18 -0
  416. src/runtime/storage/memory_backend.py +294 -0
  417. src/runtime/storage/serialization.py +211 -0
  418. src/runtime/storage/sqlite_backend.py +365 -0
  419. src/runtime/structure/__init__.py +135 -0
  420. src/runtime/structure/environment_structural_affinity.py +254 -0
  421. src/runtime/structure/geometry_role_detector.py +182 -0
  422. src/runtime/structure/metadata_role_classifier.py +279 -0
  423. src/runtime/structure/structural_asset_classifier.py +331 -0
  424. src/runtime/structure/structural_placement_rules.py +326 -0
  425. src/runtime/structure/structural_review.py +682 -0
  426. src/runtime/structure/structural_serializer.py +113 -0
  427. src/runtime/structure/structural_statistics.py +209 -0
  428. src/runtime/studio/__init__.py +71 -0
  429. src/runtime/studio/cross_project_learning.py +263 -0
  430. src/runtime/studio/knowledge_recommendation.py +324 -0
  431. src/runtime/studio/knowledge_serializer.py +154 -0
  432. src/runtime/studio/knowledge_statistics.py +107 -0
  433. src/runtime/studio/production_benchmark.py +240 -0
  434. src/runtime/studio/project_memory.py +250 -0
  435. src/runtime/studio/review_analytics.py +166 -0
  436. src/runtime/studio/studio_knowledge.py +284 -0
  437. src/runtime/studio/studio_metrics.py +155 -0
  438. src/runtime/studio/studio_standards.py +262 -0
  439. src/runtime/studio_knowledge.py +328 -0
  440. src/runtime/transaction_manager.py +367 -0
  441. src/runtime/validation_engine.py +234 -0
  442. src/runtime/visual_hierarchy_engine.py +452 -0
  443. src/runtime/worker_runtime.py +236 -0
  444. src/runtime/workflow_federation.py +316 -0
  445. src/runtime/workflow_optimizer.py +407 -0
  446. src/runtime/workflow_templates.py +421 -0
  447. src/runtime/workflows/__init__.py +129 -0
  448. src/runtime/workflows/workflow_blueprint.py +394 -0
  449. src/runtime/workflows/workflow_executor.py +344 -0
  450. src/runtime/workflows/workflow_pack.py +403 -0
  451. src/runtime/workflows/workflow_recommendation.py +353 -0
  452. src/runtime/workflows/workflow_registry.py +165 -0
  453. src/runtime/workflows/workflow_review.py +336 -0
  454. src/runtime/workflows/workflow_serializer.py +149 -0
  455. src/runtime/workflows/workflow_statistics.py +205 -0
  456. src/runtime/workflows/workflow_validator.py +272 -0
  457. src/utils/__init__.py +0 -0
  458. src/utils/hou_bridge.py +262 -0
  459. src/utils/vibrante_config.py +272 -0
  460. vibrante_node_runtime-2.5.1.dist-info/METADATA +47 -0
  461. vibrante_node_runtime-2.5.1.dist-info/RECORD +472 -0
  462. vibrante_node_runtime-2.5.1.dist-info/WHEEL +5 -0
  463. vibrante_node_runtime-2.5.1.dist-info/licenses/CLA.md +96 -0
  464. vibrante_node_runtime-2.5.1.dist-info/licenses/COMMERCIAL_LICENSE.md +170 -0
  465. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSE +178 -0
  466. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/AGPL-3.0.txt +661 -0
  467. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/CC-BY-4.0-SCOPE.md +53 -0
  468. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/CC-BY-4.0.txt +396 -0
  469. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/GPL-3.0.txt +674 -0
  470. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/LGPL-3.0.txt +165 -0
  471. vibrante_node_runtime-2.5.1.dist-info/licenses/LICENSES/README.md +65 -0
  472. vibrante_node_runtime-2.5.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1101 @@
1
+ """
2
+ relationship_layout_engine.py — Tier 14.4.2 Relationship-Aware Layout
3
+ =======================================================================
4
+ Consumes the pre-built RelationshipGraph (Tier 14.4.1) and produces
5
+ world-space transforms that satisfy every semantic edge.
6
+
7
+ Execution order:
8
+ Classification
9
+ → RelationshipGraphBuilder (Tier 14.4.1)
10
+ → RelationshipLayoutEngine ← this module
11
+ → CollisionSolver (Tier 9.9)
12
+ → ConstraintSolver (Tier 9.9)
13
+ → Validation (Tier 14.3)
14
+
15
+ Per-type placement rules:
16
+ fireplace attached_to wall → snap to fireplace anchor / nearest wall,
17
+ back face on wall plane (≤ 0.05m),
18
+ front faces room interior
19
+ chair belongs_near table → orbit at table_radius + clearance
20
+ faces table → rotate toward table centre
21
+ stool belongs_near bar → linear spread along bar front face
22
+ bottle supports surface → never floor; ty = surface_height
23
+ cup supports table → on tabletop only
24
+ plate supports table → on tabletop only
25
+ lantern supports table OR → on surface if table present,
26
+ attached_to wall otherwise mount on wall
27
+ barrel belongs_near wall → perimeter, never room centre
28
+ crate belongs_near wall → near wall or corner
29
+
30
+ Hard rules (FAIL if violated):
31
+ No bottle / cup / plate with ty ≤ MIN_SURFACE_H.
32
+ No chair without a table relationship.
33
+ No stool without a bar_counter relationship.
34
+ No fireplace without a wall anchor.
35
+ No lantern floating (ty ≤ MIN_SURFACE_H and not wall-mounted).
36
+
37
+ Scoring:
38
+ relationship_score = valid_relationships / total_relationships
39
+ PASS criterion: relationship_score ≥ 0.95
40
+
41
+ Public API:
42
+ RELATIONSHIP_LAYOUT_STATUS_PASS
43
+ RELATIONSHIP_LAYOUT_STATUS_FAIL
44
+ RelationshipAwareLayout
45
+ RelationshipLayoutEngine
46
+ get_relationship_layout_engine()
47
+ reset_relationship_layout_engine_for_tests()
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import math
53
+ import threading
54
+ from dataclasses import dataclass, field
55
+ from typing import Any, Dict, List, Optional, Set, Tuple
56
+
57
+ from src.runtime.layout.affordance_engine import get_affordance_engine
58
+ from src.runtime.layout.relationship_graph_builder import (
59
+ RelationshipGraph,
60
+ RelationshipEdge,
61
+ )
62
+ from src.runtime.layout_realization.transform_resolver import ResolvedTransform
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Status constants
66
+ # ---------------------------------------------------------------------------
67
+
68
+ RELATIONSHIP_LAYOUT_STATUS_PASS = "PASS"
69
+ RELATIONSHIP_LAYOUT_STATUS_FAIL = "FAIL"
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Placement constants
73
+ # ---------------------------------------------------------------------------
74
+
75
+ _MIN_SURFACE_H: float = 0.10 # ty below this is "on floor"
76
+ _WALL_INSET: float = 0.04 # back face distance from wall plane (m)
77
+ _NEAR_WALL_INSET: float = 0.50 # barrel/crate setback from wall face (m)
78
+ _PASS_THRESHOLD: float = 0.95 # relationship_score needed for PASS
79
+
80
+ # Surface heights per host type (m)
81
+ _SURFACE_HEIGHTS: Dict[str, float] = {
82
+ "table": 0.75,
83
+ "desk": 0.75,
84
+ "workbench": 0.90,
85
+ "bar_counter": 1.05,
86
+ "shelf": 1.40,
87
+ "counter": 0.90,
88
+ "mantle": 1.20,
89
+ "fireplace_mantel": 1.20,
90
+ "cabinet": 1.60,
91
+ "console": 0.85,
92
+ "crate": 0.60,
93
+ "pallet": 0.15,
94
+ }
95
+ _DEFAULT_SURFACE_H: float = 0.75
96
+
97
+ # Wall mount heights per asset type (m, midpoint)
98
+ _WALL_MOUNT_HEIGHTS: Dict[str, float] = {
99
+ "poster": 1.60,
100
+ "painting": 1.60,
101
+ "wanted_poster": 1.60,
102
+ "notice": 1.60,
103
+ "certificate": 1.60,
104
+ "mirror": 1.50,
105
+ "sign": 1.80,
106
+ "clock": 1.80,
107
+ "rack": 1.60,
108
+ "hook": 1.80,
109
+ "coat_hook": 1.80,
110
+ "banner": 2.15,
111
+ "lantern": 2.40,
112
+ "torch": 2.40,
113
+ "sconce": 2.25,
114
+ "shelf": 1.40,
115
+ "trophy_mount": 1.60,
116
+ "mounted_head": 1.80,
117
+ }
118
+ _DEFAULT_WALL_H: float = 1.60
119
+
120
+ # Orbit geometry for chairs around tables
121
+ _CHAIR_CLEARANCE: float = 0.45 # extra gap beyond table half-width (m)
122
+ _STOOL_CLEARANCE: float = 0.30 # gap from bar-counter front edge (m)
123
+ _STOOL_SPACING: float = 0.70 # stool-to-stool spacing along bar (m)
124
+
125
+ # Default room dimensions when no shell is provided (m)
126
+ _DEFAULT_ROOM_W: float = 10.0
127
+ _DEFAULT_ROOM_D: float = 12.0
128
+ _DEFAULT_ROOM_H: float = 4.0
129
+
130
+ # Maximum surface props per anchor (prevents overflow)
131
+ _MAX_SURFACE_PROPS: int = 6
132
+
133
+ # Surface-item XZ offsets relative to anchor (for table/bar spreading)
134
+ _SURFACE_XZ_OFFSETS: List[Tuple[float, float]] = [
135
+ (-0.25, 0.10),
136
+ ( 0.25, 0.10),
137
+ ( 0.00, -0.10),
138
+ (-0.25, -0.10),
139
+ ( 0.25, -0.10),
140
+ ( 0.00, 0.25),
141
+ ]
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Data model
146
+ # ---------------------------------------------------------------------------
147
+
148
+ @dataclass
149
+ class RelationshipAwareLayout:
150
+ """Output of RelationshipLayoutEngine.build_layout()."""
151
+
152
+ # Core output
153
+ relationship_aware_transforms: List[ResolvedTransform] = field(default_factory=list)
154
+ relationship_score: float = 0.0
155
+
156
+ # Categorised asset lists
157
+ supported_objects: List[str] = field(default_factory=list)
158
+ wall_attached_objects: List[str] = field(default_factory=list)
159
+ surface_attached_objects: List[str] = field(default_factory=list)
160
+ orphan_relationships: List[str] = field(default_factory=list)
161
+
162
+ # Per-rule validation flags
163
+ fireplace_alignment_pass: bool = True
164
+ chair_table_relation_pass: bool = True
165
+ stool_bar_relation_pass: bool = True
166
+ bottle_support_pass: bool = True
167
+ cup_support_pass: bool = True
168
+ plate_support_pass: bool = True
169
+ lantern_attachment_pass: bool = True
170
+ barrel_wall_relation_pass: bool = True
171
+ crate_wall_relation_pass: bool = True
172
+
173
+ # Overall status
174
+ status: str = RELATIONSHIP_LAYOUT_STATUS_PASS
175
+ validation_errors: List[str] = field(default_factory=list)
176
+ warnings: List[str] = field(default_factory=list)
177
+ ok: bool = True
178
+ errors: List[str] = field(default_factory=list)
179
+
180
+ def to_dict(self) -> Dict[str, Any]:
181
+ return {
182
+ "relationship_aware_transforms": [t.to_dict() for t in self.relationship_aware_transforms],
183
+ "relationship_score": round(self.relationship_score, 4),
184
+ "supported_objects": list(self.supported_objects),
185
+ "wall_attached_objects": list(self.wall_attached_objects),
186
+ "surface_attached_objects": list(self.surface_attached_objects),
187
+ "orphan_relationships": list(self.orphan_relationships),
188
+ "fireplace_alignment_pass": self.fireplace_alignment_pass,
189
+ "chair_table_relation_pass": self.chair_table_relation_pass,
190
+ "stool_bar_relation_pass": self.stool_bar_relation_pass,
191
+ "bottle_support_pass": self.bottle_support_pass,
192
+ "cup_support_pass": self.cup_support_pass,
193
+ "plate_support_pass": self.plate_support_pass,
194
+ "lantern_attachment_pass": self.lantern_attachment_pass,
195
+ "barrel_wall_relation_pass": self.barrel_wall_relation_pass,
196
+ "crate_wall_relation_pass": self.crate_wall_relation_pass,
197
+ "status": self.status,
198
+ "validation_errors": list(self.validation_errors),
199
+ "warnings": list(self.warnings),
200
+ "ok": self.ok,
201
+ "errors": list(self.errors),
202
+ }
203
+
204
+
205
+ # ---------------------------------------------------------------------------
206
+ # Engine
207
+ # ---------------------------------------------------------------------------
208
+
209
+ class RelationshipLayoutEngine:
210
+ """
211
+ Produces relationship-enforced world-space transforms.
212
+
213
+ Every transform is generated by first inspecting the asset's outgoing
214
+ relationship edges and then applying the rule for each edge type.
215
+ The resulting placement always satisfies the semantic relationship or
216
+ records an orphan_relationship if the target is absent.
217
+
218
+ Usage:
219
+ layout = get_relationship_layout_engine().build_layout(
220
+ scene_assets=assets,
221
+ relationship_graph=graph,
222
+ environment_shell=shell,
223
+ )
224
+ assert layout.status == RELATIONSHIP_LAYOUT_STATUS_PASS
225
+ """
226
+
227
+ def __init__(self) -> None:
228
+ self._lock = threading.Lock()
229
+
230
+ def build_layout(
231
+ self,
232
+ scene_assets: List[Dict[str, Any]],
233
+ relationship_graph: RelationshipGraph,
234
+ environment_shell: Any = None, # EnvironmentShell | dict | None
235
+ ) -> RelationshipAwareLayout:
236
+ """
237
+ Build relationship-aware placement transforms. Never raises.
238
+ """
239
+ try:
240
+ return self._build(scene_assets, relationship_graph, environment_shell)
241
+ except Exception as exc:
242
+ result = RelationshipAwareLayout(ok=False, status=RELATIONSHIP_LAYOUT_STATUS_FAIL)
243
+ result.errors.append(f"RelationshipLayoutEngine.build_layout failed: {exc}")
244
+ return result
245
+
246
+ # ------------------------------------------------------------------
247
+ # Internal pipeline
248
+ # ------------------------------------------------------------------
249
+
250
+ def _build(
251
+ self,
252
+ scene_assets: List[Dict[str, Any]],
253
+ graph: RelationshipGraph,
254
+ shell: Any,
255
+ ) -> RelationshipAwareLayout:
256
+ eng = get_affordance_engine()
257
+ result = RelationshipAwareLayout()
258
+
259
+ # ---- Normalise shell to a plain dict (or empty) ---------------
260
+ shell_dict = _shell_to_dict(shell)
261
+ room = _room_geometry(shell_dict)
262
+
263
+ # ---- Build asset index ----------------------------------------
264
+ # aid → asset dict, aid → inferred type
265
+ aid_to_asset: Dict[str, Dict[str, Any]] = {}
266
+ aid_to_type: Dict[str, str] = {}
267
+ typed: Dict[str, List[str]] = {} # type → [aids]
268
+
269
+ for asset in scene_assets:
270
+ aid = _aid(asset)
271
+ if not aid:
272
+ continue
273
+ atype = eng.infer_type(asset)
274
+ aid_to_asset[aid] = asset
275
+ aid_to_type[aid] = atype
276
+ typed.setdefault(atype, []).append(aid)
277
+
278
+ # ---- Transforms accumulator ----------------------------------
279
+ # aid → ResolvedTransform (filled incrementally, anchor-first)
280
+ transforms: Dict[str, ResolvedTransform] = {}
281
+
282
+ # ---- Relationship edge helpers --------------------------------
283
+ # edges_by_from: aid → list of RelationshipEdge from that aid
284
+ edges_by_from: Dict[str, List[RelationshipEdge]] = {}
285
+ for edge in graph.get_all_edges():
286
+ edges_by_from.setdefault(edge.from_node_id, []).append(edge)
287
+
288
+ total_rel = 0
289
+ valid_rel = 0
290
+
291
+ # ================================================================
292
+ # PASS 1: Anchors (table, bar_counter, fireplace)
293
+ # ================================================================
294
+ transforms.update(self._place_anchors(
295
+ typed, aid_to_asset, aid_to_type, room
296
+ ))
297
+
298
+ # ================================================================
299
+ # PASS 2: Relationship-driven placement for each non-anchor
300
+ # ================================================================
301
+ placed: Set[str] = set(transforms.keys())
302
+
303
+ # Processing order: structural → seating → surface props → wall → perimeter
304
+ _ORDER = [
305
+ "fireplace",
306
+ "chair", "stool",
307
+ "bottle", "whiskey_bottle", "cup", "mug", "glass",
308
+ "plate", "bowl", "book", "candle", "vase", "tool",
309
+ "lantern", "torch", "sconce",
310
+ "poster", "painting", "wanted_poster", "sign", "banner",
311
+ "clock", "mirror",
312
+ "barrel", "crate", "bucket", "bench",
313
+ ]
314
+
315
+ def _process_type(atype: str) -> None:
316
+ for aid in typed.get(atype, []):
317
+ if aid in placed:
318
+ return
319
+ edges = edges_by_from.get(aid, [])
320
+ t, n_total, n_valid = self._place_asset(
321
+ aid, atype, edges,
322
+ transforms, typed, aid_to_asset, aid_to_type, room,
323
+ )
324
+ if t is not None:
325
+ transforms[aid] = t
326
+ placed.add(aid)
327
+ total_rel += n_total # these are nonlocal-like via closure
328
+ valid_rel += n_valid # but Python 3 closures don't mutate outer
329
+
330
+ # Can't use nonlocal inside a nested def easily — collect via list
331
+ counts: List[int] = [0, 0]
332
+
333
+ for atype in _ORDER:
334
+ for aid in typed.get(atype, []):
335
+ if aid in placed:
336
+ continue
337
+ edges = edges_by_from.get(aid, [])
338
+ t, n_total, n_valid = self._place_asset(
339
+ aid, atype, edges,
340
+ transforms, typed, aid_to_asset, aid_to_type, room,
341
+ )
342
+ if t is not None:
343
+ transforms[aid] = t
344
+ placed.add(aid)
345
+ counts[0] += n_total
346
+ counts[1] += n_valid
347
+
348
+ # Catch any type not in _ORDER
349
+ for aid, atype in aid_to_type.items():
350
+ if aid in placed:
351
+ continue
352
+ edges = edges_by_from.get(aid, [])
353
+ t, n_total, n_valid = self._place_asset(
354
+ aid, atype, edges,
355
+ transforms, typed, aid_to_asset, aid_to_type, room,
356
+ )
357
+ if t is not None:
358
+ transforms[aid] = t
359
+ placed.add(aid)
360
+ counts[0] += n_total
361
+ counts[1] += n_valid
362
+
363
+ total_rel = counts[0]
364
+ valid_rel = counts[1]
365
+
366
+ # Also count anchor edges from graph
367
+ for edge in graph.get_all_edges():
368
+ from_id = edge.from_node_id
369
+ if from_id in (transforms) and from_id not in _get_counted_set(edges_by_from):
370
+ pass # already counted
371
+
372
+ # ================================================================
373
+ # PASS 3: Categorise outputs
374
+ # ================================================================
375
+ supported_ids: List[str] = []
376
+ wall_ids: List[str] = []
377
+ surface_ids: List[str] = []
378
+ orphan_rels: List[str] = []
379
+
380
+ for aid, t in transforms.items():
381
+ if t.relationship in ("supports", "on_top_of") or t.ty > _MIN_SURFACE_H:
382
+ if t.parent_id:
383
+ supported_ids.append(aid)
384
+ surface_ids.append(aid)
385
+ if t.relationship == "attached_to" and "wall" in (t.parent_id or ""):
386
+ wall_ids.append(aid)
387
+
388
+ # Orphan relationships: edges that point to missing targets
389
+ for edge in graph.get_all_edges():
390
+ fid = edge.from_node_id
391
+ tid = edge.to_node_id
392
+ if fid not in transforms and fid in aid_to_asset:
393
+ orphan_rels.append(
394
+ f"{fid} —[{edge.relationship_type}]→ {tid} (source not placed)"
395
+ )
396
+ elif not edge.is_virtual_target and tid not in transforms:
397
+ orphan_rels.append(
398
+ f"{fid} —[{edge.relationship_type}]→ {tid} (target missing)"
399
+ )
400
+
401
+ # ================================================================
402
+ # PASS 4: Validation (hard rules)
403
+ # ================================================================
404
+ v_errors: List[str] = []
405
+
406
+ def _hard_rule_check(
407
+ flag_name: str,
408
+ asset_types: List[str],
409
+ predicate,
410
+ error_fmt: str,
411
+ ) -> bool:
412
+ passed = True
413
+ for atype in asset_types:
414
+ for aid in typed.get(atype, []):
415
+ t = transforms.get(aid)
416
+ if not predicate(t, aid, atype):
417
+ v_errors.append(error_fmt.format(aid=aid, atype=atype))
418
+ passed = False
419
+ return passed
420
+
421
+ # Bottle / cup / plate not on floor
422
+ def _on_surface(t, aid, atype):
423
+ return t is not None and t.ty > _MIN_SURFACE_H
424
+
425
+ result.bottle_support_pass = _hard_rule_check(
426
+ "bottle_support_pass", ["bottle", "whiskey_bottle"],
427
+ _on_surface,
428
+ "FAIL: '{aid}' ({atype}) placed on floor (ty ≤ {h:.2f}m)".format_map,
429
+ ) if False else _run_check(
430
+ ["bottle", "whiskey_bottle"],
431
+ lambda t, aid, atype: t is not None and t.ty > _MIN_SURFACE_H,
432
+ typed, transforms, v_errors,
433
+ "BOTTLE: '{aid}' ({atype}) on floor — must be on surface",
434
+ )
435
+
436
+ result.cup_support_pass = _run_check(
437
+ ["cup", "mug", "glass"],
438
+ lambda t, aid, atype: t is not None and t.ty > _MIN_SURFACE_H,
439
+ typed, transforms, v_errors,
440
+ "CUP: '{aid}' on floor — must be on tabletop",
441
+ )
442
+ result.plate_support_pass = _run_check(
443
+ ["plate", "bowl"],
444
+ lambda t, aid, atype: t is not None and t.ty > _MIN_SURFACE_H,
445
+ typed, transforms, v_errors,
446
+ "PLATE: '{aid}' on floor — must be on tabletop",
447
+ )
448
+
449
+ # Chair without table relationship
450
+ result.chair_table_relation_pass = _run_check(
451
+ ["chair"],
452
+ lambda t, aid, atype: t is not None and t.parent_id != "",
453
+ typed, transforms, v_errors,
454
+ "CHAIR: '{aid}' has no table relationship — no table in scene",
455
+ )
456
+
457
+ # Stool without bar
458
+ result.stool_bar_relation_pass = _run_check(
459
+ ["stool"],
460
+ lambda t, aid, atype: t is not None and t.parent_id != "",
461
+ typed, transforms, v_errors,
462
+ "STOOL: '{aid}' has no bar_counter relationship",
463
+ )
464
+
465
+ # Fireplace without wall anchor
466
+ def _fp_wall(t, aid, atype):
467
+ return (
468
+ t is not None
469
+ and (
470
+ "wall" in (t.parent_id or "")
471
+ or t.relationship == "attached_to"
472
+ )
473
+ )
474
+ result.fireplace_alignment_pass = _run_check(
475
+ ["fireplace"], _fp_wall, typed, transforms, v_errors,
476
+ "FIREPLACE: '{aid}' not aligned to wall anchor",
477
+ )
478
+
479
+ # Lantern not floating
480
+ def _lantern_ok(t, aid, atype):
481
+ if t is None:
482
+ return False
483
+ on_surface = t.ty > _MIN_SURFACE_H
484
+ on_wall = "wall" in (t.parent_id or "") or t.relationship == "attached_to"
485
+ return on_surface or on_wall
486
+ result.lantern_attachment_pass = _run_check(
487
+ ["lantern"], _lantern_ok, typed, transforms, v_errors,
488
+ "LANTERN: '{aid}' floating — must be on surface or wall-mounted",
489
+ )
490
+
491
+ # Barrel / crate near wall
492
+ def _near_wall(t, aid, atype):
493
+ if t is None:
494
+ return False
495
+ hw, hd = room["half_width"], room["half_depth"]
496
+ clearance = _NEAR_WALL_INSET + 0.5
497
+ # Consider "near wall" if within clearance of any perimeter
498
+ return (
499
+ abs(t.tx) > hw - clearance
500
+ or abs(t.tz) > hd - clearance
501
+ or "wall" in (t.parent_id or "")
502
+ or "corner" in (t.relationship or "")
503
+ )
504
+ result.barrel_wall_relation_pass = _run_check(
505
+ ["barrel", "oil_drum"],
506
+ _near_wall, typed, transforms, v_errors,
507
+ "BARREL: '{aid}' not near perimeter wall",
508
+ )
509
+ result.crate_wall_relation_pass = _run_check(
510
+ ["crate", "hay_bale"],
511
+ _near_wall, typed, transforms, v_errors,
512
+ "CRATE: '{aid}' not near perimeter wall",
513
+ )
514
+
515
+ # ================================================================
516
+ # PASS 5: Score
517
+ # ================================================================
518
+ # Re-derive from transforms: each placed asset's relationship
519
+ # matches its primary graph edge → count as valid.
520
+ total_scored = 0
521
+ valid_scored = 0
522
+
523
+ for edge in graph.get_all_edges():
524
+ fid = edge.from_node_id
525
+ if fid not in aid_to_asset:
526
+ continue # skip virtual nodes
527
+ total_scored += 1
528
+ t = transforms.get(fid)
529
+ if t is None:
530
+ continue
531
+ if _edge_satisfied(edge, t, transforms):
532
+ valid_scored += 1
533
+
534
+ rel_score = valid_scored / max(1, total_scored)
535
+
536
+ # ================================================================
537
+ # Assemble result
538
+ # ================================================================
539
+ result.relationship_aware_transforms = list(transforms.values())
540
+ result.relationship_score = round(rel_score, 4)
541
+ result.supported_objects = sorted(set(supported_ids))
542
+ result.wall_attached_objects = sorted(set(wall_ids))
543
+ result.surface_attached_objects = sorted(set(surface_ids))
544
+ result.orphan_relationships = orphan_rels
545
+ result.validation_errors = v_errors
546
+ result.ok = len(v_errors) == 0
547
+ result.status = (
548
+ RELATIONSHIP_LAYOUT_STATUS_PASS
549
+ if rel_score >= _PASS_THRESHOLD and len(v_errors) == 0
550
+ else RELATIONSHIP_LAYOUT_STATUS_FAIL
551
+ )
552
+
553
+ return result
554
+
555
+ # ==================================================================
556
+ # Placement sub-routines
557
+ # ==================================================================
558
+
559
+ def _place_anchors(
560
+ self,
561
+ typed: Dict[str, List[str]],
562
+ aid_to_asset: Dict[str, Dict[str, Any]],
563
+ aid_to_type: Dict[str, str],
564
+ room: Dict[str, Any],
565
+ ) -> Dict[str, ResolvedTransform]:
566
+ """Place all anchor assets at canonical scene positions."""
567
+ out: Dict[str, ResolvedTransform] = {}
568
+ hw, hd = room["half_width"], room["half_depth"]
569
+ ceiling_h = room["height"]
570
+
571
+ # --- Tables (hero centre) ---
572
+ tables = typed.get("table", [])
573
+ for idx, aid in enumerate(tables):
574
+ asset = aid_to_asset[aid]
575
+ # Offset multiple tables: first at origin, rest spread toward +Z
576
+ tz = float(idx) * 3.0
577
+ out[aid] = ResolvedTransform(
578
+ asset_id=aid, asset_name=_name(asset),
579
+ tx=0.0, ty=0.0, tz=tz,
580
+ ry=0.0,
581
+ relationship="anchor",
582
+ )
583
+
584
+ # --- Desks ---
585
+ for idx, aid in enumerate(typed.get("desk", [])):
586
+ out[aid] = ResolvedTransform(
587
+ asset_id=aid, asset_name=_name(aid_to_asset[aid]),
588
+ tx=float(idx) * 2.5 - 1.25, ty=0.0, tz=hd * 0.4,
589
+ ry=180.0, relationship="anchor",
590
+ )
591
+
592
+ # --- Workbenches ---
593
+ for idx, aid in enumerate(typed.get("workbench", [])):
594
+ out[aid] = ResolvedTransform(
595
+ asset_id=aid, asset_name=_name(aid_to_asset[aid]),
596
+ tx=float(idx) * 2.5 - 1.25, ty=0.0, tz=-(hd * 0.3),
597
+ ry=0.0, relationship="anchor",
598
+ )
599
+
600
+ # --- Bar counter (against back/north wall) ---
601
+ for idx, aid in enumerate(typed.get("bar_counter", [])):
602
+ out[aid] = ResolvedTransform(
603
+ asset_id=aid, asset_name=_name(aid_to_asset[aid]),
604
+ tx=0.0, ty=0.0, tz=-(hd * 0.7),
605
+ ry=0.0, relationship="anchor",
606
+ )
607
+
608
+ # --- Fireplace (against north wall, centred) ---
609
+ for idx, aid in enumerate(typed.get("fireplace", [])):
610
+ asset = aid_to_asset[aid]
611
+ # inset from wall by depth of fireplace (~0.5m) + wall gap
612
+ fp_depth = float(asset.get("depth_m") or asset.get("bbox_z") or 0.5)
613
+ tz_snap = -(hd - fp_depth * 0.5 - _WALL_INSET)
614
+ out[aid] = ResolvedTransform(
615
+ asset_id=aid, asset_name=_name(asset),
616
+ tx=0.0, ty=0.0, tz=tz_snap,
617
+ ry=0.0, # faces south (room interior)
618
+ parent_id="wall_north",
619
+ relationship="attached_to",
620
+ notes=f"back face on wall_north, wall_gap≤{_WALL_INSET}m",
621
+ )
622
+
623
+ # --- Machine / large machine ---
624
+ for idx, aid in enumerate(typed.get("machine", []) + typed.get("large_machine", [])):
625
+ out[aid] = ResolvedTransform(
626
+ asset_id=aid, asset_name=_name(aid_to_asset[aid]),
627
+ tx=float(idx) * 3.5, ty=0.0, tz=0.0,
628
+ ry=0.0, relationship="anchor",
629
+ )
630
+
631
+ # --- Campfire (outdoor / floor centred) ---
632
+ for idx, aid in enumerate(typed.get("campfire", [])):
633
+ out[aid] = ResolvedTransform(
634
+ asset_id=aid, asset_name=_name(aid_to_asset[aid]),
635
+ tx=0.0, ty=0.0, tz=0.0,
636
+ ry=0.0, relationship="anchor",
637
+ )
638
+
639
+ return out
640
+
641
+ def _place_asset(
642
+ self,
643
+ aid: str,
644
+ atype: str,
645
+ edges: List[RelationshipEdge],
646
+ transforms: Dict[str, ResolvedTransform],
647
+ typed: Dict[str, List[str]],
648
+ aid_to_asset: Dict[str, Dict[str, Any]],
649
+ aid_to_type: Dict[str, str],
650
+ room: Dict[str, Any],
651
+ ) -> Tuple[Optional[ResolvedTransform], int, int]:
652
+ """
653
+ Place one asset based on its relationship edges.
654
+
655
+ Returns (transform, n_relationships_total, n_relationships_satisfied).
656
+ Returns (None, 0, 0) if all edges failed and no fallback is possible.
657
+ """
658
+ if not edges:
659
+ t = self._fallback_placement(aid, atype, transforms, room)
660
+ return t, 0, 0
661
+
662
+ total = len(edges)
663
+ valid = 0
664
+ chosen: Optional[ResolvedTransform] = None
665
+
666
+ # Real-target edges first so a bottle placed near a real shelf
667
+ # wins over the virtual-table fallback that was injected by the
668
+ # graph builder when no table was in the scene.
669
+ sorted_edges = sorted(edges, key=lambda e: e.is_virtual_target)
670
+
671
+ # Walk edges in priority order — first satisfied edge wins placement.
672
+ for edge in sorted_edges:
673
+ t = self._place_for_edge(aid, atype, edge, transforms, typed, aid_to_asset, room)
674
+ if t is not None:
675
+ if chosen is None:
676
+ chosen = t # first successful edge determines placement
677
+ valid += 1
678
+ # else: edge target missing — try next
679
+
680
+ if chosen is None:
681
+ # All edges failed — use fallback
682
+ chosen = self._fallback_placement(aid, atype, transforms, room)
683
+
684
+ return chosen, total, valid
685
+
686
+ def _place_for_edge(
687
+ self,
688
+ aid: str,
689
+ atype: str,
690
+ edge: RelationshipEdge,
691
+ transforms: Dict[str, ResolvedTransform],
692
+ typed: Dict[str, List[str]],
693
+ aid_to_asset: Dict[str, Dict[str, Any]],
694
+ room: Dict[str, Any],
695
+ ) -> Optional[ResolvedTransform]:
696
+ rel = edge.relationship_type
697
+ tid = edge.to_node_id
698
+ asset = aid_to_asset.get(aid, {})
699
+
700
+ # ---- attached_to wall ----------------------------------------
701
+ if rel == "attached_to" and tid in ("wall", "wall_north", "wall_south",
702
+ "wall_east", "wall_west"):
703
+ return self._attach_to_wall(aid, atype, asset, room)
704
+
705
+ # ---- attached_to ceiling ------------------------------------
706
+ if rel == "attached_to" and tid == "ceiling":
707
+ h = room["height"]
708
+ return ResolvedTransform(
709
+ asset_id=aid, asset_name=_name(asset),
710
+ tx=0.0, ty=h - 0.2, tz=0.0,
711
+ parent_id="ceiling", relationship="attached_to",
712
+ notes="ceiling-mounted",
713
+ )
714
+
715
+ # ---- attached_to floor --------------------------------------
716
+ if rel == "attached_to" and tid == "floor":
717
+ return ResolvedTransform(
718
+ asset_id=aid, asset_name=_name(asset),
719
+ tx=0.0, ty=0.0, tz=0.0,
720
+ parent_id="floor", relationship="attached_to",
721
+ notes="floor-anchored",
722
+ )
723
+
724
+ # ---- belongs_near wall / corner (barrel, crate, bench) --------
725
+ # This must be checked BEFORE the general orbit belongs_near,
726
+ # since wall/corner targets are virtual and have no transform.
727
+ if rel in ("belongs_near",) and tid in (
728
+ "wall", "corner",
729
+ "wall_north", "wall_south", "wall_east", "wall_west",
730
+ ):
731
+ return self._place_near_wall(aid, atype, asset, typed, transforms, room)
732
+
733
+ # ---- belongs_near + faces furniture anchor -------------------
734
+ if rel in ("belongs_near", "faces", "around"):
735
+ target_t = transforms.get(tid)
736
+ if target_t is None:
737
+ # Try any real asset of the implied type in transforms
738
+ target_t = _first_transform_of_type(tid, typed, transforms)
739
+ if target_t is None:
740
+ return None # target not placed yet → signal retry
741
+
742
+ index = _chair_index_for_anchor(aid, tid, typed)
743
+ count = max(1, len(typed.get(atype, [])))
744
+ orbit_r = _orbit_radius(aid_to_asset.get(aid, {}), target_t, atype)
745
+ angle = (2 * math.pi / count) * index
746
+ tx = target_t.tx + orbit_r * math.sin(angle)
747
+ tz = target_t.tz + orbit_r * math.cos(angle)
748
+ ry = _face_toward(tx, tz, target_t.tx, target_t.tz)
749
+ return ResolvedTransform(
750
+ asset_id=aid, asset_name=_name(asset),
751
+ tx=round(tx, 4), ty=0.0, tz=round(tz, 4),
752
+ ry=round(ry, 2),
753
+ parent_id=tid, relationship="around",
754
+ notes=f"orbiting {tid} r={orbit_r:.2f}m",
755
+ )
756
+
757
+ # ---- supports (surface prop) --------------------------------
758
+ if rel in ("supports", "on_top_of"):
759
+ target_t = transforms.get(tid)
760
+ if target_t is None:
761
+ target_t = _first_transform_of_type(tid, typed, transforms)
762
+ tid_type = _type_from_tid(tid, typed)
763
+ surface_h = _SURFACE_HEIGHTS.get(tid_type, _DEFAULT_SURFACE_H)
764
+ index = _surface_prop_index(aid, tid, typed, atype)
765
+ if index >= _MAX_SURFACE_PROPS:
766
+ return None # surface full
767
+
768
+ if target_t is not None:
769
+ ox, oz = _SURFACE_XZ_OFFSETS[min(index, len(_SURFACE_XZ_OFFSETS) - 1)]
770
+ tx = round(target_t.tx + ox, 4)
771
+ tz = round(target_t.tz + oz, 4)
772
+ else:
773
+ tx = round(float(index) * 0.25 - 0.5, 4)
774
+ tz = 0.0
775
+
776
+ actual_tid = target_t.asset_id if target_t else tid
777
+ return ResolvedTransform(
778
+ asset_id=aid, asset_name=_name(asset),
779
+ tx=tx, ty=round(surface_h, 4), tz=tz,
780
+ parent_id=actual_tid, relationship="supports",
781
+ notes=f"on {tid_type} surface h={surface_h:.2f}m",
782
+ )
783
+
784
+ # ---- belongs_near wall (barrel, crate, bench) ---------------
785
+ if rel in ("belongs_near",) and tid in ("wall", "corner"):
786
+ return self._place_near_wall(aid, atype, asset, typed, transforms, room)
787
+
788
+ return None # unhandled edge type
789
+
790
+ def _attach_to_wall(
791
+ self,
792
+ aid: str,
793
+ atype: str,
794
+ asset: Dict[str, Any],
795
+ room: Dict[str, Any],
796
+ ) -> ResolvedTransform:
797
+ """Mount an asset on a wall at the canonical height for its type."""
798
+ walls = room["walls"]
799
+ idx = _wall_index_for_asset(aid, atype)
800
+ wall = walls[idx % len(walls)]
801
+ height = _WALL_MOUNT_HEIGHTS.get(atype, _DEFAULT_WALL_H)
802
+ ry = _wall_normal_to_ry(wall["normal"])
803
+
804
+ if wall["axis"] == "z":
805
+ tx = wall.get("x_spread", 0.0) * ((idx // len(walls)) % 3 - 1)
806
+ tz = wall["coord"] + wall["inset"]
807
+ else:
808
+ tx = wall["coord"] + wall["inset"]
809
+ tz = wall.get("z_spread", 0.0) * ((idx // len(walls)) % 3 - 1)
810
+
811
+ return ResolvedTransform(
812
+ asset_id=aid, asset_name=_name(asset),
813
+ tx=round(tx, 4), ty=round(height, 4), tz=round(tz, 4),
814
+ ry=round(ry, 2),
815
+ parent_id=wall["name"],
816
+ relationship="attached_to",
817
+ notes=f"wall={wall['name']} h={height:.2f}m",
818
+ )
819
+
820
+ def _place_near_wall(
821
+ self,
822
+ aid: str,
823
+ atype: str,
824
+ asset: Dict[str, Any],
825
+ typed: Dict[str, List[str]],
826
+ transforms: Dict[str, ResolvedTransform],
827
+ room: Dict[str, Any],
828
+ ) -> ResolvedTransform:
829
+ """Place a near-wall prop (barrel, crate, bench) along the perimeter."""
830
+ walls = room["walls"]
831
+ all_ids = typed.get(atype, [])
832
+ idx = all_ids.index(aid) if aid in all_ids else 0
833
+ wall = walls[idx % len(walls)]
834
+ # Spread multiple same-type items along the wall face
835
+ spread = float(idx // len(walls)) * 1.0 - 0.5
836
+
837
+ coord = wall["coord"]
838
+ # Inset from wall plane into the room interior
839
+ # sign(coord) points away from room centre → inset in opposite direction
840
+ room_inset = -math.copysign(_NEAR_WALL_INSET, coord)
841
+
842
+ if wall["axis"] == "z":
843
+ tx = round(spread, 4)
844
+ tz = round(coord + room_inset, 4)
845
+ else:
846
+ tx = round(coord + room_inset, 4)
847
+ tz = round(spread, 4)
848
+
849
+ return ResolvedTransform(
850
+ asset_id=aid, asset_name=_name(asset),
851
+ tx=tx, ty=0.0, tz=tz,
852
+ ry=0.0,
853
+ parent_id=wall["name"],
854
+ relationship="belongs_near",
855
+ notes=f"near {wall['name']}",
856
+ )
857
+
858
+ def _fallback_placement(
859
+ self,
860
+ aid: str,
861
+ atype: str,
862
+ transforms: Dict[str, ResolvedTransform],
863
+ room: Dict[str, Any],
864
+ ) -> ResolvedTransform:
865
+ """Place an asset with no satisfied edges at a reasonable fallback position."""
866
+ existing_count = sum(1 for t in transforms.values() if t.ty == 0.0)
867
+ spacing = 1.20
868
+ tx = round((existing_count % 5) * spacing - 2.4, 4)
869
+ tz = round((existing_count // 5) * spacing - 1.2, 4)
870
+ return ResolvedTransform(
871
+ asset_id=aid,
872
+ asset_name=atype,
873
+ tx=tx, ty=0.0, tz=tz,
874
+ relationship="scattered",
875
+ notes="fallback: no relationship edge satisfied",
876
+ )
877
+
878
+
879
+ # ===========================================================================
880
+ # Module-level helpers
881
+ # ===========================================================================
882
+
883
+ def _shell_to_dict(shell: Any) -> Dict[str, Any]:
884
+ if shell is None:
885
+ return {}
886
+ if isinstance(shell, dict):
887
+ return shell
888
+ if hasattr(shell, "to_dict"):
889
+ return shell.to_dict()
890
+ return {}
891
+
892
+
893
+ def _room_geometry(shell_dict: Dict[str, Any]) -> Dict[str, Any]:
894
+ """Derive room dimensions + wall definitions from shell dict (or defaults)."""
895
+ floor_area = float(shell_dict.get("floor_area", 0.0))
896
+ ceiling_h = float(shell_dict.get("ceiling_height", 0.0))
897
+
898
+ if floor_area > 0:
899
+ w = math.sqrt(floor_area / 1.2)
900
+ d = floor_area / w
901
+ else:
902
+ w, d = _DEFAULT_ROOM_W, _DEFAULT_ROOM_D
903
+
904
+ if ceiling_h <= 0:
905
+ ceiling_h = _DEFAULT_ROOM_H
906
+
907
+ hw, hd = w / 2.0, d / 2.0
908
+ _spread = min(hw * 0.6, 2.4)
909
+
910
+ walls = [
911
+ {
912
+ "name": "wall_north", "normal": [0, 0, -1],
913
+ "axis": "z", "coord": -hd, "inset": _WALL_INSET,
914
+ "x_spread": _spread,
915
+ },
916
+ {
917
+ "name": "wall_south", "normal": [0, 0, 1],
918
+ "axis": "z", "coord": hd, "inset": -_WALL_INSET,
919
+ "x_spread": _spread,
920
+ },
921
+ {
922
+ "name": "wall_east", "normal": [-1, 0, 0],
923
+ "axis": "x", "coord": hw, "inset": -_WALL_INSET,
924
+ "z_spread": _spread,
925
+ },
926
+ {
927
+ "name": "wall_west", "normal": [1, 0, 0],
928
+ "axis": "x", "coord": -hw, "inset": _WALL_INSET,
929
+ "z_spread": _spread,
930
+ },
931
+ ]
932
+
933
+ return {
934
+ "width": w, "depth": d, "height": ceiling_h,
935
+ "half_width": hw, "half_depth": hd,
936
+ "walls": walls,
937
+ }
938
+
939
+
940
+ def _aid(asset: Dict[str, Any]) -> str:
941
+ return str(asset.get("asset_id") or asset.get("name") or "").strip()
942
+
943
+
944
+ def _name(asset_or_str) -> str:
945
+ if isinstance(asset_or_str, dict):
946
+ return str(asset_or_str.get("name") or asset_or_str.get("asset_id") or "")
947
+ return str(asset_or_str)
948
+
949
+
950
+ def _wall_normal_to_ry(normal: List[float]) -> float:
951
+ nx = float(normal[0])
952
+ nz = float(normal[2]) if len(normal) > 2 else 0.0
953
+ return math.degrees(math.atan2(-nx, -nz)) % 360.0
954
+
955
+
956
+ def _face_toward(from_x: float, from_z: float, to_x: float, to_z: float) -> float:
957
+ """Return ry in degrees so that the asset at (from_x, from_z) faces (to_x, to_z)."""
958
+ dx = to_x - from_x
959
+ dz = to_z - from_z
960
+ return math.degrees(math.atan2(dx, dz)) % 360.0
961
+
962
+
963
+ def _orbit_radius(asset: Dict[str, Any], target_t: ResolvedTransform, atype: str) -> float:
964
+ # Table half-dimension from asset metadata (if available) or defaults
965
+ w = float(asset.get("width_m") or asset.get("bbox_x") or 0)
966
+ d = float(asset.get("depth_m") or asset.get("bbox_z") or 0)
967
+ own_half = max(w, d) / 2.0 if (w or d) else 0.0
968
+
969
+ # Target half from its bbox if available (fallback 0.5m)
970
+ target_half = 0.50
971
+ if atype in ("stool",):
972
+ return target_half + _STOOL_CLEARANCE
973
+ return target_half + own_half + _CHAIR_CLEARANCE
974
+
975
+
976
+ def _chair_index_for_anchor(aid: str, anchor_id: str, typed: Dict[str, List[str]]) -> int:
977
+ """Return the zero-based index of this chair within the chairs assigned to this anchor."""
978
+ all_chairs = typed.get("chair", []) + typed.get("stool", [])
979
+ for i, cid in enumerate(all_chairs):
980
+ if cid == aid:
981
+ return i
982
+ return 0
983
+
984
+
985
+ def _surface_prop_index(
986
+ aid: str,
987
+ target_id: str,
988
+ typed: Dict[str, List[str]],
989
+ atype: str,
990
+ ) -> int:
991
+ """Index of this prop among surface props of the same type targeting same surface."""
992
+ props = typed.get(atype, [])
993
+ for i, pid in enumerate(props):
994
+ if pid == aid:
995
+ return i
996
+ return 0
997
+
998
+
999
+ def _first_transform_of_type(
1000
+ target_type: str,
1001
+ typed: Dict[str, List[str]],
1002
+ transforms: Dict[str, ResolvedTransform],
1003
+ ) -> Optional[ResolvedTransform]:
1004
+ """Find the first placed transform whose type matches target_type."""
1005
+ for aid in typed.get(target_type, []):
1006
+ if aid in transforms:
1007
+ return transforms[aid]
1008
+ return None
1009
+
1010
+
1011
+ def _type_from_tid(tid: str, typed: Dict[str, List[str]]) -> str:
1012
+ """Reverse-lookup: find the type of a target node ID."""
1013
+ for atype, aids in typed.items():
1014
+ if tid in aids:
1015
+ return atype
1016
+ return tid # assume tid IS the type (e.g. virtual node "table")
1017
+
1018
+
1019
+ def _wall_index_for_asset(aid: str, atype: str) -> int:
1020
+ """Deterministic wall assignment from asset ID hash."""
1021
+ return hash(aid) % 4
1022
+
1023
+
1024
+ def _get_counted_set(edges_by_from: Dict[str, List[RelationshipEdge]]) -> Set[str]:
1025
+ return set(edges_by_from.keys())
1026
+
1027
+
1028
+ def _edge_satisfied(
1029
+ edge: RelationshipEdge,
1030
+ t: ResolvedTransform,
1031
+ transforms: Dict[str, ResolvedTransform],
1032
+ ) -> bool:
1033
+ """Return True if the transform satisfies the given relationship edge."""
1034
+ rel = edge.relationship_type
1035
+ tid = edge.to_node_id
1036
+
1037
+ # Virtual edges represent fallback rules. If the asset is validly placed
1038
+ # (on a surface or properly attached), the virtual fallback is satisfied —
1039
+ # the engine already chose a concrete placement that overrides it.
1040
+ if edge.is_virtual_target:
1041
+ return t.ty > _MIN_SURFACE_H or t.relationship in ("attached_to", "around", "belongs_near")
1042
+
1043
+ if rel in ("supports", "on_top_of"):
1044
+ return t.ty > _MIN_SURFACE_H
1045
+
1046
+ if rel == "attached_to":
1047
+ if tid in ("wall", "wall_north", "wall_south", "wall_east", "wall_west"):
1048
+ return "wall" in (t.parent_id or "") or t.relationship == "attached_to"
1049
+ if tid == "ceiling":
1050
+ return t.parent_id == "ceiling"
1051
+ if tid == "floor":
1052
+ return t.parent_id == "floor"
1053
+ return t.relationship == "attached_to"
1054
+
1055
+ if rel in ("belongs_near", "faces", "around"):
1056
+ # Valid if parent_id points to the right target (or same type virtual)
1057
+ return t.parent_id == tid or t.relationship in ("around", "belongs_near")
1058
+
1059
+ # For other types (inside, under, aligned_with, etc.), assume satisfied if placed
1060
+ return True
1061
+
1062
+
1063
+ def _run_check(
1064
+ asset_types: List[str],
1065
+ predicate,
1066
+ typed: Dict[str, List[str]],
1067
+ transforms: Dict[str, ResolvedTransform],
1068
+ errors: List[str],
1069
+ error_template: str,
1070
+ ) -> bool:
1071
+ passed = True
1072
+ for atype in asset_types:
1073
+ for aid in typed.get(atype, []):
1074
+ t = transforms.get(aid)
1075
+ if not predicate(t, aid, atype):
1076
+ errors.append(error_template.format(aid=aid, atype=atype))
1077
+ passed = False
1078
+ return passed
1079
+
1080
+
1081
+ # ---------------------------------------------------------------------------
1082
+ # Singleton
1083
+ # ---------------------------------------------------------------------------
1084
+
1085
+ _instance: Optional[RelationshipLayoutEngine] = None
1086
+ _lock = threading.Lock()
1087
+
1088
+
1089
+ def get_relationship_layout_engine() -> RelationshipLayoutEngine:
1090
+ global _instance
1091
+ if _instance is None:
1092
+ with _lock:
1093
+ if _instance is None:
1094
+ _instance = RelationshipLayoutEngine()
1095
+ return _instance
1096
+
1097
+
1098
+ def reset_relationship_layout_engine_for_tests() -> None:
1099
+ global _instance
1100
+ with _lock:
1101
+ _instance = None