File size: 37,644 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
3f15e9f
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
"""Public scene input contract for the portable whole-house generator.

This module is deliberately dependency-free. It turns a small, stable scene
description into the manifest/request pair consumed by the existing native
pipeline. Asset IDs are provenance supplied by the caller; this layer never
invents an asset to make a request appear ready.
"""
from __future__ import annotations

import copy
import json
import math
import re
from pathlib import Path
from typing import Any


SCHEMA = "rhg.scene-spec.v1"


class SceneSpecError(ValueError):
    """Raised when a public scene description cannot be compiled safely."""


_ROOM_ALIASES = {
    "living": ("living_room", "客厅", "起居室", "living room", "family room"),
    "kitchen": ("kitchen", "厨房"),
    "dining": ("dining_room", "餐厅", "dining room"),
    "bedroom": ("bedroom", "卧室", "主卧", "次卧"),
    "bathroom": ("bathroom", "卫生间", "厕所", "浴室", "bath room"),
    "study": ("study", "书房", "office", "办公室"),
    "hallway": ("hallway", "走廊", "过道", "hall"),
    "balcony": ("balcony", "阳台"),
}

_ENTITY_ALIASES = {
    "sofa": ("sofa", "couch", "沙发"),
    "television": ("television", "tv", "电视", "电视机"),
    "coffee_table": ("coffee table", "茶几"),
    "dining_table": ("dining table", "餐桌", "饭桌"),
    "kitchen_counter": ("kitchen counter", "counter", "料理台", "厨房台面"),
    "bed": ("bed", "床"),
    "desk": ("desk", "书桌", "办公桌"),
    "toilet": ("toilet", "马桶"),
    "sink": ("sink", "水槽", "洗手池"),
    "refrigerator": ("refrigerator", "fridge", "冰箱"),
    "plant": ("plant", "盆栽", "植物"),
    "lamp": ("lamp", "台灯", "落地灯"),
    "apple": ("apple", "苹果"),
    "bottle": ("bottle", "瓶子", "水瓶"),
    "cup": ("cup", "杯子", "水杯"),
    "plate": ("plate", "盘子"),
    "bowl": ("bowl", "碗"),
}

_DEFAULT_DIMENSIONS = {
    "sofa": [2.0, 0.9, 0.85],
    "television": [1.4, 0.15, 0.85],
    "coffee_table": [1.1, 0.6, 0.42],
    "dining_table": [1.6, 0.9, 0.75],
    "kitchen_counter": [2.0, 0.65, 0.9],
    "bed": [2.0, 1.6, 0.65],
    "desk": [1.2, 0.65, 0.75],
    "toilet": [0.7, 0.7, 0.8],
    "sink": [0.7, 0.55, 0.85],
    "refrigerator": [0.8, 0.75, 1.8],
    "plant": [0.35, 0.35, 1.0],
    "lamp": [0.3, 0.3, 1.2],
    "apple": [0.08, 0.08, 0.08],
    "bottle": [0.08, 0.08, 0.28],
    "cup": [0.09, 0.09, 0.12],
    "plate": [0.25, 0.25, 0.03],
    "bowl": [0.2, 0.2, 0.1],
}

_ROOM_DEFAULT_SIZE = {
    "living_room": [5.0, 4.0, 2.8],
    "kitchen": [3.5, 3.0, 2.8],
    "dining_room": [3.5, 3.0, 2.8],
    "bedroom": [4.0, 3.5, 2.8],
    "bathroom": [2.4, 2.2, 2.8],
    "study": [3.5, 3.0, 2.8],
    "hallway": [2.5, 1.8, 2.8],
    "balcony": [3.0, 1.8, 2.8],
    "indoor_room": [5.0, 4.0, 2.8],
}


def _text(value: Any, name: str) -> str:
    if not isinstance(value, str) or not value.strip():
        raise SceneSpecError(f"{name} must be a non-empty string")
    return value.strip()


def _finite(value: Any, name: str) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise SceneSpecError(f"{name} must be a finite number")
    return float(value)


def _vector(value: Any, count: int, name: str, *, positive: bool = False) -> list[float]:
    if not isinstance(value, (list, tuple)) or len(value) != count:
        raise SceneSpecError(f"{name} must contain {count} numbers")
    result = [_finite(item, name) for item in value]
    if positive and any(item <= 0 for item in result):
        raise SceneSpecError(f"{name} must be positive")
    return result


def _slug(value: str) -> str:
    value = re.sub(r"[^a-z0-9]+", "_", value.casefold()).strip("_")
    return value or "room"


def _first_alias(text: str, aliases: dict[str, tuple[str, ...]]) -> str | None:
    lowered = text.casefold()
    matches = []
    for key, values in aliases.items():
        for value in values:
            index = lowered.find(value.casefold())
            if index >= 0:
                matches.append((index, -len(value), key))
    return min(matches)[2] if matches else None


def _room_type(value: str) -> str:
    direct = {
        "living": "living_room",
        "dining": "dining_room",
        "bedroom": "bedroom",
        "bathroom": "bathroom",
        "study": "study",
        "kitchen": "kitchen",
        "hallway": "hallway",
        "balcony": "balcony",
    }
    if value.casefold() in direct:
        return direct[value.casefold()]
    key = _first_alias(value, _ROOM_ALIASES)
    if key is None:
        return _slug(value)
    return {
        "living": "living_room",
        "dining": "dining_room",
    }.get(key, key)


def _entity_category(value: str) -> str | None:
    return _first_alias(value, _ENTITY_ALIASES)


def _pack_rooms(rooms: list[dict[str, Any]]) -> list[dict[str, Any]]:
    cursor_x = 0.0
    result = []
    for row in rooms:
        item = copy.deepcopy(row)
        dimensions = item.get("dimensions_m") or _ROOM_DEFAULT_SIZE.get(
            item["room_type"], _ROOM_DEFAULT_SIZE["indoor_room"]
        )
        dimensions = _vector(dimensions, 3, f"rooms[{item['room_id']}].dimensions_m", positive=True)
        item["dimensions_m"] = dimensions
        if item.get("bounds_m") is None:
            item["bounds_m"] = [cursor_x, 0.0, cursor_x + dimensions[0], dimensions[1]]
        else:
            item["bounds_m"] = _vector(item["bounds_m"], 4, f"rooms[{item['room_id']}].bounds_m")
        x0, y0, x1, y1 = item["bounds_m"]
        if x1 <= x0 or y1 <= y0:
            raise SceneSpecError(f"room {item['room_id']} has invalid bounds_m")
        # Adjacent generated rooms share a boundary so a declared connection
        # can become a real portal. A caller can provide explicit bounds when
        # a gap or a non-linear floor plan is required.
        cursor_x = max(cursor_x, x1)
        result.append(item)
    return result


def _shared_door(room_a: dict[str, Any], room_b: dict[str, Any], connection: dict[str, Any], index: int) -> dict[str, Any]:
    ax0, ay0, ax1, ay1 = room_a["bounds_m"]
    bx0, by0, bx1, by1 = room_b["bounds_m"]
    width = float(connection.get("clear_width_m", 0.9))
    if abs(ax1 - bx0) <= 1e-6 or abs(bx1 - ax0) <= 1e-6:
        line = ax1 if abs(ax1 - bx0) <= 1e-6 else bx1
        low, high = max(ay0, by0), min(ay1, by1)
        if high <= low:
            raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} do not share a boundary")
        mid = (low + high) / 2.0
        interval = [max(low, mid - width / 2.0), min(high, mid + width / 2.0)]
        orientation = "V"
    elif abs(ay1 - by0) <= 1e-6 or abs(by1 - ay0) <= 1e-6:
        line = ay1 if abs(ay1 - by0) <= 1e-6 else by1
        low, high = max(ax0, bx0), min(ax1, bx1)
        if high <= low:
            raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} do not share a boundary")
        mid = (low + high) / 2.0
        interval = [max(low, mid - width / 2.0), min(high, mid + width / 2.0)]
        orientation = "H"
    else:
        raise SceneSpecError(f"rooms {room_a['room_id']} and {room_b['room_id']} are not adjacent")
    return {
        "door_id": connection.get("portal_id", f"portal_{index + 1}"),
        "room_ids": [room_a["room_id"], room_b["room_id"]],
        "wall_orientation": orientation,
        "wall_line_m": line,
        "door_interval_m": interval,
        "clear_width_m": width,
        "clear_height_m": float(connection.get("clear_height_m", 2.1)),
        "hinge_side": connection.get("hinge_side", "left"),
        "swing_room_id": connection.get("swing_room_id", room_a["room_id"]),
        "initial_open_fraction": float(connection.get("initial_open_fraction", 1.0)),
    }


def normalize_scene_spec(raw: dict[str, Any]) -> dict[str, Any]:
    if not isinstance(raw, dict):
        raise SceneSpecError("scene input must be an object")
    data = copy.deepcopy(raw)
    data.setdefault("schema", SCHEMA)
    if data["schema"] != SCHEMA:
        raise SceneSpecError(f"unsupported scene schema: {data['schema']}")
    seed = data.get("seed", 0)
    if isinstance(seed, bool) or not isinstance(seed, int):
        raise SceneSpecError("seed must be an integer")
    room_rows = data.get("rooms")
    if not isinstance(room_rows, list) or not room_rows:
        raise SceneSpecError("rooms must be a non-empty list")
    rooms = []
    room_ids = set()
    for index, row in enumerate(room_rows):
        if not isinstance(row, dict):
            raise SceneSpecError(f"rooms[{index}] must be an object")
        room_id = _text(row.get("room_id"), f"rooms[{index}].room_id")
        if room_id in room_ids:
            raise SceneSpecError(f"duplicate room_id: {room_id}")
        room_ids.add(room_id)
        rooms.append({
            "room_id": room_id,
            "room_type": _room_type(_text(row.get("room_type", room_id), f"rooms[{index}].room_type")),
            "dimensions_m": row.get("dimensions_m"),
            "bounds_m": row.get("bounds_m"),
        })
    rooms = _pack_rooms(rooms)
    room_by_id = {row["room_id"]: row for row in rooms}

    connections = []
    for index, row in enumerate(data.get("connections", [])):
        if not isinstance(row, dict):
            raise SceneSpecError(f"connections[{index}] must be an object")
        room_ids = row.get("room_ids") or []
        room_a = _text(row.get("room_a_id", room_ids[0] if len(room_ids) > 0 else None),
                       f"connections[{index}].room_a_id")
        room_b = _text(row.get("room_b_id", room_ids[1] if len(room_ids) > 1 else None),
                       f"connections[{index}].room_b_id")
        if room_a not in room_by_id or room_b not in room_by_id or room_a == room_b:
            raise SceneSpecError(f"connection {index} references invalid rooms")
        connections.append(_shared_door(room_by_id[room_a], room_by_id[room_b], row, index))

    entity_rows = data.get("entities", [])
    if not isinstance(entity_rows, list):
        raise SceneSpecError("entities must be a list")
    task_text = data.get("task_text", "")
    if not isinstance(task_text, str):
        raise SceneSpecError("task_text must be a string")
    entities = []
    entity_ids = set()
    for index, row in enumerate(entity_rows):
        if not isinstance(row, dict):
            raise SceneSpecError(f"entities[{index}] must be an object")
        entity_id = _text(row.get("entity_id"), f"entities[{index}].entity_id")
        room_id = _text(row.get("room_id"), f"entities[{index}].room_id")
        category = _slug(_text(row.get("category"), f"entities[{index}].category"))
        if entity_id in entity_ids:
            raise SceneSpecError(f"duplicate entity_id: {entity_id}")
        if room_id not in room_by_id:
            raise SceneSpecError(f"entity {entity_id} references unknown room {room_id}")
        entity_ids.add(entity_id)
        parent = row.get("support_entity_id", row.get("supported_by_entity_id"))
        candidates = row.get("candidate_asset_ids", [])
        if not isinstance(candidates, list) or any(
            not isinstance(item, str) or not item.strip() for item in candidates
        ):
            raise SceneSpecError(f"entities[{index}].candidate_asset_ids must be a string list")
        item = {
            "entity_id": entity_id,
            "room_id": room_id,
            "category": category,
            "role": row.get("role", category),
            "dimensions_m": _vector(
                row.get("dimensions_m", _DEFAULT_DIMENSIONS.get(category, [0.5, 0.5, 0.5])),
                3,
                f"entities[{index}].dimensions_m",
                positive=True,
            ),
            "candidate_asset_ids": list(dict.fromkeys(item.strip() for item in candidates)),
        }
        if row.get("asset_id") is not None:
            item["asset_id"] = _text(row["asset_id"], f"entities[{index}].asset_id")
        if parent is not None:
            item["support_entity_id"] = _text(parent, f"entities[{index}].support_entity_id")
        for key in ("center_xy_m", "yaw_deg", "base_z_m", "asset_query", "placement_hint", "requirements"):
            if key in row:
                item[key] = copy.deepcopy(row[key])
        entities.append(item)
    by_id = {row["entity_id"]: row for row in entities}
    for row in entities:
        parent = row.get("support_entity_id")
        if parent is not None:
            if parent not in by_id:
                raise SceneSpecError(f"unknown support entity: {parent}")
            if by_id[parent]["room_id"] != row["room_id"]:
                raise SceneSpecError(f"cross-room support is not allowed: {row['entity_id']}")

    tasks = []
    for index, row in enumerate(data.get("tasks", [])):
        if not isinstance(row, dict):
            raise SceneSpecError(f"tasks[{index}] must be an object")
        kind = _text(row.get("kind"), f"tasks[{index}].kind")
        subject = _text(row.get("subject_entity_id"), f"tasks[{index}].subject_entity_id")
        target = row.get("target_entity_id")
        if subject not in by_id:
            raise SceneSpecError(f"unknown task subject: {subject}")
        if target is not None and target not in by_id:
            raise SceneSpecError(f"unknown task target: {target}")
        # Validate known references, but keep caller predicates, parameters,
        # ordering, provenance and future task fields intact.
        item = copy.deepcopy(row)
        item.update({
            "kind": kind,
            "subject_entity_id": subject,
            "target_entity_id": target,
            "text": row.get("text"),
        })
        tasks.append(item)
    return {
        "schema": SCHEMA,
        "scene_id": _slug(str(data.get("scene_id", "scene"))),
        "seed": seed,
        "source": copy.deepcopy(data.get("source", {})),
        "description": data.get("description", ""),
        "task_text": task_text,
        "rooms": rooms,
        "connections": connections,
        "entities": entities,
        "tasks": tasks,
        "style": copy.deepcopy(data.get("style", {})),
        "constraints": copy.deepcopy(data.get("constraints", {})),
    }


def _find_entity(category: str, entities: list[dict[str, Any]]) -> dict[str, Any] | None:
    return next((row for row in entities if row["category"] == category), None)


_RESIDENTIAL_FURNISHING = {
    "living_room": ("sofa", "coffee_table", "television", "lamp"),
    "bedroom": ("bed", "wardrobe", "nightstand", "lamp"),
    "kitchen": ("kitchen_counter", "sink", "refrigerator", "stove", "dining_table", "dining_chair"),
    "bathroom": ("toilet", "sink", "shower"),
}


def _entity_mentions(text: str) -> list[tuple[int, int, str]]:
    aliases = {alias: category for category, values in _ENTITY_ALIASES.items() for alias in values}
    pattern = "|".join(
        (r"(?<![a-z0-9_])" + re.escape(alias) + r"(?![a-z0-9_])")
        if alias.isascii() else re.escape(alias)
        for alias in sorted(aliases, key=len, reverse=True)
    )
    return [(m.start(), m.end(), aliases[m.group().casefold()])
            for m in re.finditer(pattern, text, re.IGNORECASE)]


def _text_segments(text: str, *, split_commas: bool = False) -> list[str]:
    # A decimal point belongs to its number, not a sentence boundary.
    boundary = r"[。!!??;;]|\.(?!\d)"
    if split_commas:
        boundary += r"|[,,]"
    return [part.strip() for part in re.split(boundary, text) if part.strip()]


def _initial_support(text: str, entities: list[dict[str, Any]]) -> set[str]:
    """Read local stative relations; action destinations never set initial support."""
    initial_clauses = set()
    for clause in _text_segments(text, split_commas=True):
        mentions = _entity_mentions(clause)
        for index, mention in enumerate(mentions):
            prefix = clause[mentions[index - 1][1] if index else 0:mention[0]]
            # In "cup upright on table", upright describes the previous noun.
            prefix = re.split(r"放在|位于|\bon(?:\s+top\s+of)?\b", prefix, flags=re.IGNORECASE)[-1]
            suffix = clause[mention[1]:]
            entity = _find_entity(mention[2], entities)
            if entity is None:
                continue
            for key, pattern in (("upright", r"直立|竖直|\bupright\b"),
                                 ("graspable", r"可抓取|可抓握|\bgraspable\b")):
                if (re.search(pattern, prefix, re.IGNORECASE)
                        or re.match(r"\s*(?:is\s+)?(?:" + pattern + ")", suffix, re.IGNORECASE)):
                    entity.setdefault("requirements", {})[key] = True
        if re.search(r"把|将|机器人|\brobot\b|\b(?:place|put)\b|放到|放入", clause, re.IGNORECASE):
            continue
        for first, second in zip(mentions, mentions[1:]):
            between = clause[first[1]:second[0]]
            suffix = clause[second[1]:]
            if re.match(r"(?:上面?|顶部)", between):
                parent_category, child_category = first[2], second[2]
            elif (re.search(r"\bon(?:\s+top\s+of)?\b", between, re.IGNORECASE)
                  or (re.search(r"在|位于", between) and re.match(r"上", suffix))):
                child_category, parent_category = first[2], second[2]
            else:
                continue
            child, parent = _find_entity(child_category, entities), _find_entity(parent_category, entities)
            if child is None or parent is None or child is parent:
                continue
            child["room_id"] = parent["room_id"]
            child["support_entity_id"] = parent["entity_id"]
            initial_clauses.add(clause.strip())
    return initial_clauses


def _task_measurement(text: str, action: str, units: dict[str, float], name: str) -> float | None:
    """Read a literal action measurement; missing values remain unresolved."""
    match = re.search(r"(?:" + action + r")\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*", text, re.IGNORECASE)
    if match is None:
        return None
    unit_pattern = "|".join(re.escape(unit) for unit in sorted(units, key=len, reverse=True))
    unit = re.match(r"(?:" + unit_pattern + r")(?![a-z])", text[match.end():], re.IGNORECASE)
    if unit is None:
        raise SceneSpecError(f"{name} requires a supported unit")
    value = _finite(float(match.group(1)), name) * units[unit.group().casefold()]
    if value <= 0:
        raise SceneSpecError(f"{name} must be positive")
    return value


def _robot_task_contract(text: str, entities: list[dict[str, Any]],
                         rooms: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any], str]:
    """Compile a grasp/lift instruction without inventing execution qualification."""
    for segment in _text_segments(text):
        grasp = re.search(r"抓住|抓取|抓握|\bgrasp\b", segment, re.IGNORECASE)
        lift = re.search(r"举起|抬起|\blift\b", segment, re.IGNORECASE)
        if not grasp or not lift:
            continue
        subject = _find_entity(_entity_category(segment[grasp.end():]) or "", entities)
        if subject is None:
            continue
        navigation = re.search(r"到达|走到|移动到|\bnavigate\s+to\b|\bapproach\b", segment, re.IGNORECASE)
        target = (_find_entity(_entity_category(segment[navigation.end():]) or "", entities)
                  if navigation else None)
        if target is None and subject.get("support_entity_id"):
            target = next(row for row in entities if row["entity_id"] == subject["support_entity_id"])
        start_match = re.search(r"从(.+?)(?:出发|起点)|\bfrom\s+(.+?)(?:,|\bto\b|$)", segment, re.IGNORECASE)
        start_type = _first_alias(start_match.group() if start_match else "", _ROOM_ALIASES)
        start_room = next((row["room_id"] for row in rooms
                           if start_type and row["room_type"] == _room_type(start_type)), None)
        parameters = {
            "lift_height_m": _task_measurement(segment, r"举起|抬起|\blift\b", {
                "毫米": 0.001, "mm": 0.001, "厘米": 0.01, "公分": 0.01, "cm": 0.01,
                "米": 1.0, "m": 1.0,
            }, "lift_height_m"),
            "hold_duration_s": _task_measurement(segment, r"保持|维持|\bhold(?:\s+for)?\b", {
                "秒": 1.0, "s": 1.0, "second": 1.0, "seconds": 1.0,
            }, "hold_duration_s"),
        }
        robot = {
            "model": None, "footprint_m": None, "reach_m": None,
            **parameters,
            "start": {"room_id": start_room, "position_xy_m": None, "yaw_deg": None,
                      "status": "unresolved_until_layout"},
        }
        subject_id = subject["entity_id"]
        held = {"predicate": "held_by", "subject_entity_id": subject_id, "agent_id": "robot"}
        near = {"predicate": "near", "agent_id": "robot",
                "target_entity_id": target["entity_id"] if target else subject_id}
        initial = [{"predicate": key, "subject_entity_id": subject_id}
                   for key, required in subject.get("requirements", {}).items() if required is True]
        if subject.get("support_entity_id"):
            initial.append({"predicate": "supported_by", "subject_entity_id": subject_id,
                            "target_entity_id": subject["support_entity_id"]})
        if not any(row["predicate"] == "graspable" for row in initial):
            initial.append({"predicate": "graspable", "subject_entity_id": subject_id})
        steps = []
        if navigation:
            steps.append(("navigate", [{"predicate": "at_start", "agent_id": "robot"}], [near]))
        steps.extend([
            ("grasp", ([near] if navigation else []) + initial, [held]),
            ("lift", [held], [held, {"predicate": "above_initial_height", "subject_entity_id": subject_id,
                                     "min_height_m": parameters["lift_height_m"],
                                     "hold_duration_s": parameters["hold_duration_s"]}]),
        ])
        tasks = []
        for order, (kind, preconditions, success) in enumerate(steps, 1):
            tasks.append({
                "task_id": f"{kind}_{order}", "kind": kind, "order": order, "agent_id": "robot",
                "subject_entity_id": subject_id,
                "target_entity_id": target["entity_id"] if kind == "navigate" and target else None,
                "depends_on": [tasks[-1]["task_id"]] if tasks else [],
                "preconditions": copy.deepcopy(preconditions), "success_predicates": copy.deepcopy(success),
                "parameters": copy.deepcopy(parameters) if kind == "lift" else {},
                "text": segment.strip(),
            })
        space = {
            "navigation": {"required": True, "clearance_m": None},
            "docking": {"required": True, "clearance_m": None,
                        "target_entity_id": target["entity_id"] if target else subject_id},
            "manipulation": {"required": True, "clearance_m": None, "target_entity_id": subject_id},
        }
        return tasks, {"robot": robot, "robot_space": space}, segment.strip()
    return [], {}, ""


def _furnish_residence(rooms: list[dict[str, Any]], entities: list[dict[str, Any]]) -> dict[str, Any]:
    required_by_room = {}
    for room in rooms:
        categories = _RESIDENTIAL_FURNISHING.get(room["room_type"], ())
        required_by_room[room["room_id"]] = list(categories)
        for category in categories:
            if any(row["room_id"] == room["room_id"] and row["category"] == category for row in entities):
                continue
            entity_id = category if _find_entity(category, entities) is None else f"{room['room_id']}_{category}"
            entities.append({"entity_id": entity_id, "room_id": room["room_id"], "category": category,
                             "requirements": {"best_effort_furnishing": True}})
    return {"profile": "complete_residential", "required_by_room": required_by_room}


def parse_text_scene(description: str, *, seed: int = 0,
                     room_inventory: list[dict[str, Any]] | None = None) -> dict[str, Any]:
    """Parse unchanged text, optionally binding furniture to selected rooms.

    The caller validates explicit topology constraints before supplying the
    inventory. Only IDs/types are used here; align_to_shell owns real geometry.
    """
    text = _text(description, "description")
    room_types = []
    for key, aliases in _ROOM_ALIASES.items():
        if any(alias.casefold() in text.casefold() for alias in aliases):
            room_types.append({"room_id": {"living": "living", "dining": "dining"}.get(key, key),
                               "room_type": _room_type(key)})
    count_match = re.search(r"([一二两三四五六七八九十]|\d+)\s*室", text)
    if count_match:
        # An explicit count replaces the unnumbered bedroom alias.
        room_types = [row for row in room_types if row["room_type"] != "bedroom"]
        count_token = count_match.group(1)
        count = {"一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5,
                 "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}.get(count_token, int(count_token) if count_token.isdigit() else 1)
        for index in range(1, count + 1):
            if not any(row["room_type"] == "bedroom" and row["room_id"] == f"bedroom_{index}" for row in room_types):
                room_types.append({"room_id": f"bedroom_{index}", "room_type": "bedroom"})
    if "厅" in text and not any(row["room_type"] == "living_room" for row in room_types):
        room_types.append({"room_id": "living", "room_type": "living_room"})
    unique_rooms = []
    seen_room_ids = set()
    for room in room_types:
        if room["room_id"] not in seen_room_ids:
            unique_rooms.append(room)
            seen_room_ids.add(room["room_id"])
    room_types = unique_rooms
    if not room_types:
        room_types = [{"room_id": "room_1", "room_type": "indoor_room"}]
    entity_rooms = room_types
    if room_inventory is not None:
        if not isinstance(room_inventory, list) or not room_inventory:
            raise SceneSpecError('room_inventory must be a non-empty list')
        selected_rooms = []
        for index, room in enumerate(room_inventory):
            if not isinstance(room, dict):
                raise SceneSpecError(f'room_inventory[{index}] must be an object')
            selected_rooms.append({
                'room_id': _text(room.get('room_id'), f'room_inventory[{index}].room_id'),
                'room_type': _room_type(_text(room.get('room_type'), f'room_inventory[{index}].room_type')),
            })
        by_id = {room['room_id']:room for room in selected_rooms}
        if len(by_id) != len(selected_rooms):
            raise SceneSpecError('room_inventory contains duplicate room IDs')
        # This flat parser has no clause-to-bedroom-role binding. Inventory
        # expansion must not make an explicit secondary/child room silently
        # refer to the first bedroom. Structured room IDs/purposes bypass this
        # text-only path and retain their existing alignment semantics.
        target = re.search(
            r'主卧|次卧|客卧|儿童房|儿童卧室|'
            r'第\s*[一二两三四五六七八九十\d]+\s*(?:间)?卧室|'
            r'(?<![a-z])(?:master|primary|guest|secondary|children|child|kids?)'
            r"(?:['’]s)?[\s_]+(?:bedroom|room)(?![a-z])|"
            r'(?<![a-z])bedroom[\s_#-]*\d+', text, re.IGNORECASE)
        if target:
            raise SceneSpecError(
                f'Unsupported explicit room target: {target.group(0)!r}. '
                'Use an explicit room_id and room purpose in a structured scene specification.')
        # Preserve the mentioned-room priority for explicit furniture. Extra
        # selected rooms participate only in the complete-home defaults below.
        # In particular, a bathroom sink must not move to an unmentioned kitchen.
        entity_rooms = []
        seen = set()
        for nominal in room_types:
            matches = ([by_id[nominal['room_id']]] if nominal['room_id'] in by_id else
                       [room for room in selected_rooms if room['room_type'] == nominal['room_type']])
            if not matches and nominal['room_type'] != 'indoor_room':
                raise SceneSpecError('Input text references a room absent from the native shell: '+nominal['room_id'])
            for room in matches:
                if room['room_id'] not in seen:
                    entity_rooms.append(room)
                    seen.add(room['room_id'])
        entity_rooms = entity_rooms or selected_rooms
        room_types = entity_rooms + [room for room in selected_rooms if room not in entity_rooms]
    entities = []
    for category, aliases in _ENTITY_ALIASES.items():
        if not any(alias.casefold() in text.casefold() for alias in aliases):
            continue
        category_room_types = {
            "sofa": {"living_room"}, "television": {"living_room"},
            "coffee_table": {"living_room"}, "dining_table": {"kitchen", "dining_room"},
            "kitchen_counter": {"kitchen"}, "refrigerator": {"kitchen"},
            "sink": {"kitchen", "bathroom"}, "bed": {"bedroom"},
            "desk": {"study"}, "toilet": {"bathroom"},
        }.get(category, set())
        room_id = next((room["room_id"] for room in entity_rooms
                        if room["room_type"] in category_room_types), entity_rooms[0]["room_id"])
        entities.append({"entity_id": category, "room_id": room_id, "category": category})
    initial_clauses = _initial_support(text, entities)
    task_subject = task_target = None
    task_segment = None
    for segment in reversed(_text_segments(text, split_commas=True)):
        if segment.strip() in initial_clauses:
            continue
        if re.search(r"放到|放在|放入|place\s+|put\s+", segment, re.IGNORECASE):
            task_segment = segment.strip()
            break
    if task_segment:
        chinese_match = re.search(r"(?:(?:把|将)\s*)?(.+?)(?:放到|放在|放入)(.+?)(?:上|里|中)?$", task_segment)
        if chinese_match:
            task_subject = _entity_category(chinese_match.group(1))
            task_target = _entity_category(chinese_match.group(2))
        else:
            english_match = re.search(r"(?:place|put)\s+(.+?)\s+(?:on|in|into)\s+(.+)$", task_segment, re.IGNORECASE)
            if english_match:
                task_subject = _entity_category(english_match.group(1))
                task_target = _entity_category(english_match.group(2))
    tasks = []
    if task_subject and task_target:
        for category, room_id in ((task_subject, entity_rooms[0]["room_id"]), (task_target, entity_rooms[0]["room_id"])):
            if _find_entity(category, entities) is None:
                entities.append({"entity_id": category, "room_id": room_id, "category": category})
        tasks.append({"kind": "place_on", "subject_entity_id": task_subject,
                      "target_entity_id": task_target, "text": task_segment})
    robot_tasks, constraints, robot_task_text = _robot_task_contract(text, entities, room_types)
    tasks.extend(robot_tasks)
    if robot_task_text:
        task_segment = robot_task_text
    if re.search(r"完整住宅|完整的住宅|完整家居|\bcomplete\s+(?:home|residence)\b", text, re.IGNORECASE):
        constraints["furnishing"] = _furnish_residence(room_types, entities)
    connections = []
    for index in range(len(entity_rooms) - 1):
        connections.append({"portal_id": f"portal_{index + 1}",
                            "room_a_id": entity_rooms[index]["room_id"],
                            "room_b_id": entity_rooms[index + 1]["room_id"],
                            "kind": "door"})
    return normalize_scene_spec({
        "schema": SCHEMA,
        "scene_id": "text_scene",
        "seed": seed,
        "source": {"kind": "text", "text": text},
        "description": text,
        "task_text": task_segment or "",
        "rooms": room_types,
        "connections": connections,
        "entities": entities,
        "tasks": tasks,
        "constraints": constraints,
    })


def compile_native_inputs(spec: dict[str, Any]) -> dict[str, Any]:
    normalized = normalize_scene_spec(spec)
    room_by_id = {row["room_id"]: row for row in normalized["rooms"]}
    doors = []
    for index, connection in enumerate(normalized["connections"]):
        room_a = room_by_id[connection["room_ids"][0]]
        room_b = room_by_id[connection["room_ids"][1]]
        doors.append(_shared_door(room_a, room_b, connection, index))
    manifest_entities = []
    request_entities = []
    furniture = []
    unresolved = []
    all_locked = True
    for row in normalized["entities"]:
        entity = {
            "entity_id": row["entity_id"],
            "room_id": row["room_id"],
            "role": row["role"],
            "category": row["category"],
            "dimensions_m": row["dimensions_m"],
            "center_xy_m": row.get("center_xy_m", [
                sum(room_by_id[row["room_id"]]["bounds_m"][::2]) / 2.0,
                sum(room_by_id[row["room_id"]]["bounds_m"][1::2]) / 2.0,
            ]),
            "yaw_deg": row.get("yaw_deg", 0.0),
            "base_z_m": row.get("base_z_m", 0.0),
        }
        if row.get("support_entity_id") is not None:
            entity["support_entity_id"] = row["support_entity_id"]
        if "requirements" in row:
            entity["requirements"] = copy.deepcopy(row["requirements"])
        if row.get("asset_id") is not None:
            entity["asset_id"] = row["asset_id"]
            furniture.append({"entity_id": row["entity_id"], "asset_id": row["asset_id"]})
        else:
            candidates = list(row.get("candidate_asset_ids", []))
            all_locked = False
            if not candidates:
                unresolved.append(row["entity_id"])
            furniture.append({"entity_id": row["entity_id"], "candidate_asset_ids": candidates})
        manifest_entities.append(entity)
        # requested_shell projects real asset geometry. Nominal dimensions and
        # asset identity belong to the manifest/furniture map, not definitions.
        definition = {key: copy.deepcopy(entity[key]) for key in
                      ("entity_id", "room_id", "role", "category", "requirements") if key in entity}
        for source_key, preferred_key in (("center_xy_m", "preferred_center_xy_m"), ("yaw_deg", "preferred_yaw_deg")):
            if source_key in row:
                definition[preferred_key] = copy.deepcopy(row[source_key])
        if row.get("support_entity_id") is not None:
            definition.update(supported_by_entity_id=row["support_entity_id"],
                              support_relation="on_top", layout_relation="on_top")
        request_entities.append(definition)
    manifest = {
        "schema": "rhg.scene-manifest.v1",
        "scene_id": normalized["scene_id"],
        "seed": normalized["seed"],
        "source": normalized["source"],
        "floor_plan": {"rooms": normalized["rooms"], "doors": doors},
        "entities": manifest_entities,
        "style": normalized["style"],
    }
    request = {
        "schema": "rhg.scene_request.v1",
        "mode": "locked" if all_locked and not unresolved else "pool",
        "task_kind": "scene_generation",
        "task_text": normalized["task_text"] or normalized["description"] or normalized["scene_id"],
        "seed": normalized["seed"],
        "entities": request_entities,
        "furniture": furniture,
        "tasks": copy.deepcopy(normalized["tasks"]),
        "constraints": copy.deepcopy(normalized["constraints"]),
    }
    return {
        "schema": "rhg.scene-compile-result.v1",
        "scene_spec": normalized,
        "manifest": manifest,
        "request": request,
        "unresolved_assets": sorted(unresolved),
        "ready_for_native_generation": not unresolved,
    }


def write_scene_bundle(spec: dict[str, Any], output: str | Path) -> dict[str, Path]:
    """Write the portable input bundle used by the existing whole-house runner."""
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    compiled = compile_native_inputs(spec)
    payloads = {
        "scene_spec": compiled["scene_spec"],
        "manifest": compiled["manifest"],
        "request": compiled["request"],
        "asset_requirements": {
            "schema": "rhg.asset-requirements.v1",
            "ready_for_native_generation": compiled["ready_for_native_generation"],
            "unresolved_assets": compiled["unresolved_assets"],
            "entities": [
                {
                    "entity_id": row["entity_id"],
                    "category": row["category"],
                    "candidate_asset_ids": list(row.get("candidate_asset_ids", [])),
                    "asset_id": row.get("asset_id"),
                }
                for row in compiled["scene_spec"]["entities"]
            ],
        },
        "compile_result": compiled,
        "run_config": {
            "schema": "rhg.frontier-chain-config.v1",
            "manifest": "manifest.json",
            "request": "request.json",
            "geometry_validation": {"enabled": True},
        },
    }
    paths = {}
    for name, payload in payloads.items():
        path = output / (name + ".json")
        path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        paths[name] = path
    return paths