Mirror public GitHub main c456a7d (6/25)
Browse files- .gitattributes +1 -0
- runtime/h2_runtime/fonts/DejaVuSansMono.ttf +3 -0
- runtime/h2_runtime/medium88_clues.py +296 -0
- runtime/h2_runtime/medium88_final_details.py +23 -0
- runtime/h2_runtime/medium88_game.py +245 -0
- runtime/h2_runtime/medium88_numeric_binding.py +99 -0
- runtime/h2_runtime/medium88_polished.py +89 -0
- runtime/h2_runtime/medium88_room_details.py +102 -0
- runtime/h2_runtime/medium88_scene.py +996 -0
- runtime/h2_runtime/medium88_specs.py +120 -0
- runtime/h2_runtime/medium88_wire_identity.py +15 -0
- runtime/h2_runtime/medium_next_base.py +397 -0
- runtime/h2_runtime/medium_v6.py +660 -0
- runtime/h2_runtime/model_content554.py +81 -0
- runtime/h2_runtime/native_primitives364.py +506 -0
- runtime/h2_runtime/observation1280.py +39 -0
- runtime/h2_runtime/oracle355.py +139 -0
- runtime/h2_runtime/oracle560.py +54 -0
- runtime/h2_runtime/pixel355.py +245 -0
- runtime/h2_runtime/preview_four.py +52 -0
- runtime/h2_runtime/protocol.py +123 -0
- runtime/h2_runtime/rack_press_quality.py +358 -0
- runtime/h2_runtime/room_art364.py +174 -0
- runtime/h2_runtime/room_decor_quality.py +175 -0
- runtime/h2_runtime/text_layout_quality.py +97 -0
- runtime/legacy_entry.py +58 -0
- runtime/legacy_metrics/checkpoint_bank268_v2.json +0 -0
- runtime/legacy_metrics/frozen_default.json +7 -0
- runtime/legacy_metrics/milestone_checkpoints268.py +279 -0
- runtime/legacy_metrics/milestone_filter268.py +91 -0
- runtime/legacy_resume.py +87 -0
- runtime/legacy_scene_bootstrap.py +97 -0
- runtime/legacy_source/cabinet_joint345/MODIFIED_FILE.py +610 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
runtime/h2_runtime/fonts/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
|
runtime/h2_runtime/fonts/DejaVuSansMono.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:602ec86b8948cfcd956482fe64f94c36c867770149ef2f791d4613f443bcecb3
|
| 3 |
+
size 340240
|
runtime/h2_runtime/medium88_clues.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageDraw, ImageOps
|
| 2 |
+
import math
|
| 3 |
+
from font_utils import load_font
|
| 4 |
+
from easy88_clues import draw_symbol, render_clue
|
| 5 |
+
PAPER = (228, 219, 194)
|
| 6 |
+
INK = (37, 46, 45)
|
| 7 |
+
BLUE = (65, 98, 111)
|
| 8 |
+
|
| 9 |
+
def text(d, p, value, size=42):
|
| 10 |
+
d.text(p, str(value), font=load_font(size), fill=INK, anchor='mm')
|
| 11 |
+
|
| 12 |
+
def symbol(d, value, box):
|
| 13 |
+
if value is None:
|
| 14 |
+
return
|
| 15 |
+
v = str(value)
|
| 16 |
+
if ':' in v and (not v.startswith('clock:')):
|
| 17 |
+
a, b = v.rsplit(':', 1)
|
| 18 |
+
symbol(d, a, (box[0], box[1], box[2], box[3] - 25))
|
| 19 |
+
text(d, ((box[0] + box[2]) / 2, box[3] - 8), b, 30)
|
| 20 |
+
return
|
| 21 |
+
if v.startswith('clock:'):
|
| 22 |
+
im = render_clue({'visual': {'type': 'clock', 'hour': int(v[6:].split(':')[0]), 'minute': int(v.split(':')[-1].split()[0]), 'period': v.split()[-1]}})
|
| 23 |
+
im = im.resize((int(box[2] - box[0]), int(box[3] - box[1])))
|
| 24 |
+
d._image.paste(im, (int(box[0]), int(box[1])))
|
| 25 |
+
return
|
| 26 |
+
x, y, X, Y = box
|
| 27 |
+
cx = (x + X) / 2
|
| 28 |
+
cy = (y + Y) / 2
|
| 29 |
+
w = X - x
|
| 30 |
+
h = Y - y
|
| 31 |
+
if v in ('sun', 'moon'):
|
| 32 |
+
d.ellipse((x + w * 0.18, y + h * 0.18, X - w * 0.18, Y - h * 0.18), fill=(183, 143, 58), outline=INK, width=3)
|
| 33 |
+
if v == 'moon':
|
| 34 |
+
d.ellipse((x + w * 0.43, y + h * 0.06, X - w * 0.04, Y - h * 0.25), fill=PAPER)
|
| 35 |
+
elif v in ('crosshatch', 'waves', 'grid', 'dots'):
|
| 36 |
+
if v == 'dots':
|
| 37 |
+
for a, b in [(0, 0), (1, 0), (0, 1), (1, 1)]:
|
| 38 |
+
d.ellipse((cx + (a - 0.5) * w * 0.45 - 9, cy + (b - 0.5) * h * 0.45 - 9, cx + (a - 0.5) * w * 0.45 + 9, cy + (b - 0.5) * h * 0.45 + 9), fill=INK)
|
| 39 |
+
elif v == 'crosshatch':
|
| 40 |
+
d.line((x + w * 0.2, y + h * 0.2, X - w * 0.2, Y - h * 0.2), fill=INK, width=7)
|
| 41 |
+
d.line((x + w * 0.2, Y - h * 0.2, X - w * 0.2, y + h * 0.2), fill=INK, width=7)
|
| 42 |
+
elif v == 'grid':
|
| 43 |
+
for a in [0.35, 0.65]:
|
| 44 |
+
d.line((x + w * a, y + h * 0.15, x + w * a, Y - h * 0.15), fill=INK, width=5)
|
| 45 |
+
d.line((x + w * 0.15, y + h * a, X - w * 0.15, y + h * a), fill=INK, width=5)
|
| 46 |
+
else:
|
| 47 |
+
for a in [0.25, 0.5, 0.75]:
|
| 48 |
+
d.line([(x + w * t / 30, y + h * (a + 0.07 * math.sin(t * 0.7))) for t in range(3, 28)], fill=INK, width=5)
|
| 49 |
+
elif v in ('round_lid', 'tall_cup', 'square_can', 'handled_cup', 'round_pot', 'round_cup', 'square_box', 'box'):
|
| 50 |
+
if v in ('square_can', 'square_box', 'box'):
|
| 51 |
+
d.rectangle((x + w * 0.18, y + h * 0.22, X - w * 0.18, Y - h * 0.15), fill=BLUE, outline=INK, width=4)
|
| 52 |
+
else:
|
| 53 |
+
d.rounded_rectangle((x + w * 0.2, y + h * 0.27, X - w * 0.2, Y - h * 0.15), radius=10, fill=BLUE, outline=INK, width=4)
|
| 54 |
+
d.ellipse((x + w * 0.2, y + h * 0.18, X - w * 0.2, y + h * 0.38), fill=PAPER, outline=INK, width=4)
|
| 55 |
+
if v in ('handled_cup', 'round_cup'):
|
| 56 |
+
d.arc((x + w * 0.6, y + h * 0.35, X - w * 0.03, y + h * 0.75), 270, 90, fill=INK, width=6)
|
| 57 |
+
if v in ('round_lid', 'round_pot'):
|
| 58 |
+
d.ellipse((x + w * 0.25, y + h * 0.15, X - w * 0.25, y + h * 0.28), fill=BLUE, outline=INK, width=3)
|
| 59 |
+
d.rectangle((cx - 6, y + h * 0.1, cx + 6, y + h * 0.18), fill=INK)
|
| 60 |
+
elif v in ('brush', 'comb', 'ruler', 'clip', 'hook', 'scroll', 'leaf_clip', 'star_plate', 'triangle_plate'):
|
| 61 |
+
if v == 'comb':
|
| 62 |
+
d.rectangle((x + w * 0.12, y + h * 0.25, X - w * 0.12, y + h * 0.4), fill=BLUE)
|
| 63 |
+
for a in range(7):
|
| 64 |
+
d.rectangle((x + w * (0.15 + a * 0.1), y + h * 0.4, x + w * (0.19 + a * 0.1), Y - h * 0.2), fill=BLUE)
|
| 65 |
+
elif v == 'brush':
|
| 66 |
+
d.rectangle((cx - 10, y + h * 0.15, cx + 10, Y - h * 0.15), fill=(139, 99, 54))
|
| 67 |
+
d.rectangle((x + w * 0.18, y + h * 0.14, X - w * 0.18, y + h * 0.45), fill=BLUE)
|
| 68 |
+
elif v == 'ruler':
|
| 69 |
+
d.rectangle((x + w * 0.15, cy - h * 0.12, X - w * 0.15, cy + h * 0.12), fill=(165, 143, 92), outline=INK, width=3)
|
| 70 |
+
for a in range(8):
|
| 71 |
+
d.line((x + w * (0.2 + a * 0.08), cy - h * 0.12, x + w * (0.2 + a * 0.08), cy), fill=INK, width=2)
|
| 72 |
+
elif v == 'hook':
|
| 73 |
+
d.arc((x + w * 0.25, y + h * 0.3, X - w * 0.25, Y - h * 0.15), 0, 250, fill=INK, width=8)
|
| 74 |
+
d.line((X - w * 0.25, cy, x + w * 0.75, y + h * 0.15), fill=INK, width=8)
|
| 75 |
+
elif v == 'scroll':
|
| 76 |
+
d.rectangle((x + w * 0.2, y + h * 0.25, X - w * 0.2, Y - h * 0.25), fill=(198, 177, 132), outline=INK, width=3)
|
| 77 |
+
d.ellipse((x + w * 0.15, y + h * 0.15, x + w * 0.3, Y - h * 0.15), fill=PAPER, outline=INK, width=3)
|
| 78 |
+
elif v == 'clip':
|
| 79 |
+
d.rounded_rectangle((cx - w * 0.14, y + h * 0.15, cx + w * 0.14, Y - h * 0.15), radius=16, outline=INK, width=7)
|
| 80 |
+
else:
|
| 81 |
+
draw_symbol(d, {'leaf_clip': 'leaf', 'star_plate': 'star', 'triangle_plate': 'triangle'}[v], box, fill=BLUE)
|
| 82 |
+
elif v in ('building', 'tree', 'car'):
|
| 83 |
+
if v == 'building':
|
| 84 |
+
d.rectangle((x + w * 0.18, y + h * 0.15, X - w * 0.18, Y - h * 0.1), fill=BLUE, outline=INK, width=4)
|
| 85 |
+
for a in range(2):
|
| 86 |
+
for b in range(3):
|
| 87 |
+
d.rectangle((x + w * (0.3 + a * 0.25), y + h * (0.23 + b * 0.2), x + w * (0.42 + a * 0.25), y + h * (0.35 + b * 0.2)), fill=PAPER)
|
| 88 |
+
elif v == 'tree':
|
| 89 |
+
d.rectangle((cx - 6, cy, cx + 6, Y - h * 0.05), fill=INK)
|
| 90 |
+
draw_symbol(d, 'leaf', (x, y, X, Y - h * 0.2), fill=BLUE)
|
| 91 |
+
else:
|
| 92 |
+
d.rectangle((x + w * 0.12, cy, X - w * 0.12, Y - h * 0.2), fill=BLUE)
|
| 93 |
+
d.polygon([(x + w * 0.25, cy), (x + w * 0.4, y + h * 0.25), (x + w * 0.7, y + h * 0.25), (x + w * 0.85, cy)], fill=BLUE)
|
| 94 |
+
d.ellipse((x + w * 0.2, Y - h * 0.3, x + w * 0.4, Y - h * 0.08), fill=INK)
|
| 95 |
+
d.ellipse((x + w * 0.65, Y - h * 0.3, x + w * 0.85, Y - h * 0.08), fill=INK)
|
| 96 |
+
elif v in ('START', 'NEXT', 'PREVIOUS', 'READING - PAD', 'ON', 'OFF') or v.replace('.', '', 1).isdigit() or len(v) < 3 or (v in ['MON', 'TUE', 'WED', 'THU', 'STANDARD', 'HEAVIER', 'EQUAL', 'LIGHTER']) or ('/' in v) or (':' in v):
|
| 97 |
+
text(d, (cx, cy), v, min(50, int(w / max(2, len(v))) * 2))
|
| 98 |
+
else:
|
| 99 |
+
draw_symbol(d, v, box, fill=BLUE)
|
| 100 |
+
|
| 101 |
+
def board(v, state=None, size=(1200, 720)):
|
| 102 |
+
state = state or {}
|
| 103 |
+
kind = v.get('type', '')
|
| 104 |
+
im = Image.new('RGB', (1200, 720), PAPER)
|
| 105 |
+
d = ImageDraw.Draw(im)
|
| 106 |
+
d.rectangle((18, 18, 1182, 702), outline=(134, 119, 90), width=4)
|
| 107 |
+
d.polygon([(24, 24), (65, 24), (24, 65)], fill=(147, 60, 43))
|
| 108 |
+
title = v.get('title', '')
|
| 109 |
+
if title:
|
| 110 |
+
text(d, (600, 60), title, 30)
|
| 111 |
+
|
| 112 |
+
def cells(rows, area=(90, 120, 1110, 640)):
|
| 113 |
+
n = len(rows)
|
| 114 |
+
m = max(map(len, rows))
|
| 115 |
+
x, y, X, Y = area
|
| 116 |
+
cw = (X - x) / m
|
| 117 |
+
ch = (Y - y) / n
|
| 118 |
+
for r, row in enumerate(rows):
|
| 119 |
+
for c, z in enumerate(row):
|
| 120 |
+
a = x + c * cw
|
| 121 |
+
b = y + r * ch
|
| 122 |
+
d.rectangle((a, b, a + cw, b + ch), outline=(157, 145, 119), width=2)
|
| 123 |
+
symbol(d, z, (a + 10, b + 10, a + cw - 10, b + ch - 10))
|
| 124 |
+
if kind in ('table', 'symbol_grid', 'missing_middle', 'odd_one'):
|
| 125 |
+
cells(v['rows'])
|
| 126 |
+
elif kind == 'number_grid':
|
| 127 |
+
rows = v['rows']
|
| 128 |
+
cells(rows, (180, 160, 1120, 640))
|
| 129 |
+
for r, x in enumerate(v.get('row_labels', [])):
|
| 130 |
+
symbol(d, x, (40, 160 + r * 480 / len(rows), 160, 160 + (r + 1) * 480 / len(rows)))
|
| 131 |
+
for c, x in enumerate(v.get('col_labels', [])):
|
| 132 |
+
symbol(d, x, (180 + c * 940 / len(rows[0]), 60, 180 + (c + 1) * 940 / len(rows[0]), 150))
|
| 133 |
+
for label, r, c in v.get('starts', []):
|
| 134 |
+
cw = 940 / len(rows[0])
|
| 135 |
+
ch = 480 / len(rows)
|
| 136 |
+
symbol(d, label, (180 + c * cw + 5, 160 + r * ch + 5, 180 + c * cw + 75, 160 + r * ch + 75))
|
| 137 |
+
if v.get('mirror'):
|
| 138 |
+
im = ImageOps.mirror(im)
|
| 139 |
+
elif kind == 'symbol_values':
|
| 140 |
+
cells([v.get('symbols', []), v['values']])
|
| 141 |
+
elif kind == 'symbol_strip':
|
| 142 |
+
cells([v['symbols']])
|
| 143 |
+
elif kind == 'cap_notches':
|
| 144 |
+
for j, side in enumerate(v['directions']):
|
| 145 |
+
x = 240 + j * 360
|
| 146 |
+
y = 365
|
| 147 |
+
d.ellipse((x - 115, y - 115, x + 115, y + 115), fill=BLUE, outline=INK, width=7)
|
| 148 |
+
a = {'right': 0, 'down': 90, 'left': 180, 'up': 270}[side]
|
| 149 |
+
d.pieslice((x - 120, y - 120, x + 120, y + 120), a - 18, a + 18, fill=PAPER)
|
| 150 |
+
d.ellipse((x - 65, y - 65, x + 65, y + 65), fill=BLUE)
|
| 151 |
+
elif kind in ('pattern_rings', 'lever_shapes'):
|
| 152 |
+
cells([['leaf', 'leaf'] if kind == 'pattern_rings' else ['square', 'star']])
|
| 153 |
+
elif kind in ('holes', 'hole_mask'):
|
| 154 |
+
rows = v.get('rows', 6)
|
| 155 |
+
cols = v.get('cols', len(v.get('positions', [])) or 4)
|
| 156 |
+
cw = 880 / cols
|
| 157 |
+
ch = 480 / rows
|
| 158 |
+
for r in range(rows):
|
| 159 |
+
text(d, (110, 140 + (r + 0.5) * ch), r + 1, 32)
|
| 160 |
+
for c in range(cols):
|
| 161 |
+
d.rectangle((180 + c * cw, 140 + r * ch, 180 + (c + 1) * cw, 140 + (r + 1) * ch), outline=(165, 155, 130), width=2)
|
| 162 |
+
points = v.get('points', [(p - 1, j) for j, p in enumerate(v.get('positions', []))])
|
| 163 |
+
for j, (r, c) in enumerate(points):
|
| 164 |
+
xx = 180 + (c + 0.5) * cw
|
| 165 |
+
yy = 140 + (r + 0.5) * ch
|
| 166 |
+
d.ellipse((xx - 22, yy - 22, xx + 22, yy + 22), fill=INK)
|
| 167 |
+
if kind == 'hole_mask':
|
| 168 |
+
text(d, (xx + 40, yy - 20), j + 1, 30)
|
| 169 |
+
elif kind == 'hole_count':
|
| 170 |
+
for j, holes in enumerate(v['holes']):
|
| 171 |
+
x = 180 + j * 350
|
| 172 |
+
d.rounded_rectangle((x - 90, 120, x + 110, 630), radius=15, outline=INK, width=5)
|
| 173 |
+
for h in holes:
|
| 174 |
+
y = 150 + h * 65
|
| 175 |
+
d.ellipse((x - 18, y - 18, x + 18, y + 18), fill=INK)
|
| 176 |
+
elif kind == 'pattern_map':
|
| 177 |
+
cells([v['references']], (190, 95, 1010, 300))
|
| 178 |
+
cells([[x[0] for x in v['samples']], [x[1] for x in v['samples']]], (90, 360, 1110, 650))
|
| 179 |
+
elif kind == 'successor':
|
| 180 |
+
cells([[x, '?'] for x in v['before']])
|
| 181 |
+
text(d, (600, 75), 'NEXT PAGE / 1 > 2', 30)
|
| 182 |
+
elif kind == 'dials':
|
| 183 |
+
for j, val in enumerate(v['values']):
|
| 184 |
+
x = 240 + j * 360
|
| 185 |
+
y = 365
|
| 186 |
+
d.ellipse((x - 125, y - 125, x + 125, y + 125), fill=(231, 225, 203), outline=INK, width=7)
|
| 187 |
+
for k in range(1, 7):
|
| 188 |
+
a = math.radians(-140 + (k - 1) * 56)
|
| 189 |
+
text(d, (x + 95 * math.cos(a), y + 95 * math.sin(a)), k, 32)
|
| 190 |
+
a = math.radians(-140 + (val - 1) * 56)
|
| 191 |
+
d.line((x, y, x + 78 * math.cos(a), y + 78 * math.sin(a)), fill=(153, 61, 42), width=10)
|
| 192 |
+
elif kind == 'count':
|
| 193 |
+
for j, n in enumerate(v['groups']):
|
| 194 |
+
x = 230 + j * 360
|
| 195 |
+
y = 350
|
| 196 |
+
if v.get('object') == 'spoke':
|
| 197 |
+
d.ellipse((x - 120, y - 120, x + 120, y + 120), outline=INK, width=10)
|
| 198 |
+
for k in range(n):
|
| 199 |
+
a = math.pi * 2 * k / n
|
| 200 |
+
d.line((x, y, x + 110 * math.cos(a), y + 110 * math.sin(a)), fill=INK, width=7)
|
| 201 |
+
else:
|
| 202 |
+
d.rectangle((x - 105, y + 40, x + 105, y + 80), fill=BLUE)
|
| 203 |
+
for k in range(n):
|
| 204 |
+
d.rectangle((x - 100 + k * 210 / n, y - 45, x - 100 + k * 210 / n + 150 / n, y + 45), fill=BLUE)
|
| 205 |
+
elif kind in ('stamp_compare', 'gauge_pairs', 'classes', 'chain', 'locations', 'trace', 'wire_trace', 'heights', 'occlusion'):
|
| 206 |
+
if kind == 'stamp_compare':
|
| 207 |
+
cells([v['left'][:3], v['left'][3:], v['right'][:3], v['right'][3:]])
|
| 208 |
+
elif kind == 'chain':
|
| 209 |
+
cells(v['ends'])
|
| 210 |
+
text(d, (600, 65), 'circle > ... > flag', 25)
|
| 211 |
+
elif kind == 'gauge_pairs':
|
| 212 |
+
for row, values in enumerate([list('ABCD'), v['reference']]):
|
| 213 |
+
for j, k in enumerate(values):
|
| 214 |
+
x = 150 + j * (280 if row == 0 else 500)
|
| 215 |
+
y = 200 + row * 300
|
| 216 |
+
gap = 25 + 20 * 'ABCD'.index(k)
|
| 217 |
+
d.rounded_rectangle((x - 85, y - 55, x + 85, y + 55), radius=9, outline=INK, width=4)
|
| 218 |
+
for xx in [x - gap / 2, x + gap / 2]:
|
| 219 |
+
d.ellipse((xx - 9, y - 9, xx + 9, y + 9), fill=INK)
|
| 220 |
+
if row == 0:
|
| 221 |
+
text(d, (x, y + 90), k, 35)
|
| 222 |
+
text(d, (600, 75), 'HOLE SPACING / LEFT / RIGHT', 28)
|
| 223 |
+
elif kind == 'classes':
|
| 224 |
+
cells([v['classes']])
|
| 225 |
+
text(d, (600, 75), 'STORAGE LABELS', 28)
|
| 226 |
+
elif kind == 'locations':
|
| 227 |
+
d.line((150, 300, 650, 300), fill=(152, 62, 45), width=10)
|
| 228 |
+
d.line((900, 150, 900, 560), fill=BLUE, width=10)
|
| 229 |
+
pts = [(230, 300), (550, 300), (900, 230), (900, 480)]
|
| 230 |
+
for j, (x, y) in enumerate(pts):
|
| 231 |
+
d.ellipse((x - 35, y - 35, x + 35, y + 35), outline=INK, width=8)
|
| 232 |
+
for n, j in enumerate(v['selected']):
|
| 233 |
+
x, y = pts[j - 1]
|
| 234 |
+
text(d, (x + 60, y - 60), n + 1, 40)
|
| 235 |
+
d.line((x + 50, y - 42, x + 15, y - 15), fill=INK, width=4)
|
| 236 |
+
elif kind in ('trace', 'wire_trace'):
|
| 237 |
+
for j, k in enumerate(v['mapping']):
|
| 238 |
+
y = 190 + j * 160
|
| 239 |
+
symbol(d, ['circle', 'star', 'square'][j], (50, y - 45, 145, y + 45))
|
| 240 |
+
dy = 130 + (k - 1) * (140 if kind == 'wire_trace' else 90)
|
| 241 |
+
d.line((160, y, 350 + j * 130, y, 350 + j * 130, dy, 1010, dy), fill=[BLUE, (148, 87, 57), (82, 119, 70)][j], width=9)
|
| 242 |
+
for j in range(4 if kind == 'wire_trace' else 6):
|
| 243 |
+
text(d, (1090, 130 + j * (140 if kind == 'wire_trace' else 90)), j + 1, 38)
|
| 244 |
+
elif kind == 'heights':
|
| 245 |
+
for j, n in enumerate(v['numbers']):
|
| 246 |
+
x = 200 + j * 270
|
| 247 |
+
d.rectangle((x - 50, 560 - n * 90, x + 50, 560), fill=BLUE, outline=INK, width=4)
|
| 248 |
+
text(d, (x, 610), j + 1, 34)
|
| 249 |
+
text(d, (600, 70), 'LOW > HIGH', 30)
|
| 250 |
+
else:
|
| 251 |
+
for j, x in reversed(list(enumerate(v['symbols']))):
|
| 252 |
+
symbol(d, x, (200 + j * 150, 190 + j * 30, 540 + j * 150, 540 + j * 30))
|
| 253 |
+
text(d, (600, 80), 'FRONT > BACK', 30)
|
| 254 |
+
elif kind == 'solid':
|
| 255 |
+
for j in range(8):
|
| 256 |
+
x = 110 + j * 135
|
| 257 |
+
d.ellipse((x - 35, 190, x + 35, 260), fill=INK if j + 1 in v['solid'] else PAPER, outline=INK, width=4)
|
| 258 |
+
if 'numbers' in v:
|
| 259 |
+
text(d, (x, 440), v['numbers'][j], 65)
|
| 260 |
+
elif kind == 'ring':
|
| 261 |
+
for j in range(12):
|
| 262 |
+
a = math.pi * 2 * j / 12 - math.pi / 2
|
| 263 |
+
x = 600 + 240 * math.cos(a)
|
| 264 |
+
y = 370 + 240 * math.sin(a)
|
| 265 |
+
if 'numbers' in v:
|
| 266 |
+
text(d, (x, y), v['numbers'][j], 45)
|
| 267 |
+
else:
|
| 268 |
+
d.ellipse((x - 18, y - 18, x + 18, y + 18), fill=INK if j in v['marks'] else PAPER, outline=INK, width=3)
|
| 269 |
+
if j == v.get('triangle', 0):
|
| 270 |
+
symbol(d, 'triangle', (x - 15, y - 60, x + 15, y - 25))
|
| 271 |
+
elif kind == 'segments':
|
| 272 |
+
pts = {'a': (0.2, 0.1, 0.8, 0.1), 'b': (0.8, 0.1, 0.8, 0.5), 'c': (0.8, 0.5, 0.8, 0.9), 'd': (0.2, 0.9, 0.8, 0.9), 'e': (0.2, 0.5, 0.2, 0.9), 'f': (0.2, 0.1, 0.2, 0.5), 'g': (0.2, 0.5, 0.8, 0.5)}
|
| 273 |
+
for j, parts in enumerate(v['values']):
|
| 274 |
+
x = 95 + j * 280
|
| 275 |
+
for c in parts:
|
| 276 |
+
a, b, A, B = pts[c]
|
| 277 |
+
d.line((x + a * 220, 160 + b * 400, x + A * 220, 160 + B * 400), fill=INK, width=17)
|
| 278 |
+
elif kind == 'route':
|
| 279 |
+
R = v['rows']
|
| 280 |
+
C = v['cols']
|
| 281 |
+
cw = 210
|
| 282 |
+
ch = 125
|
| 283 |
+
for r in range(R):
|
| 284 |
+
for c in range(C):
|
| 285 |
+
d.rectangle((300 + c * cw, 115 + r * ch, 300 + (c + 1) * cw, 115 + (r + 1) * ch), outline=(155, 144, 120), width=2)
|
| 286 |
+
path = [(300 + (c + 0.5) * cw, 115 + (r + 0.5) * ch) for r, c in v['path']]
|
| 287 |
+
d.line(path, fill=BLUE, width=14)
|
| 288 |
+
text(d, path[0], 'S', 35)
|
| 289 |
+
text(d, path[-1], 'T', 35)
|
| 290 |
+
elif kind == 'bolt_chain':
|
| 291 |
+
text(d, (600, 350), 'MECHANICAL INTERLOCK', 50)
|
| 292 |
+
elif kind in ('balance', 'pushbox'):
|
| 293 |
+
text(d, (600, 350), '6' if kind == 'balance' else '', 60)
|
| 294 |
+
else:
|
| 295 |
+
return render_clue({'visual': v}, state, size=size)
|
| 296 |
+
return im.resize(size)
|
runtime/h2_runtime/medium88_final_details.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from medium88_polished import MediumScene as CableScene
|
| 2 |
+
from medium88_room_details import MediumScene as DeviceScene
|
| 3 |
+
|
| 4 |
+
class R31Scene(CableScene):
|
| 5 |
+
|
| 6 |
+
def controls_for(self, i, s, root):
|
| 7 |
+
super().controls_for(i, s, root)
|
| 8 |
+
if s.get('visual', {}).get('type') == 'heights':
|
| 9 |
+
for node in self.buffers[i]:
|
| 10 |
+
self.visibility(node, False)
|
| 11 |
+
self.box('height_input_mount', [0, 0.26, 1.47], [0.95, 0.05, 0.2], 'wood', root)
|
| 12 |
+
self.box('height_input_bezel', [0, 0.22, 1.47], [0.9, 0.035, 0.16], 'iron', root)
|
| 13 |
+
|
| 14 |
+
def screen(self, key, parent, pos, w, h, im, sig):
|
| 15 |
+
if key == 's1_buffer':
|
| 16 |
+
pos = [0, 0.198, 1.47]
|
| 17 |
+
return super().screen(key, parent, pos, w, h, im, sig)
|
| 18 |
+
|
| 19 |
+
class R27Scene(DeviceScene):
|
| 20 |
+
|
| 21 |
+
def float_key(self, i, s, root):
|
| 22 |
+
super().float_key(i, s, root)
|
| 23 |
+
self.cylinder('faucet_valve_stem', [0.36, 0.135, 1.2525], 0.009, 0.065, 'steel', 'z', root)
|
runtime/h2_runtime/medium88_game.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy, re
|
| 2 |
+
from easy88_core import EasyGame, pipe_connected
|
| 3 |
+
from action_feedback import failure_for
|
| 4 |
+
|
| 5 |
+
class MediumGame(EasyGame):
|
| 6 |
+
|
| 7 |
+
def __init__(self):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.reward_open = [False] * 3
|
| 10 |
+
self.cover_keys = {}
|
| 11 |
+
self.possessions = {}
|
| 12 |
+
for i, s in enumerate(self.SPEC['stages']):
|
| 13 |
+
self.opened[f's{i + 1}_cover'] = s.get('parent') is None
|
| 14 |
+
if s['kind'] == 'bolts':
|
| 15 |
+
self.states[i]['selected'] = [0] * 4
|
| 16 |
+
if s['kind'] == 'pushbox':
|
| 17 |
+
self.states[i].update(player=list(s['initial_player']), box=list(s['initial_box']))
|
| 18 |
+
if s['kind'] == 'balance':
|
| 19 |
+
self.states[i]['weights'] = []
|
| 20 |
+
self.opened.pop('key_box', None)
|
| 21 |
+
|
| 22 |
+
def snapshot(self):
|
| 23 |
+
x = super().snapshot()
|
| 24 |
+
x.update(reward_open=list(self.reward_open), cover_keys=dict(self.cover_keys), possessions=copy.deepcopy(self.possessions))
|
| 25 |
+
return x
|
| 26 |
+
|
| 27 |
+
def stage_accessible(self, i):
|
| 28 |
+
return 0 <= i < 3 and self.opened.get(f's{i + 1}_cover', False)
|
| 29 |
+
|
| 30 |
+
def cover_unlocked(self, i):
|
| 31 |
+
p = self.SPEC['stages'][i].get('parent')
|
| 32 |
+
return (p is None or self.solved[p]) and (not self.SPEC['stages'][i].get('key_gate') or self.cover_keys.get(i, self.cover_keys.get(str(i), False)))
|
| 33 |
+
|
| 34 |
+
def _check(self, i):
|
| 35 |
+
s = self.SPEC['stages'][i]
|
| 36 |
+
v = self.states[i]
|
| 37 |
+
if s.get('route_special'):
|
| 38 |
+
return v['angles'] == s['target']
|
| 39 |
+
if s['kind'] == 'bolts':
|
| 40 |
+
return all(v['selected'])
|
| 41 |
+
if s['kind'] == 'pushbox':
|
| 42 |
+
return v['box'] == s['goal']
|
| 43 |
+
if s['kind'] == 'balance':
|
| 44 |
+
return sum((s['weights'][j] for j in v['weights'])) == s['target_mass']
|
| 45 |
+
return super()._check(i)
|
| 46 |
+
|
| 47 |
+
def act(self, a):
|
| 48 |
+
kind = a.get('action')
|
| 49 |
+
key = a.get('_hit364', '')
|
| 50 |
+
if key == 'exit_lock' and kind == 'unlock':
|
| 51 |
+
key = 'exit'
|
| 52 |
+
|
| 53 |
+
def out(ok, text=''):
|
| 54 |
+
return {'ok': bool(ok), 'text': text if ok and kind == 'read' else '' if ok else failure_for(kind)}
|
| 55 |
+
if not a.get('_validated364'):
|
| 56 |
+
return out(False)
|
| 57 |
+
if key in ('clue_A', 'clue_B'):
|
| 58 |
+
room = key[-1]
|
| 59 |
+
i = self.SPEC['last'][room]
|
| 60 |
+
portable = self.SPEC['id'] == 'R31' or (self.SPEC['id'] == 'R24' and room == 'A')
|
| 61 |
+
if kind == 'take' and portable and self.reward_open[i] and (key not in self.taken):
|
| 62 |
+
self.taken.add(key)
|
| 63 |
+
self.holding.append(key)
|
| 64 |
+
return out(True)
|
| 65 |
+
if kind == 'use' and self.SPEC['id'] == 'R24' and (room == 'B') and self.reward_open[i]:
|
| 66 |
+
item = self._resolve_item(a.get('item'))
|
| 67 |
+
if item != 'clue_A':
|
| 68 |
+
return out(False)
|
| 69 |
+
self.holding.remove(item)
|
| 70 |
+
self.possessions['mask_installed'] = True
|
| 71 |
+
return out(True)
|
| 72 |
+
return out(False)
|
| 73 |
+
if key == 'light_frame' and kind == 'use' and (self.SPEC['id'] == 'R31'):
|
| 74 |
+
item = self._resolve_item(a.get('item'))
|
| 75 |
+
if item not in ('clue_A', 'clue_B'):
|
| 76 |
+
return out(False)
|
| 77 |
+
self.holding.remove(item)
|
| 78 |
+
self.possessions['installed_' + item[-1]] = True
|
| 79 |
+
return out(True)
|
| 80 |
+
if key == 'exit':
|
| 81 |
+
if kind == 'unlock':
|
| 82 |
+
self.possessions['door_input'] = str(a.get('code', ''))
|
| 83 |
+
if str(a.get('code', '')) == self.SPEC['door_code']:
|
| 84 |
+
self.exit_unlocked = True
|
| 85 |
+
return out(True)
|
| 86 |
+
return out(False)
|
| 87 |
+
if kind in ('open', 'close'):
|
| 88 |
+
if kind == 'open' and (not self.exit_unlocked):
|
| 89 |
+
return out(False)
|
| 90 |
+
self.opened['exit'] = kind == 'open'
|
| 91 |
+
self.exited = self.opened['exit'] and self.exit_unlocked
|
| 92 |
+
return out(True)
|
| 93 |
+
return out(False)
|
| 94 |
+
r = re.fullmatch('reward_(\\d)', key)
|
| 95 |
+
if r:
|
| 96 |
+
i = int(r[1])
|
| 97 |
+
if kind not in ('open', 'close') or (kind == 'open' and (not self.solved[i])):
|
| 98 |
+
return out(False)
|
| 99 |
+
self.reward_open[i] = kind == 'open'
|
| 100 |
+
return out(True)
|
| 101 |
+
r = re.fullmatch('reward_key_(\\d)', key)
|
| 102 |
+
if r:
|
| 103 |
+
i = int(r[1])
|
| 104 |
+
if kind == 'take' and self.reward_open[i] and (key not in self.taken):
|
| 105 |
+
self.taken.add(key)
|
| 106 |
+
self.holding.append(key)
|
| 107 |
+
return out(True)
|
| 108 |
+
return out(False)
|
| 109 |
+
r = re.fullmatch('s([123])_(.+)', key)
|
| 110 |
+
if not r:
|
| 111 |
+
return out(False)
|
| 112 |
+
i = int(r[1]) - 1
|
| 113 |
+
tail = r[2]
|
| 114 |
+
s = self.SPEC['stages'][i]
|
| 115 |
+
v = self.states[i]
|
| 116 |
+
if tail == 'tool' and kind == 'take' and ((s.get('setup') or {}).get('kind') == 'weigh') and v['setup_used']:
|
| 117 |
+
if key in self.holding:
|
| 118 |
+
return out(False)
|
| 119 |
+
v['setup_used'] = False
|
| 120 |
+
v['setup_ready'] = False
|
| 121 |
+
self.holding.append(key)
|
| 122 |
+
return out(True)
|
| 123 |
+
if s['kind'] == 'assign' and tail == 'reset' and (kind == 'press'):
|
| 124 |
+
if not self.stage_accessible(i) or self.solved[i]:
|
| 125 |
+
return out(False)
|
| 126 |
+
v['assignment'] = {}
|
| 127 |
+
for j in range(len(s['items'])):
|
| 128 |
+
item = f's{i + 1}_item_{j}'
|
| 129 |
+
self.taken.discard(item)
|
| 130 |
+
if item in self.holding:
|
| 131 |
+
self.holding.remove(item)
|
| 132 |
+
return out(True)
|
| 133 |
+
if tail == 'cover' and s.get('key_gate') and (kind == 'use'):
|
| 134 |
+
item = self._resolve_item(a.get('item'))
|
| 135 |
+
if item != 'reward_key_' + str(s['parent']):
|
| 136 |
+
return out(False)
|
| 137 |
+
self.cover_keys[i] = True
|
| 138 |
+
return out(True)
|
| 139 |
+
if tail == 'tool' and s.get('tool_source') is not None and (not self.reward_open[s['tool_source']]):
|
| 140 |
+
return out(False)
|
| 141 |
+
if tail.startswith('item_') and s.get('item_source') is not None and (not self.reward_open[s['item_source']]):
|
| 142 |
+
return out(False)
|
| 143 |
+
if tail == 'lock' and kind == 'unlock':
|
| 144 |
+
self.possessions[key] = str(a.get('code', ''))
|
| 145 |
+
if s['kind'] == 'rotate_pipes' and kind == 'press' and tail.startswith('control_'):
|
| 146 |
+
if not self.stage_accessible(i):
|
| 147 |
+
return out(False)
|
| 148 |
+
j = int(tail.rsplit('_', 1)[1])
|
| 149 |
+
v['angles'][j] = (v['angles'][j] + 1) % s.get('moduli', [4] * len(v['angles']))[j]
|
| 150 |
+
if self._check(i):
|
| 151 |
+
self._solve(i)
|
| 152 |
+
return out(True)
|
| 153 |
+
if s['kind'] not in ('bolts', 'pushbox', 'balance'):
|
| 154 |
+
return super().act(a)
|
| 155 |
+
if tail == 'cover':
|
| 156 |
+
if kind not in ('open', 'close') or (kind == 'open' and (not self.cover_unlocked(i))):
|
| 157 |
+
return out(False)
|
| 158 |
+
self.opened[key] = kind == 'open'
|
| 159 |
+
return out(True)
|
| 160 |
+
if not self.stage_accessible(i):
|
| 161 |
+
return out(False)
|
| 162 |
+
if tail == 'reset' and kind == 'press':
|
| 163 |
+
if self.solved[i]:
|
| 164 |
+
return out(False)
|
| 165 |
+
if s['kind'] == 'pushbox':
|
| 166 |
+
v.update(player=list(s['initial_player']), box=list(s['initial_box']))
|
| 167 |
+
if s['kind'] == 'bolts':
|
| 168 |
+
v['selected'] = [0] * 4
|
| 169 |
+
return out(True)
|
| 170 |
+
if s['kind'] == 'bolts' and tail.startswith('control_') and (kind == 'press'):
|
| 171 |
+
j = int(tail.rsplit('_', 1)[1])
|
| 172 |
+
order = ['ABCD'.index(x) for x in s['order']]
|
| 173 |
+
n = sum(v['selected'])
|
| 174 |
+
if n == 4 or j != order[n]:
|
| 175 |
+
return out(False)
|
| 176 |
+
v['selected'][j] = 1
|
| 177 |
+
if all(v['selected']):
|
| 178 |
+
self._solve(i)
|
| 179 |
+
return out(True)
|
| 180 |
+
if s['kind'] == 'pushbox' and tail.startswith('choice_') and (kind == 'press'):
|
| 181 |
+
j = int(tail.rsplit('_', 1)[1])
|
| 182 |
+
dr, dc = [(-1, 0), (0, 1), (1, 0), (0, -1)][j]
|
| 183 |
+
p = [v['player'][0] + dr, v['player'][1] + dc]
|
| 184 |
+
b = v['box'][:]
|
| 185 |
+
if not all((1 <= z <= 4 for z in p)):
|
| 186 |
+
return out(False)
|
| 187 |
+
if p == b:
|
| 188 |
+
b = [b[0] + dr, b[1] + dc]
|
| 189 |
+
if not all((1 <= z <= 4 for z in b)):
|
| 190 |
+
return out(False)
|
| 191 |
+
v['player'] = p
|
| 192 |
+
v['box'] = b
|
| 193 |
+
if b == s['goal']:
|
| 194 |
+
self._solve(i)
|
| 195 |
+
return out(True)
|
| 196 |
+
if s['kind'] == 'balance':
|
| 197 |
+
m = re.fullmatch('weight_(\\d)', tail)
|
| 198 |
+
if m and kind == 'take':
|
| 199 |
+
j = int(m[1])
|
| 200 |
+
if key in self.holding:
|
| 201 |
+
return out(False)
|
| 202 |
+
if j in v['weights']:
|
| 203 |
+
v['weights'].remove(j)
|
| 204 |
+
self.holding.append(key)
|
| 205 |
+
self.taken.add(key)
|
| 206 |
+
return out(True)
|
| 207 |
+
if tail == 'pan' and kind == 'use':
|
| 208 |
+
item = self._resolve_item(a.get('item'))
|
| 209 |
+
m = re.fullmatch('s' + str(i + 1) + '_weight_(\\d)', item or '')
|
| 210 |
+
if not m:
|
| 211 |
+
return out(False)
|
| 212 |
+
j = int(m[1])
|
| 213 |
+
v['weights'].append(j)
|
| 214 |
+
self.holding.remove(item)
|
| 215 |
+
if self._check(i):
|
| 216 |
+
self._solve(i)
|
| 217 |
+
return out(True)
|
| 218 |
+
return out(False)
|
| 219 |
+
|
| 220 |
+
def make_game(spec):
|
| 221 |
+
from easy88_core import build_labels
|
| 222 |
+
|
| 223 |
+
class Game(MediumGame):
|
| 224 |
+
pass
|
| 225 |
+
Game.SPEC = copy.deepcopy(spec)
|
| 226 |
+
for i, s in enumerate(Game.SPEC['stages']):
|
| 227 |
+
if spec['id'] == 'R29' and i == 2 or (spec['id'] == 'R36' and i == 1):
|
| 228 |
+
s['key_gate'] = True
|
| 229 |
+
Game.LABELS = build_labels(Game.SPEC)
|
| 230 |
+
for i, s in enumerate(Game.SPEC['stages']):
|
| 231 |
+
Game.LABELS['reward_' + str(i)] = s['name'] + ' drawer'
|
| 232 |
+
Game.LABELS['reward_key_' + str(i)] = 'small brass control key'
|
| 233 |
+
for j in range(4):
|
| 234 |
+
Game.LABELS[f's{i + 1}_weight_{j}'] = str([1, 2, 4, 8][j]) + '-point weight'
|
| 235 |
+
Game.LABELS[f's{i + 1}_pan'] = 'balance pan'
|
| 236 |
+
Game.LABELS.update(exit='exit door')
|
| 237 |
+
Game.LABELS.update(exit_lock='exit code keypad', clue_A=spec['room_names'][0] + ' record', clue_B=spec['room_names'][1] + ' record')
|
| 238 |
+
if spec['id'] == 'R24':
|
| 239 |
+
Game.LABELS['clue_A'] = 'transparent locator sheet'
|
| 240 |
+
if spec['id'] == 'R31':
|
| 241 |
+
Game.LABELS.update(clue_A='first numeral film', clue_B='second numeral film', light_frame='locating light frame')
|
| 242 |
+
for i, s in enumerate(Game.SPEC['stages']):
|
| 243 |
+
if s['kind'] == 'float_key':
|
| 244 |
+
Game.LABELS[f's{i + 1}_float_key'] = 'small brass cylinder key'
|
| 245 |
+
return Game
|
runtime/h2_runtime/medium88_numeric_binding.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from PIL import Image, ImageDraw
|
| 3 |
+
from font_utils import load_font
|
| 4 |
+
from action_feedback import failure_for
|
| 5 |
+
from easy88_core import CODE
|
| 6 |
+
|
| 7 |
+
class NumericLockMixin:
|
| 8 |
+
|
| 9 |
+
def act(self, a):
|
| 10 |
+
m = re.fullmatch('s([123])_lock', str(a.get('_hit364', '')))
|
| 11 |
+
if a.get('_validated364') and a.get('action') == 'unlock' and m:
|
| 12 |
+
i = int(m[1]) - 1
|
| 13 |
+
s = self.SPEC['stages'][i]
|
| 14 |
+
if s['kind'] in CODE:
|
| 15 |
+
value = str(a.get('code', '')).strip()
|
| 16 |
+
self.possessions[a['_hit364']] = value
|
| 17 |
+
ok = self.stage_accessible(i) and value == str(s['answer'])
|
| 18 |
+
if ok:
|
| 19 |
+
self._solve(i)
|
| 20 |
+
return {'ok': ok, 'text': '' if ok else failure_for('unlock')}
|
| 21 |
+
return super().act(a)
|
| 22 |
+
|
| 23 |
+
class MeasurementSceneMixin:
|
| 24 |
+
|
| 25 |
+
def numeric(self, i, s, root):
|
| 26 |
+
super().numeric(i, s, root)
|
| 27 |
+
if (s.get('setup') or {}).get('kind') != 'measure':
|
| 28 |
+
return
|
| 29 |
+
for node in list(root['meshes']):
|
| 30 |
+
if node['prim'].GetName().startswith(('measurement_strip', 'endpoint_marker')):
|
| 31 |
+
self.visibility(node, False)
|
| 32 |
+
width = float(s['visual']['measurement']) / 1000.0
|
| 33 |
+
p = f's{i + 1}'
|
| 34 |
+
target = self.group(p + '_actual_measurement_strip', parent=root)
|
| 35 |
+
self.box('true_scale_sample_strip', [0, 0.21, 1.18], [width, 0.025, 0.045], 'cloth', target)
|
| 36 |
+
for x in [-width / 2, width / 2]:
|
| 37 |
+
self.box('true_sample_endpoint', [x, 0.193, 1.18], [0.003, 0.008, 0.09], 'red', target)
|
| 38 |
+
self.transform(target, [0, 0.0575, 0])
|
| 39 |
+
for xx in [-width / 2, width / 2]:
|
| 40 |
+
self.box('sample_clamp_mount', [xx, 0.26, 1.18], [0.016, 0.045, 0.08], 'red', root)
|
| 41 |
+
self.reg(p + '_setup', target)
|
| 42 |
+
self.setups[i] = target
|
| 43 |
+
self.label(p + '_measurement_unit', 'mm', [0.31, 0.19, 1.18], 0.1, 0.06, parent=root)
|
| 44 |
+
self.visibility(self.tools[i][0], False)
|
| 45 |
+
ruler = self.group(p + '_true_ruler', parent=self.rewards[s['tool_source']] if s.get('tool_source') is not None else root)
|
| 46 |
+
self.box('thin_steel_ruler', [0, 0, 0], [0.31, 0.025, 0.004], 'steel', ruler)
|
| 47 |
+
scale_image = Image.new('RGB', (1600, 180), (180, 187, 182))
|
| 48 |
+
draw = ImageDraw.Draw(scale_image)
|
| 49 |
+
for mm in range(0, 301, 5):
|
| 50 |
+
x = 30 + mm * 1540 / 300
|
| 51 |
+
draw.line((x, 8, x, 85 if mm % 50 == 0 else 48), fill=(32, 39, 37), width=4)
|
| 52 |
+
if mm % 50 == 0:
|
| 53 |
+
draw.text((x, 132), str(mm), font=load_font(50), fill=(32, 39, 37), anchor='mm')
|
| 54 |
+
path = self.tex / (p + '_ruler_graduations.png')
|
| 55 |
+
scale_image.save(path)
|
| 56 |
+
mat = self.mat(p + '_ruler_scale', texture=path, rough=0.92)
|
| 57 |
+
self.plane('etched_ruler_scale', [0, 0, 0.0021], 0.3, 0.022, (1, 0, 0), (0, 1, 0), None, ruler, material=mat)
|
| 58 |
+
self.reg(p + '_tool', ruler)
|
| 59 |
+
self.tools[i] = [ruler]
|
| 60 |
+
|
| 61 |
+
def sync(self, g):
|
| 62 |
+
super().sync(g)
|
| 63 |
+
for i, s in enumerate(self.spec['stages']):
|
| 64 |
+
if (s.get('setup') or {}).get('kind') != 'measure':
|
| 65 |
+
continue
|
| 66 |
+
ruler = self.tools[i][0]
|
| 67 |
+
source = s.get('tool_source')
|
| 68 |
+
if source is None:
|
| 69 |
+
self.transform(ruler, [-0.4, 0.05, 0.7945])
|
| 70 |
+
else:
|
| 71 |
+
self.transform(ruler, [0, 0.19, -0.0805], rpy=[0, 0, 0])
|
| 72 |
+
|
| 73 |
+
def screen(self, key, parent, pos, w, h, im, sig):
|
| 74 |
+
if re.fullmatch('s[123]_measuring_face', key):
|
| 75 |
+
if not sig:
|
| 76 |
+
if key in self.images:
|
| 77 |
+
self.visibility(self.images[key], False)
|
| 78 |
+
return
|
| 79 |
+
i = int(key[1]) - 1
|
| 80 |
+
value = float(self.spec['stages'][i]['visual']['measurement'])
|
| 81 |
+
width = value / 1000.0
|
| 82 |
+
im = Image.new('RGB', (1600, 460), (200, 188, 151))
|
| 83 |
+
d = ImageDraw.Draw(im)
|
| 84 |
+
left = 38
|
| 85 |
+
scale = 1524 / 300
|
| 86 |
+
d.rectangle((6, 6, 1593, 453), outline=(45, 48, 42), width=10)
|
| 87 |
+
for mm in range(0, 301, 5):
|
| 88 |
+
x = left + mm * scale
|
| 89 |
+
major = mm % 50 == 0
|
| 90 |
+
d.line((x, 290, x, 180 if major else 225), fill=(35, 43, 42), width=4)
|
| 91 |
+
if major:
|
| 92 |
+
d.text((x, 365), str(mm), font=load_font(68), anchor='mm', fill=(35, 43, 42))
|
| 93 |
+
x = left + value * scale
|
| 94 |
+
d.line((x, 35, x, 285), fill=(151, 54, 37), width=9)
|
| 95 |
+
d.text((max(155, min(1440, x)), 105), str(int(value)) + ' mm', font=load_font(102), anchor='mm', fill=(35, 43, 42))
|
| 96 |
+
pos = [0.15 - width / 2, 0.247, 1.105]
|
| 97 |
+
w = 0.31
|
| 98 |
+
h = 0.089
|
| 99 |
+
return super().screen(key, parent, pos, w, h, im, sig)
|
runtime/h2_runtime/medium88_polished.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from medium88_scene import MediumScene as FrozenScene
|
| 3 |
+
from medium88_clues import board
|
| 4 |
+
|
| 5 |
+
class MediumScene(FrozenScene):
|
| 6 |
+
|
| 7 |
+
def show_image(self, key, parent, pos, w, h, im):
|
| 8 |
+
if len(key) > 2 and key[0] == 's' and key[1].isdigit() and key.endswith('_reference'):
|
| 9 |
+
i = int(key[1]) - 1
|
| 10 |
+
typ = self.spec['stages'][i].get('visual', {}).get('type')
|
| 11 |
+
if typ == 'heights':
|
| 12 |
+
return None
|
| 13 |
+
if typ == 'chain':
|
| 14 |
+
im = board({'type': 'symbol_strip', 'symbols': ['circle', 'flag'], 'title': 'START > END'})
|
| 15 |
+
return super().show_image(key, parent, pos, w, h, im)
|
| 16 |
+
|
| 17 |
+
def controls_for(self, i, s, root):
|
| 18 |
+
super().controls_for(i, s, root)
|
| 19 |
+
if s.get('visual', {}).get('type') == 'heights':
|
| 20 |
+
for j, h in enumerate(s['visual']['numbers']):
|
| 21 |
+
x = (j - 1.5) * 0.29
|
| 22 |
+
top = 0.97 + h * 0.085
|
| 23 |
+
self.cylinder('lamp_foot', [x, 0.06, 0.81], 0.055, 0.035, 'iron', 'z', root)
|
| 24 |
+
self.cylinder('lamp_stem', [x, 0.06, (0.83 + top) / 2], 0.01, top - 0.83, 'steel', 'z', root)
|
| 25 |
+
self.cylinder('lamp_shade', [x, 0.06, top], 0.061, 0.07, 'paint', 'z', root)
|
| 26 |
+
self.cylinder('lamp_diffuser', [x, 0.06, top - 0.038], 0.052, 0.008, 'lamp', 'z', root)
|
| 27 |
+
self.label('height_lamp_number_' + str(j), j + 1, [x, -0.012, 0.855], 0.07, 0.045, parent=root)
|
| 28 |
+
|
| 29 |
+
def assign(self, i, s, root):
|
| 30 |
+
if s.get('visual', {}).get('type') != 'wire_trace':
|
| 31 |
+
return super().assign(i, s, root)
|
| 32 |
+
p = f's{i + 1}'
|
| 33 |
+
self.extra[i, 'wire_pose'] = {'coils': [], 'plugs': [], 'links': []}
|
| 34 |
+
self.box('integrated_wiring_enclosure', [0, 0.12, 1.305], [1.3, 0.3, 0.69], 'paint', root)
|
| 35 |
+
for xx in [-0.45, 0.45]:
|
| 36 |
+
self.box('wiring_unit_mount', [xx, 0.23, 0.87625], [0.045, 0.09, 0.1675], 'iron', root)
|
| 37 |
+
pose = self.extra[i, 'wire_pose']
|
| 38 |
+
for j, item in enumerate(s['items']):
|
| 39 |
+
node = self.group(p + '_item_' + str(j), parent=self.rewards[s['item_source']] if s.get('item_source') is not None else root)
|
| 40 |
+
coil = self.group(p + '_coiled_lead_' + str(j), parent=node)
|
| 41 |
+
for k in range(28):
|
| 42 |
+
a = k * 2 * math.pi / 28
|
| 43 |
+
b = (k + 1) * 2 * math.pi / 28
|
| 44 |
+
self.tube('flexible_lead', [0.055 * math.cos(a), 0.045 * math.sin(a), 0.012], [0.055 * math.cos(b), 0.045 * math.sin(b), 0.012], 0.006, 'rubber', coil)
|
| 45 |
+
self.cylinder('loose_connector', [0.064, 0, 0.013], 0.012, 0.055, 'brass', 'x', coil)
|
| 46 |
+
self.tube('loose_tail', [-0.055, 0, 0.012], [-0.076, 0.025, 0.012], 0.006, 'rubber', coil)
|
| 47 |
+
self.cylinder('other_connector', [-0.08, 0.025, 0.012], 0.012, 0.045, 'steel', 'x', coil)
|
| 48 |
+
plug = self.group(p + '_installed_plug_' + str(j), parent=node)
|
| 49 |
+
self.cylinder('connector_barrel', [0, -0.035, 0], 0.024, 0.075, 'brass', 'y', plug)
|
| 50 |
+
self.show_image(p + '_plug_mark_' + str(j), plug, [0, -0.077, 0], 0.052, 0.052, board({'type': 'symbol_strip', 'symbols': [item['symbol']]}))
|
| 51 |
+
self.reg(p + '_item_' + str(j), node)
|
| 52 |
+
self.items[i].append(node)
|
| 53 |
+
pose['coils'].append(coil)
|
| 54 |
+
pose['plugs'].append(plug)
|
| 55 |
+
variants = []
|
| 56 |
+
for slot in range(4):
|
| 57 |
+
link = self.group(p + '_lead_' + str(j) + '_to_' + str(slot), parent=root)
|
| 58 |
+
end = (slot - 1.5) * 0.25
|
| 59 |
+
startz = 1.49 - j * 0.15
|
| 60 |
+
points = [[-0.535, -0.065, startz], [-0.46, -0.12 - j * 0.012, startz], [-0.2 + j * 0.11, -0.14 - j * 0.012, 1.09 - j * 0.025], [end, -0.13, 1.1], [end, -0.1, 1.1]]
|
| 61 |
+
for a, b in zip(points, points[1:]):
|
| 62 |
+
self.tube('connected_flexible_lead', a, b, 0.007, 'rubber', link)
|
| 63 |
+
variants.append(link)
|
| 64 |
+
pose['links'].append(variants)
|
| 65 |
+
self.cylinder('fixed_source_socket', [-0.535, -0.036, 1.49 - j * 0.15], 0.031, 0.035, 'iron', 'y', root)
|
| 66 |
+
self.show_image(p + '_source_identity_' + str(j), root, [-0.425, -0.035, 1.49 - j * 0.15], 0.065, 0.065, board({'type': 'symbol_strip', 'symbols': [item['symbol']]}))
|
| 67 |
+
for j in range(4):
|
| 68 |
+
n = self.group(p + '_slot_' + str(j), [(j - 1.5) * 0.25, -0.036, 1.1], root)
|
| 69 |
+
self.cylinder('metal_terminal', [0, 0, 0], 0.049, 0.027, 'steel', 'y', n)
|
| 70 |
+
self.cylinder('terminal_recess', [0, -0.016, 0], 0.03, 0.013, 'iron', 'y', n)
|
| 71 |
+
self.label(p + '_terminal_number_' + str(j), j + 1, [0, -0.025, -0.1], 0.09, 0.055, parent=n)
|
| 72 |
+
self.reg(p + '_slot_' + str(j), n)
|
| 73 |
+
self.slots[i].append(n)
|
| 74 |
+
|
| 75 |
+
def sync(self, g):
|
| 76 |
+
super().sync(g)
|
| 77 |
+
for i, s in enumerate(self.spec['stages']):
|
| 78 |
+
pose = self.extra.get((i, 'wire_pose'))
|
| 79 |
+
if pose is None:
|
| 80 |
+
continue
|
| 81 |
+
assignments = {int(k): int(v) for k, v in g.states[i]['assignment'].items()}
|
| 82 |
+
for j, node in enumerate(self.items[i]):
|
| 83 |
+
slot = next((k for k, v in assignments.items() if v == j), None)
|
| 84 |
+
self.visibility(pose['coils'][j], slot is None)
|
| 85 |
+
self.visibility(pose['plugs'][j], slot is not None)
|
| 86 |
+
if slot is None and s.get('item_source') is None:
|
| 87 |
+
self.transform(node, [(j - 1) * 0.25, -0.015, 0.7925])
|
| 88 |
+
for k, link in enumerate(pose['links'][j]):
|
| 89 |
+
self.visibility(link, slot == k)
|
runtime/h2_runtime/medium88_room_details.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from medium88_scene import MediumScene as FrozenScene
|
| 3 |
+
|
| 4 |
+
class MediumScene(FrozenScene):
|
| 5 |
+
|
| 6 |
+
def float_key(self, i, s, root):
|
| 7 |
+
p = f's{i + 1}'
|
| 8 |
+
jug = self.tool(p + '_tool', root, [-0.46, 0.03, 0.85], 'jug')
|
| 9 |
+
self.tools[i].append(jug)
|
| 10 |
+
tap = self.group(p + '_tap', [0.36, 0.1, 1.22], root)
|
| 11 |
+
self.tube('water_feed', [0, 0.04, -0.41], [0, 0.04, 0], 0.018, 'steel', tap)
|
| 12 |
+
self.tube('faucet_spout', [0, 0.04, 0], [0, -0.11, 0], 0.018, 'steel', tap)
|
| 13 |
+
self.box('faucet_handle', [0, 0.035, 0.065], [0.11, 0.025, 0.025], 'brass', tap)
|
| 14 |
+
self.reg(p + '_tap', tap)
|
| 15 |
+
tank = self.group(p + '_setup', [0, 0.03, 1.04], root)
|
| 16 |
+
self.cylinder('narrow_glass_cylinder', [0, 0, 0], 0.105, 0.45, 'glass', 'z', tank, n=40)
|
| 17 |
+
self.cylinder('supported_cylinder_base', [0, 0, -0.238], 0.12, 0.025, 'steel', 'z', tank)
|
| 18 |
+
self.reg(p + '_setup', tank)
|
| 19 |
+
self.setups[i] = tank
|
| 20 |
+
water = self.group(p + '_water_volume', parent=root)
|
| 21 |
+
self.cylinder('full_water_column', [0, 0, 0], 0.098, 1.0, 'water', 'z', water, n=36)
|
| 22 |
+
with self.og.sim.editing_usd():
|
| 23 |
+
scale = self.G.Xformable(water['prim']).AddScaleOp()
|
| 24 |
+
cork = self.group(p + '_cork_float', parent=root)
|
| 25 |
+
self.cylinder('horizontal_cork_float', [0, 0, 0], 0.07, 0.024, 'wood', 'z', cork, n=30)
|
| 26 |
+
key = self.tool(p + '_float_key', root, [0, 0.021, 0.85], 'key')
|
| 27 |
+
self.transform(key, rpy=[90, 0, 0])
|
| 28 |
+
self.extra[i, 'float_details'] = (jug, water, scale, cork, key)
|
| 29 |
+
|
| 30 |
+
def numeric(self, i, s, root):
|
| 31 |
+
super().numeric(i, s, root)
|
| 32 |
+
if s.get('visual', {}).get('type') == 'successor':
|
| 33 |
+
p = f's{i + 1}'
|
| 34 |
+
self.visibility(self.nodes[p + '_evidence'], False)
|
| 35 |
+
self.label(p + '_page_rule', 'NEXT PAGE / 1 > 2', [0, 0.1, 1.48], 0.78, 0.08, parent=root)
|
| 36 |
+
for j, n in enumerate(s['visual']['before']):
|
| 37 |
+
x = (j - 1) * 0.35
|
| 38 |
+
book = self.group(p + '_open_sample_book_' + str(j), [x, 0.055, 1.15], root)
|
| 39 |
+
self.transform(book, rpy=[-35, 0, 0])
|
| 40 |
+
self.box('open_book_cover', [0, 0.015, 0], [0.31, 0.025, 0.225], 'darkwood', book)
|
| 41 |
+
for side, value in [(-1, str(n)), (1, '?')]:
|
| 42 |
+
page = self.group('sample_page_' + str(j) + '_' + ('left' if side < 0 else 'right'), [side * 0.0775, 0, 0], book)
|
| 43 |
+
self.box('paper_block', [0, 0, 0], [0.148, 0.014, 0.21], 'ivory', page)
|
| 44 |
+
self.show_image(p + '_page_print_' + str(j) + '_' + str(side).replace('-', 'm'), page, [0, -0.008, 0], 0.13, 0.18, self.small_text(value))
|
| 45 |
+
self.tube('book_spine', [0, -0.005, -0.11], [0, -0.005, 0.11], 0.006, 'wood', book)
|
| 46 |
+
self.box('book_stand', [x, 0.18, 0.98], [0.04, 0.08, 0.36], 'iron', root)
|
| 47 |
+
|
| 48 |
+
def special_device(self, i, s, root):
|
| 49 |
+
super().special_device(i, s, root)
|
| 50 |
+
if s['kind'] == 'balance':
|
| 51 |
+
beam, pan, weights = self.extra[i, 'balance']
|
| 52 |
+
for node in beam['meshes']:
|
| 53 |
+
if node['prim'].GetName().startswith('balance_hanger'):
|
| 54 |
+
self.visibility(node, False)
|
| 55 |
+
self.visibility(self.nodes['fixed_six_weight'], False)
|
| 56 |
+
self.visibility(self.nodes[f's{i + 1}_fixed_mass'], False)
|
| 57 |
+
left = self.group('balanced_left_pan', parent=root)
|
| 58 |
+
self.cylinder('left_pan_plate', [0, 0, 0], 0.13, 0.018, 'steel', 'z', left)
|
| 59 |
+
self.cylinder('fixed_six_point_mass', [0, 0, 0.057], 0.072, 0.095, 'steel', 'z', left)
|
| 60 |
+
self.label('fixed_six_point_label', '6', [0, -0.076, 0.057], 0.09, 0.065, parent=left)
|
| 61 |
+
hangers = []
|
| 62 |
+
for side in ['left', 'right']:
|
| 63 |
+
hanger = self.group('vertical_' + side + '_hanger', parent=root)
|
| 64 |
+
self.tube('vertical_chain', [0, 0, 0], [0, 0, -0.17], 0.007, 'brass', hanger)
|
| 65 |
+
hangers.append(hanger)
|
| 66 |
+
self.extra[i, 'balance_details'] = (left, hangers)
|
| 67 |
+
|
| 68 |
+
def sync(self, g):
|
| 69 |
+
super().sync(g)
|
| 70 |
+
for i, s in enumerate(self.spec['stages']):
|
| 71 |
+
state = g.states[i]
|
| 72 |
+
if s['kind'] == 'window_align':
|
| 73 |
+
for j, node in enumerate(self.extra[i, 'adjust_nodes'][2]):
|
| 74 |
+
error = state['angles'][j] - s['target'][j]
|
| 75 |
+
self.transform(node, [error * 0.105, -0.105 if j == 0 else -0.045, 1.15])
|
| 76 |
+
if (i, 'float_details') in self.extra:
|
| 77 |
+
jug, water, scale, cork, key = self.extra[i, 'float_details']
|
| 78 |
+
filled = bool(state['floated'])
|
| 79 |
+
height = 0.4 if filled else 0.0
|
| 80 |
+
self.visibility(water, filled)
|
| 81 |
+
with self.og.sim.editing_usd():
|
| 82 |
+
scale.Set(self.F.Vec3f(1, 1, max(0.001, height)))
|
| 83 |
+
self.transform(water, [0, 0.03, 0.815 + height / 2])
|
| 84 |
+
cork_z = 0.815 + height + 0.012
|
| 85 |
+
self.transform(cork, [0, 0.03, cork_z])
|
| 86 |
+
self.transform(key, [0, 0.021, cork_z + 0.02], rpy=[90, 0, 0])
|
| 87 |
+
self.visibility(key, f's{i + 1}_float_key' not in g.taken)
|
| 88 |
+
if (i, 'balance_details') in self.extra:
|
| 89 |
+
left, hangers = self.extra[i, 'balance_details']
|
| 90 |
+
beam, pan, weights = self.extra[i, 'balance']
|
| 91 |
+
mass = sum((s['weights'][j] for j in state['weights']))
|
| 92 |
+
angle = math.radians((mass - 6) * 3)
|
| 93 |
+
positions = []
|
| 94 |
+
for x, hanger in zip([-0.38, 0.38], hangers):
|
| 95 |
+
tip = [x * math.cos(angle), 0.07, 1.24 - x * math.sin(angle)]
|
| 96 |
+
self.transform(hanger, tip)
|
| 97 |
+
positions.append([tip[0], tip[1], tip[2] - 0.17])
|
| 98 |
+
self.transform(left, positions[0])
|
| 99 |
+
self.transform(pan, positions[1])
|
| 100 |
+
for j, node in enumerate(weights):
|
| 101 |
+
if j in state['weights']:
|
| 102 |
+
self.transform(node, [positions[1][0] + (j % 2 - 0.5) * 0.08, 0.07 + (j // 2 - 0.5) * 0.08, positions[1][2] + 0.048])
|
runtime/h2_runtime/medium88_scene.py
ADDED
|
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, copy, hashlib
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
from easy88_scene import EasyScene
|
| 5 |
+
from easy88_core import ROTATE, ADJUST, BINARY, SEQUENCE, CODE as NUMERIC
|
| 6 |
+
from medium88_clues import board, symbol, PAPER, INK, text
|
| 7 |
+
from font_utils import load_font
|
| 8 |
+
|
| 9 |
+
class MediumScene(EasyScene):
|
| 10 |
+
|
| 11 |
+
def __init__(self, og, run, spec):
|
| 12 |
+
super().__init__(og, run, spec)
|
| 13 |
+
self.spec = spec
|
| 14 |
+
self.views = {}
|
| 15 |
+
self.focus = {}
|
| 16 |
+
self.labels = {}
|
| 17 |
+
self.rewards = []
|
| 18 |
+
self.gates = []
|
| 19 |
+
self.core_cards = []
|
| 20 |
+
self.extra = {}
|
| 21 |
+
self.images = {}
|
| 22 |
+
self.image_sig = {}
|
| 23 |
+
self.lock_nodes = {}
|
| 24 |
+
self.actor_roots = []
|
| 25 |
+
for name in ['controls', 'choice_nodes', 'buffers', 'items', 'slots', 'tools', 'nodes_by_stage']:
|
| 26 |
+
setattr(self, name, [[], [], []])
|
| 27 |
+
self.setups = [None, None, None]
|
| 28 |
+
|
| 29 |
+
def transform(self, group, pos=None, rpy=None):
|
| 30 |
+
self._dynamic_collision_cache = None
|
| 31 |
+
return super().transform(group, pos, rpy)
|
| 32 |
+
|
| 33 |
+
def palette(self):
|
| 34 |
+
super().palette()
|
| 35 |
+
n = int(self.spec['id'][1:])
|
| 36 |
+
pal = [(0.23, 0.34, 0.32), (0.4, 0.33, 0.24), (0.29, 0.37, 0.4), (0.43, 0.38, 0.31)]
|
| 37 |
+
self.mats['paint'] = self.mat('medium_theme', pal[n % 4], rough=0.88)
|
| 38 |
+
self.mat('ivory', (0.75, 0.72, 0.62), rough=0.95)
|
| 39 |
+
self.mat('sample_blue', (0.24, 0.37, 0.44), rough=0.86)
|
| 40 |
+
self.mat('floor_mortar', (0.25, 0.28, 0.27), rough=0.95)
|
| 41 |
+
|
| 42 |
+
def reg(self, key, node):
|
| 43 |
+
self.add_target(key, node)
|
| 44 |
+
if key.startswith('s') and key[1:2].isdigit():
|
| 45 |
+
i = int(key[1]) - 1
|
| 46 |
+
if i < len(self.stage_views):
|
| 47 |
+
self.views[key] = self.stage_views[i]
|
| 48 |
+
return node
|
| 49 |
+
|
| 50 |
+
def show_image(self, key, parent, pos, w, h, im):
|
| 51 |
+
if len(key) > 2 and key[0] == 's' and key[1].isdigit() and key.endswith(('_reference', '_evidence')):
|
| 52 |
+
i = int(key[1]) - 1
|
| 53 |
+
st = self.spec['stages'][i]
|
| 54 |
+
if key == f's{i + 1}_reference' and st.get('visual', {}).get('type') == 'wire_trace':
|
| 55 |
+
pos = [0.12, -0.035, 1.425]
|
| 56 |
+
w = 0.92
|
| 57 |
+
h = 0.34
|
| 58 |
+
elif key == f's{i + 1}_reference':
|
| 59 |
+
pos = [0, 0.27, 1.47]
|
| 60 |
+
w = 1.1
|
| 61 |
+
h = 0.34
|
| 62 |
+
elif key == f's{i + 1}_evidence':
|
| 63 |
+
pos = [0, 0.27, 1.43]
|
| 64 |
+
w = 1.1
|
| 65 |
+
h = 0.38
|
| 66 |
+
if key.endswith(('_reference', '_evidence', '_complete_reference', '_goal')) and any((parent is root for root in self.roots)):
|
| 67 |
+
self.box(key + '_physical_backing', [pos[0], pos[1] + 0.012, pos[2]], [w + 0.025, 0.022, h + 0.025], 'ivory', parent)
|
| 68 |
+
p = self.tex / (key + '.png')
|
| 69 |
+
im.save(p)
|
| 70 |
+
m = self.image_mat('medium_' + key, p)
|
| 71 |
+
return self.plane(key, pos, w, h, (1, 0, 0), (0, 0, 1), None, parent, material=m)
|
| 72 |
+
|
| 73 |
+
def screen(self, key, parent, pos, w, h, im, sig):
|
| 74 |
+
if self.image_sig.get(key) == sig:
|
| 75 |
+
return
|
| 76 |
+
if key in self.images:
|
| 77 |
+
self.visibility(self.images[key], False)
|
| 78 |
+
tag = key + '_' + hashlib.sha256(repr(sig).encode()).hexdigest()[:12]
|
| 79 |
+
self.images[key] = self.show_image(tag, parent, pos, w, h, im)
|
| 80 |
+
self.image_sig[key] = sig
|
| 81 |
+
|
| 82 |
+
def small_text(self, value, size=(600, 170)):
|
| 83 |
+
im = Image.new('RGB', size, (46, 62, 53))
|
| 84 |
+
d = ImageDraw.Draw(im)
|
| 85 |
+
d.text((size[0] / 2, size[1] / 2), str(value), font=load_font(100), anchor='mm', fill=(219, 226, 187))
|
| 86 |
+
return im
|
| 87 |
+
|
| 88 |
+
def adjust(self, i, s, root):
|
| 89 |
+
p = f's{i + 1}'
|
| 90 |
+
nodes = []
|
| 91 |
+
kind = s['kind']
|
| 92 |
+
v = s.get('visual', {}).get('type')
|
| 93 |
+
for j in range(2):
|
| 94 |
+
self.controls[i].append(self.button(p + '_control_' + str(j), root, [-0.25 + j * 0.5, -0.17, 0.81], 'up', 0.12))
|
| 95 |
+
if kind == 'block_faces':
|
| 96 |
+
faces = ['circle', 'triangle', 'square', 'star', 'cross', 'leaf']
|
| 97 |
+
for j in range(2):
|
| 98 |
+
n = self.group(p + '_six_face_' + str(j), [(j - 0.5) * 0.48, -0.1, 1.17], root)
|
| 99 |
+
self.box('six_face_column', [0, 0, 0], [0.24, 0.24, 0.24], 'wood', n)
|
| 100 |
+
for k, orientation in enumerate([(0, 0, 0), (0, 0, 90), (0, 0, 180), (0, 0, -90), (-90, 0, 0), (90, 0, 0)]):
|
| 101 |
+
f = self.group(p + '_face_' + str(j) + '_' + str(k), parent=n)
|
| 102 |
+
self.transform(f, rpy=orientation)
|
| 103 |
+
self.show_image(p + '_face_print_' + str(j) + '_' + str(k), f, [0, -0.122, 0], 0.21, 0.21, board({'type': 'symbol_strip', 'symbols': [faces[k]]}))
|
| 104 |
+
nodes.append(n)
|
| 105 |
+
self.show_image(p + '_six_face_reference', root, [0, 0.26, 1.52], 0.68, 0.16, board({'type': 'symbol_strip', 'symbols': ['star', 'cross']}))
|
| 106 |
+
elif v == 'pattern_rings':
|
| 107 |
+
for j in range(2):
|
| 108 |
+
n = self.group(p + '_ring_' + str(j), [(j - 0.5) * 0.47, -0.08, 1.22], root)
|
| 109 |
+
self.cylinder('brass_ring_body', [0, 0, 0], 0.18, 0.035, 'brass', 'y', n, n=40)
|
| 110 |
+
for a, b in [([-0.12, -0.025, 0], [0, -0.025, 0]), ([0, -0.025, 0], [0, -0.025, 0.13])]:
|
| 111 |
+
self.tube('tea_branch', a, b, 0.011, 'leaf_green', n)
|
| 112 |
+
for x, z in [(-0.07, 0.025), (0.025, 0.08)]:
|
| 113 |
+
self.box('branch_leaf', [x, -0.03, z], [0.045, 0.014, 0.025], 'leaf_green', n)
|
| 114 |
+
t = s['target'][j] * math.pi / 2
|
| 115 |
+
for dx, dz in [(-0.2, 0), (0, 0.2)]:
|
| 116 |
+
x = (j - 0.5) * 0.47 + dx * math.cos(t) + dz * math.sin(t)
|
| 117 |
+
z = 1.22 - dx * math.sin(t) + dz * math.cos(t)
|
| 118 |
+
self.cylinder('fixed_tea_branch_end', [x, -0.075, z], 0.015, 0.025, 'leaf_green', 'y', root)
|
| 119 |
+
nodes.append(n)
|
| 120 |
+
elif kind == 'window_align':
|
| 121 |
+
self.box('fixed_interior_handle', [0, 0.11, 1.15], [0.11, 0.04, 0.065], 'brass', root)
|
| 122 |
+
for j in range(2):
|
| 123 |
+
n = self.group(p + '_window_layer_' + str(j), parent=root)
|
| 124 |
+
for x in [-0.19, 0.19]:
|
| 125 |
+
self.box('window_side', [x, 0, 0], [0.24, 0.035, 0.38], 'steel', n)
|
| 126 |
+
for z in [-0.16, 0.16]:
|
| 127 |
+
self.box('window_rail', [0, 0, z], [0.15, 0.035, 0.06], 'steel', n)
|
| 128 |
+
nodes.append(n)
|
| 129 |
+
elif kind == 'support_align':
|
| 130 |
+
for j in range(2):
|
| 131 |
+
n = self.group(p + '_jack_' + str(j), parent=root)
|
| 132 |
+
self.cylinder('support_screw', [0, 0, 0], 0.023, 0.27, 'steel', 'z', n)
|
| 133 |
+
self.box('support_pad', [0, 0, 0.14], [0.2, 0.11, 0.025], 'iron', n)
|
| 134 |
+
nodes.append(n)
|
| 135 |
+
frame = self.group(p + '_mirror_frame', parent=root)
|
| 136 |
+
for x in [-0.39, 0.39]:
|
| 137 |
+
self.box('mirror_frame_side', [x, 0, 0.21], [0.03, 0.055, 0.44], 'darkwood', frame)
|
| 138 |
+
for z in [0, 0.43]:
|
| 139 |
+
self.box('mirror_frame_bar', [0, 0, z], [0.81, 0.055, 0.03], 'darkwood', frame)
|
| 140 |
+
self.box('matte_back_of_mirror', [0, 0.015, 0.21], [0.74, 0.02, 0.39], 'steel', frame)
|
| 141 |
+
self.box('fixed_alignment_line', [0, 0.07, 1.04], [1.03, 0.025, 0.015], 'red', root)
|
| 142 |
+
self.extra[i, 'support_frame'] = frame
|
| 143 |
+
else:
|
| 144 |
+
options = ['circle', 'triangle', 'square', 'star']
|
| 145 |
+
for j in range(2):
|
| 146 |
+
x = (j - 0.5) * 0.48
|
| 147 |
+
self.box('lever_track', [x, 0.1, 1.24], [0.035, 0.045, 0.42], 'iron', root)
|
| 148 |
+
self.box('lever_scale_mount', [x + 0.1, 0.1, 1.23], [0.2, 0.05, 0.42], 'wood', root)
|
| 149 |
+
self.tube('lever_back_support', [x, 0.28, 1.23], [x, 0.12, 1.23], 0.018, 'iron', root)
|
| 150 |
+
for k in range(4):
|
| 151 |
+
self.show_image(p + '_lever_stop_' + str(j) + '_' + str(k), root, [x + 0.1, 0.073, 1.04 + k * 0.1], 0.08, 0.08, board({'type': 'symbol_strip', 'symbols': [options[k]]}))
|
| 152 |
+
self.show_image(p + '_lever_reference_' + str(j), root, [x, 0.08, 1.52], 0.14, 0.13, board({'type': 'symbol_strip', 'symbols': [options[s['target'][j]]]}))
|
| 153 |
+
n = self.group(p + '_lever_' + str(j), parent=root)
|
| 154 |
+
self.box('lever_slider', [0, 0, 0], [0.1, 0.07, 0.04], 'brass', n)
|
| 155 |
+
nodes.append(n)
|
| 156 |
+
if kind == 'block_faces':
|
| 157 |
+
for j in range(2):
|
| 158 |
+
self.cylinder('column_pedestal', [(j - 0.5) * 0.48, -0.1, 0.92125], 0.025, 0.2575, 'iron', 'z', root)
|
| 159 |
+
elif v == 'pattern_rings':
|
| 160 |
+
for j in range(2):
|
| 161 |
+
self.tube('ring_spindle', [(j - 0.5) * 0.47, 0.28, 1.22], [(j - 0.5) * 0.47, -0.0625, 1.22], 0.021, 'steel', root)
|
| 162 |
+
elif kind == 'window_align':
|
| 163 |
+
self.tube('handle_mount', [0, 0.28, 1.15], [0, 0.11, 1.15], 0.018, 'iron', root)
|
| 164 |
+
for xx in [-0.64, 0.64]:
|
| 165 |
+
for zz in [1.0, 1.3]:
|
| 166 |
+
self.tube('window_slide_support', [xx, 0.28, zz], [xx, -0.13, zz], 0.012, 'steel', root)
|
| 167 |
+
elif kind != 'support_align':
|
| 168 |
+
for j, node in enumerate(nodes):
|
| 169 |
+
self.tube('lever_slide_link', [0, 0.035, 0], [0, 0.1, 0], 0.012, 'steel', node)
|
| 170 |
+
self.extra[i, 'adjust_nodes'] = (kind, v, nodes)
|
| 171 |
+
|
| 172 |
+
def assign(self, i, s, root):
|
| 173 |
+
p = f's{i + 1}'
|
| 174 |
+
items = s['items']
|
| 175 |
+
rack = s.get('rack_order', list(range(len(items))))
|
| 176 |
+
for j, item in enumerate(items):
|
| 177 |
+
n = self.group(p + '_item_' + str(j), parent=root)
|
| 178 |
+
self.box('component_body', [0, 0, 0], [0.17, 0.035, 0.15], 'ivory', n)
|
| 179 |
+
sym = item.get('symbol', 'circle')
|
| 180 |
+
v = {'type': 'symbol_strip', 'symbols': sym.split('>') if '>' in str(sym) else [sym]}
|
| 181 |
+
if sym in 'ABCD' and len(sym) == 1:
|
| 182 |
+
im = Image.new('RGB', (320, 220), PAPER)
|
| 183 |
+
d = ImageDraw.Draw(im)
|
| 184 |
+
gap = 45 + 35 * 'ABCD'.index(sym)
|
| 185 |
+
for x in [160 - gap / 2, 160 + gap / 2]:
|
| 186 |
+
d.ellipse((x - 12, 95, x + 12, 119), fill=INK)
|
| 187 |
+
text(d, (160, 175), sym, 35)
|
| 188 |
+
else:
|
| 189 |
+
im = board(v)
|
| 190 |
+
self.show_image(p + '_component_print_' + str(j), n, [0, -0.019, 0], 0.16, 0.14, im)
|
| 191 |
+
x = (rack.index(j) - (len(items) - 1) / 2) * 0.24
|
| 192 |
+
self.transform(n, [x, -0.015, 0.87])
|
| 193 |
+
self.reg(p + '_item_' + str(j), n)
|
| 194 |
+
self.items[i].append(n)
|
| 195 |
+
self.box('component_rest', [x, 0.016, 0.805], [0.19, 0.1, 0.025], 'wood', root)
|
| 196 |
+
for j in range(s['slots']):
|
| 197 |
+
x = (j - (s['slots'] - 1) / 2) * 0.25
|
| 198 |
+
n = self.group(p + '_slot_' + str(j), [x, -0.12, 1.12], root)
|
| 199 |
+
self.box('component_socket', [0, 0, 0], [0.2, 0.04, 0.18], 'iron', n)
|
| 200 |
+
self.reg(p + '_slot_' + str(j), n)
|
| 201 |
+
self.slots[i].append(n)
|
| 202 |
+
self.label(p + '_slot_mark_' + str(j), str(j + 1), [0, -0.023, -0.115], 0.1, 0.055, parent=n)
|
| 203 |
+
self.box('fixture_socket_panel', [0, 0.05, 1.12], [1.12, 0.34, 0.32], 'paint', root)
|
| 204 |
+
for xx in [-0.47, 0.47]:
|
| 205 |
+
self.tube('socket_panel_mount', [xx, 0.22, 1.12], [xx, 0.3, 1.12], 0.02, 'iron', root)
|
| 206 |
+
|
| 207 |
+
def button(self, key, parent, pos, symbol='circle', size=0.14):
|
| 208 |
+
i = int(key[1]) - 1 if key.startswith('s') and key[1:2].isdigit() else None
|
| 209 |
+
st = self.spec['stages'][i] if i is not None else {}
|
| 210 |
+
kind = st.get('kind')
|
| 211 |
+
pos = list(pos)
|
| 212 |
+
if key.endswith(('_confirm', '_reset')):
|
| 213 |
+
pos = [0.6 if key.endswith('_confirm') else -0.6, 0.06, 0.875]
|
| 214 |
+
n = self.group(key, pos, parent)
|
| 215 |
+
self.box('mounted_button_pod', [0, 0, 0], [0.17, 0.23, 0.165], 'paint', n)
|
| 216 |
+
self.box('pushbutton_bezel', [0, -0.122, 0], [0.12, 0.025, 0.115], 'iron', n)
|
| 217 |
+
self.box('pushbutton_cap', [0, -0.139, 0], [0.105, 0.018, 0.095], 'ivory', n)
|
| 218 |
+
value = 'CHECK' if key.endswith('_confirm') else 'RESET'
|
| 219 |
+
im = Image.new('RGB', (500, 300), PAPER)
|
| 220 |
+
d = ImageDraw.Draw(im)
|
| 221 |
+
d.text((250, 150), value, font=load_font(85), fill=INK, anchor='mm')
|
| 222 |
+
self.show_image(key + '_cap_legend', n, [0, -0.149, 0], 0.098, 0.083, im)
|
| 223 |
+
self.reg(key, n)
|
| 224 |
+
return n
|
| 225 |
+
if key.endswith('_play'):
|
| 226 |
+
pos = [0, 0.075, 1.18]
|
| 227 |
+
elif '_choice_' in key:
|
| 228 |
+
pos[1] = -0.04
|
| 229 |
+
pos[2] = 0.875
|
| 230 |
+
if kind == 'pushbox':
|
| 231 |
+
pos[1] = -0.28
|
| 232 |
+
elif '_control_' in key and kind in ADJUST:
|
| 233 |
+
pos[1] = -0.04
|
| 234 |
+
pos[2] = 0.875
|
| 235 |
+
elif '_control_' in key and kind in BINARY:
|
| 236 |
+
j = int(key.rsplit('_', 1)[1])
|
| 237 |
+
pos[1] = -0.07
|
| 238 |
+
pos[2] = 1.12 - j // int(st.get('cols', 2)) * 0.22
|
| 239 |
+
return super().button(key, parent, pos, symbol, size)
|
| 240 |
+
|
| 241 |
+
def rotors(self, i, s, root):
|
| 242 |
+
if not s.get('route_special'):
|
| 243 |
+
super().rotors(i, s, root)
|
| 244 |
+
for node in self.controls[i]:
|
| 245 |
+
x, y, z = map(float, node['translate'].Get())
|
| 246 |
+
self.tube('visible_rotor_spindle', [x, 0.28, z], [x, y + 0.02, z], 0.022, 'steel', root)
|
| 247 |
+
return
|
| 248 |
+
self.box('route_device_mounting_plate', [0, 0.24, 1.205], [0.76, 0.12, 0.98], 'paint', root)
|
| 249 |
+
p = f's{i + 1}'
|
| 250 |
+
space = 0.23
|
| 251 |
+
for r in range(4):
|
| 252 |
+
for c in range(3):
|
| 253 |
+
self.box('route_grid', [(c - 1) * space, 0.16, 1.55 - r * space], [space * 0.97, 0.035, space * 0.97], 'ivory', root)
|
| 254 |
+
for j, (r, c) in enumerate(s['cells']):
|
| 255 |
+
n = self.group(p + '_control_' + str(j), [(c - 1) * space, 0.11, 1.55 - r * space], root)
|
| 256 |
+
self.box('elbow_base', [0, 0, 0], [space * 0.95, 0.035, space * 0.95], 'iron', n)
|
| 257 |
+
for dx, dz in [(0, space * 0.48), (space * 0.48, 0)]:
|
| 258 |
+
self.tube('rotating_elbow', [0, -0.03, 0], [dx, -0.03, dz], 0.018, 'brass', n)
|
| 259 |
+
self.reg(p + '_control_' + str(j), n)
|
| 260 |
+
self.controls[i].append(n)
|
| 261 |
+
self.tube('route_rotor_spindle', [(c - 1) * space, 0.18, 1.55 - r * space], [(c - 1) * space, 0.1275, 1.55 - r * space], 0.02, 'steel', root)
|
| 262 |
+
for r, c, ports in [(3, 0, [0, 2]), (2, 1, [1, 3]), (1, 1, [0, 1]), (0, 1, [0, 2])]:
|
| 263 |
+
for port in ports:
|
| 264 |
+
dx, dz = [(0, space / 2), (space / 2, 0), (0, -space / 2), (-space / 2, 0)][port]
|
| 265 |
+
self.tube('fixed_route', [(c - 1) * space, 0.085, 1.55 - r * space], [(c - 1) * space + dx, 0.085, 1.55 - r * space + dz], 0.018, 'steel', root)
|
| 266 |
+
self.label(p + '_source', 'S', [-space, 0.055, 0.82], 0.09, 0.065, parent=root)
|
| 267 |
+
self.label(p + '_target', 'T', [0, 0.055, 1.62], 0.09, 0.065, parent=root)
|
| 268 |
+
|
| 269 |
+
def sliding(self, i, s, root):
|
| 270 |
+
p = f's{i + 1}'
|
| 271 |
+
space = 0.25
|
| 272 |
+
nodes = {}
|
| 273 |
+
self.box('sliding_tile_mechanism_body', [0, 0.065, 1.125], [0.88, 0.44, 0.55], 'paint', root)
|
| 274 |
+
for xx in [-0.405, 0.405]:
|
| 275 |
+
self.box('tile_guide_side', [xx, -0.185, 1.125], [0.025, 0.055, 0.55], 'steel', root)
|
| 276 |
+
for zz in [0.86, 1.39]:
|
| 277 |
+
self.box('tile_guide_crossbar', [0, -0.185, zz], [0.85, 0.055, 0.025], 'steel', root)
|
| 278 |
+
for j, value in enumerate(s['target']):
|
| 279 |
+
if not value:
|
| 280 |
+
continue
|
| 281 |
+
n = self.group(p + '_piece_' + str(j), parent=root)
|
| 282 |
+
self.box('archive_tile', [0, 0, 0], [0.235, 0.045, 0.235], 'wood', n)
|
| 283 |
+
self.show_image(p + '_tile_letter_' + value, n, [0, -0.025, 0], 0.21, 0.21, self.small_text(value))
|
| 284 |
+
nodes[value] = n
|
| 285 |
+
for j in range(6):
|
| 286 |
+
r, c = divmod(j, 3)
|
| 287 |
+
n = self.group(p + '_tile_' + str(j), [(c - 1) * space, -0.17, 1.25 - r * space], root)
|
| 288 |
+
self.box('tile_slot', [0, 0, 0], [space * 0.98, 0.025, space * 0.98], 'iron', n)
|
| 289 |
+
self.reg(p + '_tile_' + str(j), n)
|
| 290 |
+
self.special[i, 'sliding'] = (nodes, space, 2, 3)
|
| 291 |
+
self.show_image(p + '_goal', root, [0, 0.26, 1.57], 0.68, 0.2, board({'type': 'table', 'rows': [['A', 'B', 'C'], ['D', 'E', None]]}))
|
| 292 |
+
|
| 293 |
+
def drawer(self, key, root, width=1.05):
|
| 294 |
+
z = 0.57
|
| 295 |
+
depth = 0.43
|
| 296 |
+
n = self.group(key, [0, -0.02, z], root)
|
| 297 |
+
self.box(key + '_bottom', [0, 0.19, -0.095], [width, depth, 0.025], 'wood', n)
|
| 298 |
+
for x in [-width / 2, width / 2]:
|
| 299 |
+
self.box(key + '_side', [x, 0.19, -0.025], [0.025, depth, 0.17], 'wood', n)
|
| 300 |
+
self.box(key + '_back', [0, 0.4, -0.025], [width, 0.025, 0.17], 'wood', n)
|
| 301 |
+
self.box(key + '_front', [0, -0.015, -0.025], [width + 0.04, 0.045, 0.2], 'paint', n)
|
| 302 |
+
self.box(key + '_pull', [0, -0.06, -0.025], [0.23, 0.035, 0.035], 'brass', n)
|
| 303 |
+
for x in [-width / 2 - 0.035, width / 2 + 0.035]:
|
| 304 |
+
self.box(key + '_rail', [x, 0.2, 0.55], [0.018, 0.42, 0.022], 'steel', root)
|
| 305 |
+
self.reg(key, dict(n, meshes=[self.nodes[key + '_front'], self.nodes[key + '_pull']]))
|
| 306 |
+
return n
|
| 307 |
+
|
| 308 |
+
def furniture(self, i, s, xy, angle):
|
| 309 |
+
root = self.group('furniture_' + str(i), [xy[0], xy[1], 0])
|
| 310 |
+
self.transform(root, rpy=[0, 0, angle])
|
| 311 |
+
self.actor_roots.append(root)
|
| 312 |
+
w = 1.42
|
| 313 |
+
dep = 0.64
|
| 314 |
+
self.box('worktop', [0, 0.2, 0.76], [w, dep, 0.065], 'wood', root)
|
| 315 |
+
for x in [-0.62, 0.62]:
|
| 316 |
+
for y in [-0.06, 0.46]:
|
| 317 |
+
self.box('bench_leg', [x, y, 0.365], [0.07, 0.07, 0.73], 'iron', root)
|
| 318 |
+
self.box('bench_lower_shelf', [0, 0.2, 0.23], [1.28, 0.49, 0.035], 'wood', root)
|
| 319 |
+
self.box('drawer_housing_back', [0, 0.45, 0.57], [1.19, 0.03, 0.28], 'wood', root)
|
| 320 |
+
for x in [-0.59, 0.59]:
|
| 321 |
+
self.box('drawer_housing_side', [x, 0.21, 0.57], [0.035, 0.5, 0.28], 'wood', root)
|
| 322 |
+
actual_shelf = self.spec['id'] in ('R36', 'R41') and s['room'] == 'B' and (self.spec['last']['B'] == i)
|
| 323 |
+
if actual_shelf:
|
| 324 |
+
fixed = self.group('sample_cubbies_' + str(i), [0, 0, 0.55], root)
|
| 325 |
+
for z in [0.27, 0.5, 0.74]:
|
| 326 |
+
self.box('cubby_shelf', [0, 0.2, z], [1.12, 0.44, 0.025], 'ivory', fixed)
|
| 327 |
+
self.box('cubby_central_divider', [0, 0.2, 0.5], [0.018, 0.44, 0.48], 'wood', fixed)
|
| 328 |
+
self.box('cubby_back', [0, 0.45, 1.06], [1.18, 0.035, 0.52], 'wood', root)
|
| 329 |
+
for xx in [-0.58, 0.58]:
|
| 330 |
+
self.box('cubby_side', [xx, 0.17, 1.06], [0.035, 0.56, 0.52], 'wood', root)
|
| 331 |
+
self.box('cubby_supported_plinth', [0, 0.2, 0.8075], [1.18, 0.48, 0.03], 'wood', root)
|
| 332 |
+
reward = self.group('reward_' + str(i), [-0.57, -0.14, 1.06], root)
|
| 333 |
+
self.box('storage_case_door', [0.57, 0, 0], [1.14, 0.035, 0.48], 'paint', reward)
|
| 334 |
+
self.box('storage_case_pull', [1.04, -0.035, 0], [0.025, 0.025, 0.13], 'brass', reward)
|
| 335 |
+
self.reg('reward_' + str(i), reward)
|
| 336 |
+
self.extra[i, 'sample_case'] = fixed
|
| 337 |
+
else:
|
| 338 |
+
reward = self.drawer('reward_' + str(i), root)
|
| 339 |
+
self.rewards.append(reward)
|
| 340 |
+
self.extra[i, 'reward_collision'] = {'meshes': list(reward['meshes'])}
|
| 341 |
+
if s['kind'] not in ('float_key', 'balance', 'pushbox'):
|
| 342 |
+
self.box('device_back', [0, 0.32, 1.15], [1.23, 0.08, 0.67], 'paint' if s['kind'] in ('rotate_pipes', 'assign', 'window_align') else 'darkwood', root)
|
| 343 |
+
for x in [-0.55, 0.55]:
|
| 344 |
+
self.box('device_support', [x, 0.3, 0.92], [0.04, 0.05, 0.34], 'iron', root)
|
| 345 |
+
gate = None
|
| 346 |
+
if s.get('parent') is not None:
|
| 347 |
+
gate = self.group('s' + str(i + 1) + '_cover', [0, -0.37, 1.2], root)
|
| 348 |
+
leaves = []
|
| 349 |
+
inner = []
|
| 350 |
+
for side in [-1, 1]:
|
| 351 |
+
leaf = self.group('cabinet_outer_' + str(i) + '_' + ('left' if side < 0 else 'right'), [side * 0.66, 0, 0], gate)
|
| 352 |
+
self.box('folding_outer_leaf', [-side * 0.165, 0, 0], [0.33, 0.045, 0.94], 'paint', leaf)
|
| 353 |
+
second = self.group('cabinet_inner_' + str(i) + '_' + ('left' if side < 0 else 'right'), [-side * 0.33, -0.026, 0], leaf)
|
| 354 |
+
self.box('folding_inner_leaf', [-side * 0.165, 0.026, 0], [0.33, 0.045, 0.94], 'paint', second)
|
| 355 |
+
self.box('folding_door_handle', [-side * 0.24, -0.019, -0.05], [0.028, 0.03, 0.16], 'brass', second)
|
| 356 |
+
for z in [-0.32, 0.32]:
|
| 357 |
+
self.cylinder('visible_fold_hinge', [-side * 0.33, -0.026, z], 0.011, 0.045, 'steel', 'z', leaf)
|
| 358 |
+
leaves.append(leaf)
|
| 359 |
+
inner.append(second)
|
| 360 |
+
self.extra[i, 'gate_leaves'] = leaves
|
| 361 |
+
self.extra[i, 'fold_inner_leaves'] = inner
|
| 362 |
+
self.reg(f's{i + 1}_cover', gate)
|
| 363 |
+
self.gates.append(gate)
|
| 364 |
+
if gate:
|
| 365 |
+
for xx in [-0.68, 0.68]:
|
| 366 |
+
self.box('upper_cabinet_side', [xx, 0.02, 1.2], [0.035, 0.72, 0.98], 'wood', root)
|
| 367 |
+
self.box('upper_cabinet_top', [0, 0.02, 1.7], [1.4, 0.72, 0.035], 'wood', root)
|
| 368 |
+
self.box('upper_cabinet_floor', [0, 0.02, 0.715], [1.4, 0.72, 0.025], 'wood', root)
|
| 369 |
+
points = self.triangles(root).reshape(-1, 3)
|
| 370 |
+
lo = points.min(0)
|
| 371 |
+
hi = points.max(0)
|
| 372 |
+
self.add_obstacle(lo[0], lo[1], hi[0], hi[1])
|
| 373 |
+
return root
|
| 374 |
+
|
| 375 |
+
def core_card(self, i, root, reward):
|
| 376 |
+
room = self.spec['stages'][i]['room']
|
| 377 |
+
if self.spec['last'][room] != i:
|
| 378 |
+
self.core_cards.append(None)
|
| 379 |
+
return
|
| 380 |
+
if (i, 'sample_case') in self.extra:
|
| 381 |
+
case = self.extra[i, 'sample_case']
|
| 382 |
+
groups = [['book', 'cup'], ['hook', 'box'], ['hat', 'shoe'], ['leaf_clip', 'scroll']] if self.spec['id'] == 'R36' else [['square_box', 'round_cup'], ['star_plate', 'triangle_plate'], ['comb', 'ruler'], ['ball', 'hat']]
|
| 383 |
+
numbers = [[8, 1], [4, 7], [6, 2], [3, 9]] if self.spec['id'] == 'R41' else None
|
| 384 |
+
for group, objects in enumerate(groups):
|
| 385 |
+
col = group % 2
|
| 386 |
+
row = group // 2
|
| 387 |
+
xc = -0.28 + col * 0.56
|
| 388 |
+
base = 0.285 + (1 - row) * 0.23
|
| 389 |
+
self.label('group_mark_' + str(group), group + 1, [xc - 0.22, -0.022, base + 0.19], 0.065, 0.04, parent=case)
|
| 390 |
+
for j, kind in enumerate(objects):
|
| 391 |
+
x = xc + (j - 0.5) * 0.24
|
| 392 |
+
self.reference_object('sample_' + str(group) + '_' + str(j), case, [x, 0.11, base], kind)
|
| 393 |
+
if numbers:
|
| 394 |
+
self.label('sample_number_' + str(group) + '_' + str(j), numbers[group][j], [x, -0.025, base + 0.02], 0.09, 0.045, parent=case)
|
| 395 |
+
self.reg('clue_' + room, case)
|
| 396 |
+
self.core_cards.append(None)
|
| 397 |
+
return
|
| 398 |
+
im = board(self.spec['clues'][room], size=(1200, 720))
|
| 399 |
+
width, depth = (0.98, 0.42)
|
| 400 |
+
cx = 0.0
|
| 401 |
+
if self.spec['id'] == 'R23' and room == 'A':
|
| 402 |
+
width, depth, cx = (0.62, 0.34, -0.19)
|
| 403 |
+
self.box('lead_storage_divider', [0.15, 0.19, 0.105], [0.018, 0.38, 0.04], 'wood', reward)
|
| 404 |
+
self.box('lead_storage_shelf', [0.335, 0.19, 0.084], [0.31, 0.38, 0.012], 'wood', reward)
|
| 405 |
+
for xx in [0.2, 0.47]:
|
| 406 |
+
for yy in [0.04, 0.35]:
|
| 407 |
+
self.box('lead_shelf_leg', [xx, yy, -0.00225], [0.025, 0.025, 0.1605], 'iron', reward)
|
| 408 |
+
self.box('supported_reading_tray', [cx, 0.19, 0.084], [width, 0.38, 0.012], 'wood', reward)
|
| 409 |
+
for xx in [cx - width / 2 + 0.04, cx + width / 2 - 0.04]:
|
| 410 |
+
for yy in [0.04, 0.35]:
|
| 411 |
+
self.box('reading_tray_leg', [xx, yy, -0.00225], [0.025, 0.025, 0.1605], 'iron', reward)
|
| 412 |
+
n = self.group('clue_' + room, [cx, 0.195, 0.1], reward)
|
| 413 |
+
self.box('record_backing', [0, 0, 0], [width, 0.018, depth], 'ivory', n)
|
| 414 |
+
self.transform(n, rpy=[-90, 0, 0])
|
| 415 |
+
self.show_image('clue_' + room + '_print', n, [0, -0.011, 0], width - 0.03, depth - 0.03, im)
|
| 416 |
+
self.reg('clue_' + room, n)
|
| 417 |
+
self.core_cards.append(n)
|
| 418 |
+
if self.spec['id'] == 'R24' and room == 'B':
|
| 419 |
+
im = Image.new('RGBA', (1200, 720), (221, 215, 192, 255))
|
| 420 |
+
d = ImageDraw.Draw(im)
|
| 421 |
+
for j, (r, c) in enumerate(self.spec['clues']['A']['points']):
|
| 422 |
+
x = 180 + (c + 0.5) * 940 / 4
|
| 423 |
+
y = 160 + (r + 0.5) * 480 / 3
|
| 424 |
+
d.ellipse((x - 53, y - 53, x + 53, y + 53), fill=(0, 0, 0, 0))
|
| 425 |
+
d.text((x + 58, y - 42), str(j + 1), font=load_font(48), fill=(40, 45, 45, 255))
|
| 426 |
+
path = self.tex / 'locator_mask.png'
|
| 427 |
+
im.save(path)
|
| 428 |
+
mat = self.image_mat('locator_mask', path)
|
| 429 |
+
with self.og.sim.editing_usd():
|
| 430 |
+
sh = self.S.Shader(self.stage.GetPrimAtPath(str(mat.GetPath()) + '/surface'))
|
| 431 |
+
tex = self.S.Shader(self.stage.GetPrimAtPath(str(mat.GetPath()) + '/texture'))
|
| 432 |
+
tex.CreateOutput('a', self.D.ValueTypeNames.Float)
|
| 433 |
+
sh.CreateInput('opacity', self.D.ValueTypeNames.Float).ConnectToSource(tex.ConnectableAPI(), 'a')
|
| 434 |
+
mask = self.plane('locator_mask', [0, -0.014, 0], 0.95, 0.39, (1, 0, 0), (0, 0, 1), None, n, material=mat)
|
| 435 |
+
self.extra[i, 'locator_mask'] = mask
|
| 436 |
+
|
| 437 |
+
def reference_object(self, key, parent, pos, kind):
|
| 438 |
+
from easy88_physical_objects import object_mesh, _materials
|
| 439 |
+
_materials(self)
|
| 440 |
+
basic = {'round_cup': 'cup', 'square_box': 'box'}
|
| 441 |
+
kind = basic.get(kind, kind)
|
| 442 |
+
if kind in ['book', 'cup', 'hat', 'shoe', 'ball', 'bottle']:
|
| 443 |
+
return object_mesh(self, key, parent, pos, kind)
|
| 444 |
+
n = self.group(key, pos, parent)
|
| 445 |
+
if kind == 'box':
|
| 446 |
+
self.box('closed_sample_box', [0, 0, 0.055], [0.12, 0.095, 0.11], 'sample_blue', n)
|
| 447 |
+
self.box('box_lid_seam', [0, 0, 0.09], [0.125, 0.1, 0.012], 'ivory', n)
|
| 448 |
+
elif kind == 'comb':
|
| 449 |
+
self.box('comb_spine', [0, 0, 0.11], [0.13, 0.025, 0.025], 'brass', n)
|
| 450 |
+
for j in range(7):
|
| 451 |
+
self.box('comb_tooth', [-0.055 + j * 0.018, 0, 0.065], [0.009, 0.025, 0.085], 'brass', n)
|
| 452 |
+
elif kind == 'ruler':
|
| 453 |
+
self.box('sample_ruler', [0, 0, 0.07], [0.14, 0.018, 0.055], 'steel', n)
|
| 454 |
+
for j in range(8):
|
| 455 |
+
self.box('ruler_tick', [-0.06 + j * 0.016, -0.01, 0.077], [0.003, 0.002, 0.023], 'iron', n)
|
| 456 |
+
elif kind == 'scroll':
|
| 457 |
+
self.cylinder('rolled_record', [0, 0, 0.06], 0.035, 0.12, 'ivory', 'z', n)
|
| 458 |
+
self.cylinder('paper_roll_core', [0, 0, 0.123], 0.017, 0.005, 'darkwood', 'z', n)
|
| 459 |
+
elif kind == 'hook':
|
| 460 |
+
self.tube('hook_stem', [0.02, 0, 0.04], [0.02, 0, 0.14], 0.008, 'steel', n)
|
| 461 |
+
for j in range(12):
|
| 462 |
+
a = math.pi + j * math.pi / 12
|
| 463 |
+
b = math.pi + (j + 1) * math.pi / 12
|
| 464 |
+
self.tube('hook_bend', [-0.014 + 0.034 * math.cos(a), 0, 0.04 + 0.034 * math.sin(a)], [-0.014 + 0.034 * math.cos(b), 0, 0.04 + 0.034 * math.sin(b)], 0.008, 'steel', n)
|
| 465 |
+
else:
|
| 466 |
+
if kind == 'star_plate':
|
| 467 |
+
points = []
|
| 468 |
+
for j in range(10):
|
| 469 |
+
a = j * math.pi / 5 + math.pi / 2
|
| 470 |
+
r = 0.073 if j % 2 == 0 else 0.035
|
| 471 |
+
points.append([r * math.cos(a), 0, 0.08 + r * math.sin(a)])
|
| 472 |
+
elif kind == 'triangle_plate':
|
| 473 |
+
points = [[-0.067, 0, 0.012], [0.067, 0, 0.012], [0, 0, 0.15]]
|
| 474 |
+
else:
|
| 475 |
+
points = [[-0.045, 0, 0.02], [-0.05, 0, 0.09], [0.035, 0, 0.16], [0.05, 0, 0.08]]
|
| 476 |
+
self.mesh('shaped_sample_plate', points, [list(range(len(points)))], 'brass' if kind == 'star_plate' else 'sample_blue', n)
|
| 477 |
+
self.box('sample_plate_stand', [0, 0.008, 0.01], [0.11, 0.065, 0.015], 'wood', n)
|
| 478 |
+
return n
|
| 479 |
+
|
| 480 |
+
def numeric(self, i, s, root):
|
| 481 |
+
p = f's{i + 1}'
|
| 482 |
+
v = s.get('visual', {})
|
| 483 |
+
kind = v.get('type')
|
| 484 |
+
if (s.get('setup') or {}).get('kind') == 'weigh':
|
| 485 |
+
self.box('scale_base', [0, 0.02, 0.85], [0.51, 0.39, 0.12], 'sample_blue', root)
|
| 486 |
+
self.cylinder('scale_stem', [0, 0.09, 0.96], 0.025, 0.14, 'steel', 'z', root)
|
| 487 |
+
pan = self.group(p + '_setup', [0, 0.09, 1.04], root)
|
| 488 |
+
self.box('scale_tray', [0, 0, 0], [0.37, 0.3, 0.025], 'steel', pan)
|
| 489 |
+
for x in [-0.18, 0.18]:
|
| 490 |
+
self.box('tray_side', [x, 0, 0.025], [0.012, 0.3, 0.05], 'steel', pan)
|
| 491 |
+
self.reg(p + '_setup', pan)
|
| 492 |
+
self.setups[i] = pan
|
| 493 |
+
self.label(p + '_tare', 'TRAY ' + str(v.get('tare', 0)) + ' g', [0, -0.17, 1.055], 0.31, 0.045, parent=root)
|
| 494 |
+
sample = self.tool(p + '_tool', root, [-0.46, 0.1, 0.88], 'sample tin')
|
| 495 |
+
self.tools[i] = [sample]
|
| 496 |
+
self.extra[i, 'scale'] = (root, v)
|
| 497 |
+
elif (s.get('setup') or {}).get('kind') == 'measure':
|
| 498 |
+
self.box('measurement_strip', [0, 0.21, 1.15], [0.54, 0.03, 0.09], 'cloth', root)
|
| 499 |
+
for x in [-0.26, 0.26]:
|
| 500 |
+
self.box('endpoint_marker', [x, 0.19, 1.15], [0.013, 0.008, 0.13], 'ivory', root)
|
| 501 |
+
self.reg(p + '_setup', self.nodes['measurement_strip'])
|
| 502 |
+
self.setups[i] = self.nodes['measurement_strip']
|
| 503 |
+
tool = self.tool(p + '_tool', root, [-0.46, 0.07, 0.85], 'ruler')
|
| 504 |
+
self.tools[i] = [tool]
|
| 505 |
+
self.extra[i, 'measure'] = root
|
| 506 |
+
elif kind == 'count':
|
| 507 |
+
for j, n in enumerate(v['groups']):
|
| 508 |
+
x = (j - 1) * 0.37
|
| 509 |
+
if v.get('object') == 'spoke':
|
| 510 |
+
for k in range(30):
|
| 511 |
+
a = k * math.pi * 2 / 30
|
| 512 |
+
b = (k + 1) * math.pi * 2 / 30
|
| 513 |
+
self.tube('wheel_rim', [x + 0.13 * math.cos(a), 0.12, 1.18 + 0.13 * math.sin(a)], [x + 0.13 * math.cos(b), 0.12, 1.18 + 0.13 * math.sin(b)], 0.009, 'iron', root)
|
| 514 |
+
for k in range(n):
|
| 515 |
+
a = k * math.pi * 2 / n
|
| 516 |
+
self.tube('wheel_spoke', [x, 0.12, 1.18], [x + 0.12 * math.cos(a), 0.12, 1.18 + 0.12 * math.sin(a)], 0.009, 'steel', root)
|
| 517 |
+
self.cylinder('wheel_hub', [x, 0.12, 1.18], 0.017, 0.02, 'brass', 'y', root)
|
| 518 |
+
self.tube('wheel_mounting_axle', [x, 0.28, 1.18], [x, 0.13, 1.18], 0.015, 'steel', root)
|
| 519 |
+
else:
|
| 520 |
+
self.box('tooth_rack', [x, 0.12, 1.08], [0.28, 0.04, 0.05], 'steel', root)
|
| 521 |
+
for xx in [x - 0.1, x + 0.1]:
|
| 522 |
+
self.tube('rack_mounting_standoff', [xx, 0.28, 1.08], [xx, 0.14, 1.08], 0.015, 'steel', root)
|
| 523 |
+
for k in range(n):
|
| 524 |
+
self.box('individual_tooth', [x + (k - (n - 1) / 2) * 0.28 / n, 0.12, 1.15], [0.18 / n, 0.04, 0.1], 'steel', root)
|
| 525 |
+
elif kind == 'bottle_heights':
|
| 526 |
+
self.box('sample_bottle_tray', [0, 0.05, 0.84625], [0.91, 0.25, 0.0275], 'wood', root)
|
| 527 |
+
for xx in [-0.4, 0.4]:
|
| 528 |
+
self.box('bottle_tray_foot', [xx, 0.05, 0.8125], [0.04, 0.21, 0.04], 'iron', root)
|
| 529 |
+
for h in range(1, 7):
|
| 530 |
+
z = 0.86 + h * 0.075
|
| 531 |
+
self.box('height_reference', [0, 0.22, z], [1.14, 0.008, 0.008], 'ivory', root)
|
| 532 |
+
self.label(p + '_height_mark_' + str(h), h, [-0.57, 0.2, z], 0.06, 0.04, parent=root)
|
| 533 |
+
for j, h in enumerate(v['heights']):
|
| 534 |
+
x = (j - 1) * 0.32
|
| 535 |
+
height = h * 0.075
|
| 536 |
+
self.cylinder('sample_bottle', [x, 0.05, 0.86 + height / 2], 0.059, height, 'sample_blue', 'z', root)
|
| 537 |
+
self.cylinder('bottle_cap', [x, 0.05, 0.86 + height], 0.062, 0.014, 'steel', 'z', root)
|
| 538 |
+
elif (i, 'sample_case') in self.extra:
|
| 539 |
+
if kind == 'clock':
|
| 540 |
+
face = board(v, size=(1200, 660)).crop((225, 90, 705, 570))
|
| 541 |
+
self.cylinder('wall_clock_case', [0, 0.49, 1.79], 0.23, 0.055, 'darkwood', 'y', root, n=48)
|
| 542 |
+
clock_path = self.tex / (p + '_round_clock.png')
|
| 543 |
+
face.save(clock_path)
|
| 544 |
+
clock_mat = self.image_mat(p + '_round_clock_material', clock_path)
|
| 545 |
+
points = [[0, 0.46, 1.79]] + [[0.2175 * math.cos(k * 2 * math.pi / 64), 0.46, 1.79 + 0.2175 * math.sin(k * 2 * math.pi / 64)] for k in range(64)]
|
| 546 |
+
faces = [[0, 1 + k, 1 + (k + 1) % 64] for k in range(64)]
|
| 547 |
+
uv = [(points[j][0] / 0.435 + 0.5, (points[j][2] - 1.79) / 0.435 + 0.5) for f in faces for j in f]
|
| 548 |
+
self.mesh(p + '_round_clock_face', points, faces, clock_mat, root, uv=uv)
|
| 549 |
+
self.label(p + '_clock_period', str(v.get('period', 'AM')) + ' / HHMM', [0.4, 0.46, 1.79], 0.28, 0.09, parent=root)
|
| 550 |
+
else:
|
| 551 |
+
self.show_image(p + '_case_reference', self.rewards[i], [0.57, -0.02, 0.085], 0.98, 0.25, board(v))
|
| 552 |
+
else:
|
| 553 |
+
self.show_image(p + '_evidence', root, [0, 0.27, 1.43], 1.1, 0.38, board(v))
|
| 554 |
+
if (i, 'sample_case') in self.extra:
|
| 555 |
+
n = self.group(p + '_lock', [0.86, -0.035, -0.135], self.rewards[i])
|
| 556 |
+
else:
|
| 557 |
+
n = self.group(p + '_lock', [0.48, -0.04, 0.96], root)
|
| 558 |
+
self.cylinder('lock_mount_post', [0.48, 0.08, 0.86], 0.018, 0.135, 'iron', 'z', root)
|
| 559 |
+
self.tube('lock_mount_arm', [0.48, 0.08, 0.96], [0.48, -0.015, 0.96], 0.017, 'iron', root)
|
| 560 |
+
self.box('numeric_lock_body', [0, 0, 0], [0.31, 0.055, 0.105], 'iron', n)
|
| 561 |
+
self.reg(p + '_lock', n)
|
| 562 |
+
self.lock_nodes[i] = n
|
| 563 |
+
self.extra[i, 'lock_lcd_size'] = (0.27, 0.075)
|
| 564 |
+
self.labels[p + '_lock'] = s.get('name', 'device') + ' code lock'
|
| 565 |
+
|
| 566 |
+
def controls_for(self, i, s, root):
|
| 567 |
+
super().controls_for(i, s, root)
|
| 568 |
+
kind = s['kind']
|
| 569 |
+
p = f's{i + 1}'
|
| 570 |
+
if kind in SEQUENCE or kind in ADJUST:
|
| 571 |
+
if kind == 'sequence' and s.get('visual', {}).get('type') == 'heights':
|
| 572 |
+
pass
|
| 573 |
+
self.box('tabletop_control_console', [0, 0.06, 0.875], [1.04 if kind in SEQUENCE else 0.8, 0.23, 0.165], 'paint', root)
|
| 574 |
+
if kind in BINARY:
|
| 575 |
+
self.box('switch_matrix_housing', [0, 0.12, 1.025], [0.84, 0.4, 0.465], 'paint', root)
|
| 576 |
+
if kind in SEQUENCE:
|
| 577 |
+
for n in self.buffers[i]:
|
| 578 |
+
self.visibility(n, False)
|
| 579 |
+
if s.get('visual', {}).get('type') != 'heights':
|
| 580 |
+
self.box('input_display_bezel', [0, -0.135, 1.06], [0.9, 0.045, 0.15], 'iron', root)
|
| 581 |
+
if s.get('visual', {}).get('type') == 'flash':
|
| 582 |
+
self.box('replay_button_housing', [0, 0.16, 1.18], [0.2, 0.2, 0.17], 'paint', root)
|
| 583 |
+
self.tube('replay_support', [0, 0.25, 1.18], [0, 0.3, 1.18], 0.025, 'iron', root)
|
| 584 |
+
if kind == 'pushbox':
|
| 585 |
+
self.box('parcel_control_box', [0, -0.2, 0.875], [1.04, 0.23, 0.165], 'paint', root)
|
| 586 |
+
|
| 587 |
+
def set_gate_pose(self, i, fraction):
|
| 588 |
+
fraction = max(0.0, min(1.0, float(fraction)))
|
| 589 |
+
left, right = self.extra[i, 'gate_leaves']
|
| 590 |
+
inner_left, inner_right = self.extra[i, 'fold_inner_leaves']
|
| 591 |
+
self.transform(left, rpy=[0, 0, -90 * fraction])
|
| 592 |
+
self.transform(right, rpy=[0, 0, 90 * fraction])
|
| 593 |
+
self.transform(inner_left, rpy=[0, 0, 180 * fraction])
|
| 594 |
+
self.transform(inner_right, rpy=[0, 0, -180 * fraction])
|
| 595 |
+
|
| 596 |
+
def build(self, g):
|
| 597 |
+
self.room_shell('room_A', (0, 0), (4.8, 5.0), openings={'east': [(1.8, 2.95)]})
|
| 598 |
+
self.room_shell('room_B', (4.8, 0), (4.8, 5.0), openings={'west': [(1.8, 2.95)], 'east': [(0.65, 1.72)]})
|
| 599 |
+
self.box('continuous_foundation', [4.8, 2.5, -0.08], [9.76, 5.16, 0.1], 'darkwood')
|
| 600 |
+
for r, x in [('A', 0), ('B', 4.8)]:
|
| 601 |
+
self.label('room_' + r + '_purpose', self.spec['room_names'][0 if r == 'A' else 1], [x + 2.4, 4.922, 2.14], 1.55, 0.17)
|
| 602 |
+
for xx in [x + 0.18, x + 4.62]:
|
| 603 |
+
self.box('skirting', [xx, 2.5, 0.07], [0.045, 4.8, 0.14], 'darkwood')
|
| 604 |
+
counts = {'A': 0, 'B': 0}
|
| 605 |
+
self.stage_views = []
|
| 606 |
+
locations = []
|
| 607 |
+
for i, s in enumerate(self.spec['stages']):
|
| 608 |
+
r = s['room']
|
| 609 |
+
j = counts[r]
|
| 610 |
+
counts[r] += 1
|
| 611 |
+
if j == 0:
|
| 612 |
+
xy = [1.5 if r == 'A' else 6.3, 4.42]
|
| 613 |
+
a = 0
|
| 614 |
+
view = [xy[0], 3.15]
|
| 615 |
+
elif r == 'A':
|
| 616 |
+
xy = [0.62, 2.7]
|
| 617 |
+
a = 90
|
| 618 |
+
view = [1.9, 2.7]
|
| 619 |
+
else:
|
| 620 |
+
xy = [8.98, 3.6]
|
| 621 |
+
a = -90
|
| 622 |
+
view = [7.65, 3.6]
|
| 623 |
+
locations.append((xy, a))
|
| 624 |
+
self.stage_views.append(view)
|
| 625 |
+
for i, (s, (xy, a)) in enumerate(zip(self.spec['stages'], locations)):
|
| 626 |
+
root = self.furniture(i, s, xy, a)
|
| 627 |
+
self.roots.append(root)
|
| 628 |
+
self.bases.append((xy, a))
|
| 629 |
+
p = f's{i + 1}'
|
| 630 |
+
k = s['kind']
|
| 631 |
+
if k in NUMERIC:
|
| 632 |
+
self.numeric(i, s, root)
|
| 633 |
+
elif k in ('bolts', 'balance', 'pushbox'):
|
| 634 |
+
self.special_device(i, s, root)
|
| 635 |
+
else:
|
| 636 |
+
self.controls_for(i, s, root)
|
| 637 |
+
if s.get('visual', {}).get('type') == 'cap_notches':
|
| 638 |
+
for j, side in enumerate(s['visual']['directions']):
|
| 639 |
+
x = (j - 1) * 0.36
|
| 640 |
+
center = {'right': 0, 'up': math.pi / 2, 'left': math.pi, 'down': math.pi * 1.5}[side]
|
| 641 |
+
self.cylinder('cap_inner', [x, 0.09, 1.22], 0.067, 0.025, 'steel', 'y', root, n=28)
|
| 642 |
+
angles = [center + math.radians(22) + k * math.radians(316) / 32 for k in range(33)]
|
| 643 |
+
points = []
|
| 644 |
+
for a in angles:
|
| 645 |
+
points.extend([[x + 0.067 * math.cos(a), 0.075, 1.22 + 0.067 * math.sin(a)], [x + 0.125 * math.cos(a), 0.075, 1.22 + 0.125 * math.sin(a)]])
|
| 646 |
+
self.mesh('notched_metal_cap', points, [[2 * k, 2 * k + 1, 2 * k + 3, 2 * k + 2] for k in range(32)], 'steel', root)
|
| 647 |
+
elif k not in ROTATE | ADJUST and k not in ('float_key',):
|
| 648 |
+
self.show_image(p + '_reference', root, [0, 0.27, 1.22], 1.12, 0.47, board(s.get('visual', {})))
|
| 649 |
+
elif k == 'rotate_picture':
|
| 650 |
+
self.show_image(p + '_complete_reference', root, [0, 0.27, 1.58], 0.8, 0.22, board(s['visual']))
|
| 651 |
+
self.core_card(i, root, self.rewards[i])
|
| 652 |
+
self.stage_centres.append([xy[0], xy[1], 1.12])
|
| 653 |
+
off = self.cylinder(p + '_status_red', [0.6, -0.04, 0.77], 0.022, 0.013, 'red', 'y', root)
|
| 654 |
+
on = self.cylinder(p + '_status_green', [0.6, -0.05, 0.77], 0.022, 0.013, 'green', 'y', root)
|
| 655 |
+
self.status_nodes.append((off, on))
|
| 656 |
+
for i, s in enumerate(self.spec['stages']):
|
| 657 |
+
if s.get('key_gate'):
|
| 658 |
+
source = s['parent']
|
| 659 |
+
key = self.tool('reward_key_' + str(source), self.rewards[source], [0, 0.19, -0.0725], 'key')
|
| 660 |
+
self.transform(key, rpy=[90, 0, 0])
|
| 661 |
+
self.extra[source, 'reward_key'] = key
|
| 662 |
+
if self.spec['id'] == 'R31':
|
| 663 |
+
frame = self.group('light_frame', [8.15, 0.12, 1.2])
|
| 664 |
+
self.transform(frame, rpy=[0, 0, 180])
|
| 665 |
+
self.box('light_frame_housing', [0, 0, 0], [1.08, 0.08, 0.53], 'paint', frame)
|
| 666 |
+
for x in [-0.5, 0.5]:
|
| 667 |
+
self.box('light_frame_wall_bracket', [x, 0.05, 0], [0.04, 0.1, 0.36], 'iron', frame)
|
| 668 |
+
self.reg('light_frame', frame)
|
| 669 |
+
self.extra['light_frame'] = frame
|
| 670 |
+
self.stock('A', 0.65, 0.43)
|
| 671 |
+
self.stock('B', 6.0, 0.43)
|
| 672 |
+
self.exit_node = self.door('exit_leaf', [9.53, 0.68, 0], 1.04)
|
| 673 |
+
self.transform(self.exit_node, rpy=[0, 0, 90])
|
| 674 |
+
self.reg('exit', self.exit_node)
|
| 675 |
+
self.views['exit'] = [8.35, 1.2]
|
| 676 |
+
self.door_view = [8.35, 1.2]
|
| 677 |
+
self.door_lock = self.group('exit_code_lock', [9.46, 1.52, 1.1])
|
| 678 |
+
self.transform(self.door_lock, rpy=[0, 0, 90])
|
| 679 |
+
self.box('exit_lock_body', [0, 0, 0], [0.24, 0.06, 0.18], 'iron', self.door_lock)
|
| 680 |
+
self.reg('exit_lock', self.door_lock)
|
| 681 |
+
for y in [0.64, 1.76]:
|
| 682 |
+
self.box('exit_frame', [9.53, y, 1.15], [0.17, 0.065, 2.3], 'paint')
|
| 683 |
+
self.box('exit_lintel', [9.53, 1.2, 2.3], [0.17, 1.18, 0.065], 'paint')
|
| 684 |
+
self.sync(g)
|
| 685 |
+
from room_decor_quality import populate_room_decor
|
| 686 |
+
populate_room_decor(self, self.spec)
|
| 687 |
+
|
| 688 |
+
def stock(self, room, x, y):
|
| 689 |
+
root = self.group('stock_' + room, [x, y, 0])
|
| 690 |
+
self.box('supply_base', [0, 0, 0.3], [0.95, 0.46, 0.6], 'wood', root)
|
| 691 |
+
self.box('supply_top', [0, 0, 0.62], [1.02, 0.51, 0.055], 'wood', root)
|
| 692 |
+
level = int(self.spec['id'][1:])
|
| 693 |
+
if level in [23, 26, 28, 30, 36, 37, 39, 42]:
|
| 694 |
+
for j in range(3):
|
| 695 |
+
n = self.group('bound_record_' + str(j), [-0.29 + j * 0.27, 0, 0.77], root)
|
| 696 |
+
self.box('book_pages', [0, 0, 0], [0.18, 0.25, 0.22], 'ivory', n)
|
| 697 |
+
for xx in [-0.097, 0.097]:
|
| 698 |
+
self.box('book_cover', [xx, 0, 0], [0.012, 0.28, 0.24], 'sample_blue' if j % 2 else 'paint', n)
|
| 699 |
+
self.box('book_spine', [0, -0.13, 0], [0.2, 0.02, 0.24], 'paint', n)
|
| 700 |
+
elif level in [25, 33]:
|
| 701 |
+
for j in range(3):
|
| 702 |
+
self.cylinder('stored_sample_vessel', [-0.3 + j * 0.29, 0, 0.75], 0.066, 0.22, 'ivory' if level == 25 else 'sample_blue', 'z', root)
|
| 703 |
+
self.cylinder('vessel_lid', [-0.3 + j * 0.29, 0, 0.87], 0.069, 0.018, 'brass', 'z', root)
|
| 704 |
+
elif level == 31:
|
| 705 |
+
for j in range(3):
|
| 706 |
+
self.cylinder('cloth_sample_roll', [-0.29 + j * 0.29, 0, 0.72], 0.08, 0.3, 'cloth' if j % 2 else 'ivory', 'y', root)
|
| 707 |
+
self.cylinder('roll_core', [-0.29 + j * 0.29, -0.154, 0.72], 0.021, 0.016, 'darkwood', 'y', root)
|
| 708 |
+
elif level == 32:
|
| 709 |
+
for j in range(3):
|
| 710 |
+
self.box('mail_sorting_bin', [-0.3 + j * 0.3, 0, 0.73], [0.26, 0.34, 0.19], 'paint', root)
|
| 711 |
+
for k in range(3):
|
| 712 |
+
self.box('sorted_envelope', [-0.3 + j * 0.3, -0.03 + k * 0.07, 0.84], [0.21, 0.05, 0.018], 'ivory', root)
|
| 713 |
+
elif level in [27, 43]:
|
| 714 |
+
self.box('stored_flat_frame', [0, 0, 0.7], [0.76, 0.35, 0.08], 'darkwood', root)
|
| 715 |
+
for j in range(2):
|
| 716 |
+
self.cylinder('rolled_map' if level == 43 else 'mirror_polishing_roll', [-0.2 + j * 0.4, 0, 0.77], 0.035, 0.35, 'ivory' if level == 43 else 'cloth', 'y', root)
|
| 717 |
+
elif level == 34:
|
| 718 |
+
self.box('junction_box', [0, 0.02, 0.77], [0.66, 0.25, 0.25], 'paint', root)
|
| 719 |
+
for j in range(3):
|
| 720 |
+
self.tube('supported_spare_conduit', [-0.23 + j * 0.23, -0.14, 0.68], [-0.23 + j * 0.23, -0.14, 0.86], 0.025, 'rubber', root)
|
| 721 |
+
else:
|
| 722 |
+
self.box('parts_tray_floor', [0, 0, 0.67], [0.82, 0.34, 0.025], 'steel', root)
|
| 723 |
+
for xx in [-0.42, -0.14, 0.14, 0.42]:
|
| 724 |
+
self.box('parts_bin_divider', [xx, 0, 0.72], [0.018, 0.34, 0.12], 'paint', root)
|
| 725 |
+
for yy in [-0.18, 0.18]:
|
| 726 |
+
self.box('parts_bin_rim', [0, yy, 0.72], [0.85, 0.018, 0.12], 'paint', root)
|
| 727 |
+
for j in range(3):
|
| 728 |
+
if level == 38:
|
| 729 |
+
self.box('toy_block', [-0.28 + j * 0.28, 0, 0.74], [0.13, 0.13, 0.13], 'wood' if j % 2 else 'sample_blue', root)
|
| 730 |
+
else:
|
| 731 |
+
self.cylinder('stored_spare_part', [-0.28 + j * 0.28, 0, 0.715], 0.045, 0.065, 'brass' if level in [24, 29, 44] else 'steel', 'z', root)
|
| 732 |
+
self.add_obstacle(x - 0.53, y - 0.27, x + 0.53, y + 0.27)
|
| 733 |
+
|
| 734 |
+
def special_device(self, i, s, root):
|
| 735 |
+
p = f's{i + 1}'
|
| 736 |
+
k = s['kind']
|
| 737 |
+
if k == 'bolts':
|
| 738 |
+
for j in range(4):
|
| 739 |
+
rank = s['order'].index('ABCD'[j])
|
| 740 |
+
x = -0.3 + rank * 0.22
|
| 741 |
+
node = self.group(p + '_control_' + str(j), [x, 0.04, 1.2], root)
|
| 742 |
+
self.box('sliding_bolt', [0, 0, 0], [0.21, 0.085, 0.13], 'steel', node)
|
| 743 |
+
self.box('bolt_grip', [0, -0.07, 0], [0.055, 0.05, 0.12], 'brass', node)
|
| 744 |
+
self.reg(p + '_control_' + str(j), node)
|
| 745 |
+
self.controls[i].append(node)
|
| 746 |
+
self.label(p + '_bolt_mark_' + str(j), 'ABCD'[j], [x, 0.06, 1.4], 0.09, 0.06, parent=root)
|
| 747 |
+
self.box('left_retraction_pocket', [-0.65, 0.075, 1.2], [0.35, 0.1, 0.17], 'iron', root)
|
| 748 |
+
for z in [1.115, 1.285]:
|
| 749 |
+
self.box('bolt_guide_rail', [-0.02, 0.035, z], [1.16, 0.035, 0.022], 'iron', root)
|
| 750 |
+
self.label(p + '_housing_mark', 'SERVICE', [0, 0.06, 0.88], 0.48, 0.07, parent=root)
|
| 751 |
+
elif k == 'pushbox':
|
| 752 |
+
tray = self.group(p + '_board', [0, 0.08, 1.14], root)
|
| 753 |
+
self.transform(tray, rpy=[-35, 0, 0])
|
| 754 |
+
self.box('board_back', [0, 0, 0], [0.82, 0.035, 0.82], 'wood', tray)
|
| 755 |
+
self.box('parcel_board_foot', [0, -0.12, 0.805], [0.86, 0.16, 0.025], 'wood', root)
|
| 756 |
+
self.box('parcel_control_box', [0, -0.2, 0.875], [1.04, 0.23, 0.165], 'paint', root)
|
| 757 |
+
for xx in [-0.4, 0.4]:
|
| 758 |
+
self.box('parcel_console_bracket', [xx, -0.1, 0.785], [0.045, 0.42, 0.012], 'iron', root)
|
| 759 |
+
for r in range(4):
|
| 760 |
+
for c in range(4):
|
| 761 |
+
self.box('board_square', [(c - 1.5) * 0.19, -0.022, (1.5 - r) * 0.19], [0.18, 0.01, 0.18], 'ivory' if (r + c) % 2 else 'sample_blue', tray)
|
| 762 |
+
target = self.box('box_goal', [(3 - 2.5) * 0.19, -0.033, (2.5 - 3) * 0.19], [0.16, 0.008, 0.16], 'green', tray)
|
| 763 |
+
player = self.group(p + '_player', parent=tray)
|
| 764 |
+
self.cylinder('player_pawn', [0, 0, 0], 0.035, 0.075, 'brass', 'y', player)
|
| 765 |
+
box = self.group(p + '_box', parent=tray)
|
| 766 |
+
self.box('wooden_box', [0, 0, 0], [0.14, 0.09, 0.14], 'wood', box)
|
| 767 |
+
self.extra[i, 'pushbox'] = (player, box)
|
| 768 |
+
for j, icon in enumerate(['up', 'right', 'down', 'left']):
|
| 769 |
+
self.button(p + '_choice_' + str(j), root, [-0.36 + j * 0.24, -0.19, 0.72], icon, 0.13)
|
| 770 |
+
self.button(p + '_reset', root, [0.57, -0.15, 0.72], 'cross', 0.11)
|
| 771 |
+
else:
|
| 772 |
+
self.cylinder('balance_column', [0, 0.07, 1.03], 0.035, 0.44, 'brass', 'z', root)
|
| 773 |
+
beam = self.group(p + '_balance_beam', [0, 0.07, 1.24], root)
|
| 774 |
+
self.box('balance_beam', [0, 0, 0], [0.92, 0.045, 0.045], 'steel', beam)
|
| 775 |
+
for x in [-0.38, 0.38]:
|
| 776 |
+
self.tube('balance_hanger', [x, 0, 0], [x, 0, -0.17], 0.008, 'brass', beam)
|
| 777 |
+
fixed = self.cylinder('fixed_six_weight', [-0.38, 0.07, 1.05], 0.075, 0.1, 'steel', 'z', root)
|
| 778 |
+
self.label(p + '_fixed_mass', '6', [-0.38, -0.012, 1.05], 0.1, 0.07, parent=root)
|
| 779 |
+
pan = self.group(p + '_pan', [0.38, 0.07, 1.05], root)
|
| 780 |
+
self.cylinder('balance_pan', [0, 0, 0], 0.13, 0.018, 'steel', 'z', pan)
|
| 781 |
+
self.reg(p + '_pan', pan)
|
| 782 |
+
self.extra[i, 'balance'] = (beam, pan, [])
|
| 783 |
+
for j, n in enumerate(s['weights']):
|
| 784 |
+
node = self.group(p + '_weight_' + str(j), [-0.45 + j * 0.22, -0.15, 0.83], root)
|
| 785 |
+
self.cylinder('weight', [0, 0, 0], 0.045, 0.075, 'iron', 'z', node)
|
| 786 |
+
self.label(p + '_weight_label_' + str(j), n, [0, -0.048, 0], 0.065, 0.052, parent=node)
|
| 787 |
+
self.reg(p + '_weight_' + str(j), node)
|
| 788 |
+
self.extra[i, 'balance'][2].append(node)
|
| 789 |
+
|
| 790 |
+
def sync(self, g):
|
| 791 |
+
for i, s in enumerate(self.spec['stages']):
|
| 792 |
+
root = self.roots[i]
|
| 793 |
+
v = g.states[i]
|
| 794 |
+
p = f's{i + 1}'
|
| 795 |
+
open_ = g.opened[p + '_cover']
|
| 796 |
+
gate = self.gates[i]
|
| 797 |
+
if gate:
|
| 798 |
+
self.set_gate_pose(i, 1 if open_ else 0)
|
| 799 |
+
drawer = self.rewards[i]
|
| 800 |
+
if (i, 'sample_case') in self.extra:
|
| 801 |
+
self.transform(drawer, rpy=[0, 0, -115 if g.reward_open[i] else 0])
|
| 802 |
+
else:
|
| 803 |
+
self.transform(drawer, [0, -0.62 if g.reward_open[i] else -0.02, 0.57])
|
| 804 |
+
if self.core_cards[i]:
|
| 805 |
+
self.visibility(self.core_cards[i], g.reward_open[i] and 'clue_' + s['room'] not in g.taken)
|
| 806 |
+
if (i, 'locator_mask') in self.extra:
|
| 807 |
+
self.visibility(self.extra[i, 'locator_mask'], bool(g.possessions.get('mask_installed')))
|
| 808 |
+
off, on = self.status_nodes[i]
|
| 809 |
+
self.visibility(off, not g.solved[i])
|
| 810 |
+
self.visibility(on, g.solved[i])
|
| 811 |
+
if (i, 'reward_key') in self.extra:
|
| 812 |
+
self.visibility(self.extra[i, 'reward_key'], g.reward_open[i] and 'reward_key_' + str(i) not in g.taken)
|
| 813 |
+
if s['kind'] in ROTATE:
|
| 814 |
+
for j, node in enumerate(self.controls[i]):
|
| 815 |
+
self.transform(node, rpy=[0, v['angles'][j] * 90, 0])
|
| 816 |
+
elif s['kind'] in ADJUST:
|
| 817 |
+
kind, visual, nodes = self.extra[i, 'adjust_nodes']
|
| 818 |
+
for j, node in enumerate(nodes):
|
| 819 |
+
value = v['angles'][j]
|
| 820 |
+
err = value - s['target'][j]
|
| 821 |
+
if kind == 'block_faces':
|
| 822 |
+
self.transform(node, rpy=[(0, 0, 0), (0, 0, -90), (0, 0, 180), (0, 0, 90), (90, 0, 0), (-90, 0, 0)][value])
|
| 823 |
+
elif visual == 'pattern_rings':
|
| 824 |
+
self.transform(node, rpy=[0, value * 90, 0])
|
| 825 |
+
elif kind == 'window_align':
|
| 826 |
+
self.transform(node, [err * 0.105, -0.04 - j * 0.055, 1.15])
|
| 827 |
+
elif kind == 'support_align':
|
| 828 |
+
self.transform(node, [(j - 0.5) * 0.62, -0.08, 0.9 + err * 0.045])
|
| 829 |
+
else:
|
| 830 |
+
self.transform(node, [(j - 0.5) * 0.48, -0.02, 1.04 + value * 0.1])
|
| 831 |
+
if kind == 'support_align':
|
| 832 |
+
a, b = [x - y for x, y in zip(v['angles'], s['target'])]
|
| 833 |
+
self.transform(self.extra[i, 'support_frame'], [0, -0.08, 1.04 + (a + b) * 0.0225], rpy=[0, math.degrees(math.atan2((a - b) * 0.045, 0.62)), 0])
|
| 834 |
+
elif s['kind'] in BINARY:
|
| 835 |
+
for j, node in enumerate(self.controls[i]):
|
| 836 |
+
sig = v['selected'][j]
|
| 837 |
+
im = Image.new('RGB', (160, 160), (35, 42, 42) if sig else (235, 231, 215))
|
| 838 |
+
self.screen(p + '_binary_' + str(j), node, [0, -0.049, 0], 0.15, 0.15, im, sig)
|
| 839 |
+
elif s['kind'] == 'sliding_puzzle':
|
| 840 |
+
nodes, spacing, rows, cols = self.special[i, 'sliding']
|
| 841 |
+
for value, node in nodes.items():
|
| 842 |
+
j = v['grid'].index(value)
|
| 843 |
+
r, c = divmod(j, cols)
|
| 844 |
+
self.transform(node, [(c - (cols - 1) / 2) * spacing, -0.2, 1.25 - r * spacing])
|
| 845 |
+
elif s['kind'] == 'bolts':
|
| 846 |
+
for j, node in enumerate(self.controls[i]):
|
| 847 |
+
self.transform(node, [-0.3 + s['order'].index('ABCD'[j]) * 0.22 - (0.22 if v['selected'][j] else 0), 0.04, 1.2])
|
| 848 |
+
elif s['kind'] == 'pushbox':
|
| 849 |
+
for name, node in zip(['player', 'box'], self.extra[i, 'pushbox']):
|
| 850 |
+
r, c = v[name]
|
| 851 |
+
self.transform(node, [(c - 2.5) * 0.19, -0.08, (2.5 - r) * 0.19])
|
| 852 |
+
elif s['kind'] == 'balance':
|
| 853 |
+
beam, pan, nodes = self.extra[i, 'balance']
|
| 854 |
+
mass = sum((s['weights'][j] for j in v['weights']))
|
| 855 |
+
self.transform(beam, rpy=[0, (mass - 6) * 3, 0])
|
| 856 |
+
for j, node in enumerate(nodes):
|
| 857 |
+
self.visibility(node, f'{p}_weight_{j}' not in g.holding)
|
| 858 |
+
self.transform(node, [0.33 + j % 2 * 0.09, 0.07 + j // 2 * 0.06, 1.1] if j in v['weights'] else [-0.45 + j * 0.22, -0.15, 0.83])
|
| 859 |
+
elif s['kind'] == 'float_key':
|
| 860 |
+
if (i, 'float_water') in self.special:
|
| 861 |
+
self.transform(self.special[i, 'float_water'], [0, -0.27, 1.01 if v['floated'] else 0.61])
|
| 862 |
+
key = self.special[i, 'float_key']
|
| 863 |
+
self.transform(key, [0, -0.27, 1.13 if v['floated'] else 0.64])
|
| 864 |
+
self.visibility(key, p + '_float_key' not in g.taken)
|
| 865 |
+
if s['kind'] == 'assign':
|
| 866 |
+
assignments = {int(k): int(j) for k, j in v['assignment'].items()}
|
| 867 |
+
for j, node in enumerate(self.items[i]):
|
| 868 |
+
key = p + '_item_' + str(j)
|
| 869 |
+
self.visibility(node, key not in g.holding and (s.get('item_source') is None or g.reward_open[s['item_source']]))
|
| 870 |
+
slot = next((k for k, z in assignments.items() if z == j), None)
|
| 871 |
+
if slot is not None:
|
| 872 |
+
target_node = self.slots[i][slot]
|
| 873 |
+
T = self.G.XformCache().GetLocalToWorldTransform(target_node['prim'])
|
| 874 |
+
world = T.Transform(self.F.Vec3d(0, -0.025, 0)) if s.get('visual', {}).get('type') != 'wire_trace' else T.ExtractTranslation()
|
| 875 |
+
P = self.G.XformCache().GetLocalToWorldTransform(node['prim'].GetParent()).GetInverse()
|
| 876 |
+
local = P.Transform(world)
|
| 877 |
+
angle = 0.0 if s.get('item_source') is None else self.bases[i][1] - self.bases[s['item_source']][1]
|
| 878 |
+
self.transform(node, list(local), rpy=[0, 0, angle])
|
| 879 |
+
elif s.get('item_source') is not None:
|
| 880 |
+
self.transform(node, [0.32, 0.03 + j * 0.095, 0.09], rpy=[0, 0, 0])
|
| 881 |
+
else:
|
| 882 |
+
rack = s.get('rack_order', list(range(len(s['items']))))
|
| 883 |
+
self.transform(node, [(rack.index(j) - (len(s['items']) - 1) / 2) * 0.24, -0.015, 0.87])
|
| 884 |
+
if i in self.lock_nodes:
|
| 885 |
+
val = g.possessions.get(p + '_lock', '_' * s.get('digits', 3))
|
| 886 |
+
w, h = self.extra.get((i, 'lock_lcd_size'), (0.27, 0.075))
|
| 887 |
+
self.screen(p + '_lcd', self.lock_nodes[i], [0, -0.032, 0], w, h, self.small_text(val), val)
|
| 888 |
+
if s['kind'] in SEQUENCE:
|
| 889 |
+
buf = tuple(v['buffer'])
|
| 890 |
+
im = Image.new('RGB', (1000, 160), (40, 52, 49))
|
| 891 |
+
dr = ImageDraw.Draw(im)
|
| 892 |
+
for j, x in enumerate(buf):
|
| 893 |
+
symbol(dr, s['options'][x], (25 + j * 210, 15, 190 + j * 210, 145))
|
| 894 |
+
self.screen(p + '_buffer', root, [0, -0.16, 1.06], 0.85, 0.135, im, (buf, v['overflow']))
|
| 895 |
+
for j, node in enumerate(self.tools[i]):
|
| 896 |
+
key = p + '_tool'
|
| 897 |
+
on = key not in g.taken
|
| 898 |
+
source = s.get('tool_source')
|
| 899 |
+
self.visibility(node, on and (source is None or g.reward_open[source]))
|
| 900 |
+
if (i, 'scale') in self.extra:
|
| 901 |
+
reading = s['visual']['reading'] if v['setup_used'] else s['visual'].get('tare', 0)
|
| 902 |
+
self.screen(p + '_scale_lcd', root, [0, -0.184, 0.85], 0.33, 0.069, self.small_text(str(reading) + ' g'), reading)
|
| 903 |
+
sample = self.tools[i][0]
|
| 904 |
+
if v['setup_used']:
|
| 905 |
+
self.visibility(sample, True)
|
| 906 |
+
self.transform(sample, [0, 0.09, 1.15])
|
| 907 |
+
if (i, 'measure') in self.extra:
|
| 908 |
+
im = board(s['visual']) if v['setup_used'] else Image.new('RGB', (1200, 720), PAPER)
|
| 909 |
+
self.screen(p + '_measuring_face', root, [0, 0.184, 1.19], 0.9, 0.3, im, v['setup_used'])
|
| 910 |
+
self.transform(self.exit_node, rpy=[0, 0, 90 + (100 if g.opened['exit'] else 0)])
|
| 911 |
+
self.screen('exit_lcd', self.door_lock, [0, -0.034, 0], 0.205, 0.11, self.small_text(g.possessions.get('door_input', '____')), g.possessions.get('door_input', ''))
|
| 912 |
+
if 'light_frame' in self.extra:
|
| 913 |
+
flags = (bool(g.possessions.get('installed_A')), bool(g.possessions.get('installed_B')))
|
| 914 |
+
values = []
|
| 915 |
+
for j in range(4):
|
| 916 |
+
parts = set()
|
| 917 |
+
if flags[0]:
|
| 918 |
+
parts.update(self.spec['clues']['A']['values'][j])
|
| 919 |
+
if flags[1]:
|
| 920 |
+
parts.update(self.spec['clues']['B']['values'][j])
|
| 921 |
+
values.append(''.join(sorted(parts)))
|
| 922 |
+
self.screen('film_overlay', self.extra['light_frame'], [0, -0.045, 0], 0.98, 0.43, board({'type': 'segments', 'values': values}), flags)
|
| 923 |
+
self.centres = {}
|
| 924 |
+
for key, node in self.target_nodes.items():
|
| 925 |
+
pts = self.triangles(node).reshape(-1, 3)
|
| 926 |
+
if pts.size:
|
| 927 |
+
self.centres[key] = ((pts.min(0) + pts.max(0)) / 2).tolist()
|
| 928 |
+
|
| 929 |
+
def visible(self, key, g):
|
| 930 |
+
if key.startswith('clue_'):
|
| 931 |
+
return g.reward_open[self.spec['last'][key[-1]]] and key not in g.taken
|
| 932 |
+
if key.startswith('reward_key_'):
|
| 933 |
+
return g.reward_open[int(key[-1])] and key not in g.taken
|
| 934 |
+
if key.startswith('reward_'):
|
| 935 |
+
return True
|
| 936 |
+
if key in ('exit', 'exit_lock', 'light_frame'):
|
| 937 |
+
return True
|
| 938 |
+
if key.startswith('s') and key[1:2].isdigit():
|
| 939 |
+
i = int(key[1]) - 1
|
| 940 |
+
s = self.spec['stages'][i]
|
| 941 |
+
if key.endswith('_cover'):
|
| 942 |
+
return self.gates[i] is not None
|
| 943 |
+
if not g.stage_accessible(i):
|
| 944 |
+
return False
|
| 945 |
+
if '_item_' in key and s.get('item_source') is not None and (not g.reward_open[s['item_source']]):
|
| 946 |
+
return False
|
| 947 |
+
if '_item_' in key and s['kind'] == 'assign':
|
| 948 |
+
return key not in g.holding
|
| 949 |
+
if key.endswith('_tool') and s.get('tool_source') is not None and (not g.reward_open[s['tool_source']]):
|
| 950 |
+
return False
|
| 951 |
+
return key not in g.holding and (key not in g.taken or key.endswith('_setup'))
|
| 952 |
+
return False
|
| 953 |
+
|
| 954 |
+
def candidates(self, g):
|
| 955 |
+
return self.base_candidates([k for k in self.target_nodes if self.visible(k, g)])
|
| 956 |
+
|
| 957 |
+
def blocked(self, x, y, g):
|
| 958 |
+
if self.static_blocked(x, y) or not (0.16 < x < 9.44 and 0.16 < y < 4.84):
|
| 959 |
+
return True
|
| 960 |
+
cache = getattr(self, '_dynamic_collision_cache', None)
|
| 961 |
+
if cache is None:
|
| 962 |
+
cache = {}
|
| 963 |
+
for i in range(3):
|
| 964 |
+
moving = [('reward', self.extra[i, 'reward_collision'])] + [('gate', leaf) for leaf in self.extra.get((i, 'gate_leaves'), [])]
|
| 965 |
+
for j, (kind, node) in enumerate(moving):
|
| 966 |
+
pts = self.triangles(node).reshape(-1, 3)
|
| 967 |
+
cache[i, j] = (kind, pts.min(0), pts.max(0))
|
| 968 |
+
self._dynamic_collision_cache = cache
|
| 969 |
+
for (i, j), (kind, lo, hi) in cache.items():
|
| 970 |
+
active = g.reward_open[i] if kind == 'reward' else g.opened[f's{i + 1}_cover']
|
| 971 |
+
if active and lo[0] - 0.11 < x < hi[0] + 0.11 and (lo[1] - 0.11 < y < hi[1] + 0.11):
|
| 972 |
+
return True
|
| 973 |
+
return False
|
| 974 |
+
|
| 975 |
+
def view_for(self, key):
|
| 976 |
+
return self.views.get(key, self.stage_views[0])
|
| 977 |
+
|
| 978 |
+
def focus_for(self, key):
|
| 979 |
+
return self.centres.get(key)
|
| 980 |
+
|
| 981 |
+
def label_for(self, key):
|
| 982 |
+
return self.labels.get(key, key.replace('_', ' '))
|
| 983 |
+
|
| 984 |
+
def animate(self, d, before):
|
| 985 |
+
self.sync(d.game)
|
| 986 |
+
for i, s in enumerate(self.spec['stages']):
|
| 987 |
+
if d.game.states[i]['playback'] != before['states'][i]['playback']:
|
| 988 |
+
for index, icon in enumerate(s['visual'].get('sequence', [])):
|
| 989 |
+
im = board({'type': 'symbol_strip', 'symbols': [icon]})
|
| 990 |
+
self.screen('playback_' + str(i), self.roots[i], [0, 0.24, 1.43], 0.65, 0.3, im, index)
|
| 991 |
+
d.frame(warm=8)
|
| 992 |
+
d.capture_feedback_frame()
|
| 993 |
+
d.append('', 10)
|
| 994 |
+
if 'playback_' + str(i) in self.images:
|
| 995 |
+
self.visibility(self.images['playback_' + str(i)], False)
|
| 996 |
+
self.sync(d.game)
|
runtime/h2_runtime/medium88_specs.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
SYMS = ['circle', 'star', 'square', 'leaf']
|
| 3 |
+
KEYS = ['circle', 'triangle', 'square', 'star', 'leaf', 'cross']
|
| 4 |
+
|
| 5 |
+
def st(kind, room, tag, **kw):
|
| 6 |
+
return dict(kind=kind, room=room, tag=tag, name=kw.pop('name', tag + ' device'), clue_text='', **kw)
|
| 7 |
+
|
| 8 |
+
def num(room, tag, code, visual, **kw):
|
| 9 |
+
return st('read_code', room, tag, answer=code, digits=len(code), visual=visual, **kw)
|
| 10 |
+
|
| 11 |
+
def seq(room, tag, values, options=KEYS, flash=False, **kw):
|
| 12 |
+
v = {'type': 'flash', 'sequence': values} if flash else {'type': 'symbol_strip', 'symbols': values}
|
| 13 |
+
return st('sequence', room, tag, options=options, answer=[options.index(x) for x in values], length=len(values), visual=v, **kw)
|
| 14 |
+
|
| 15 |
+
def rot(room, tag, initial):
|
| 16 |
+
return st('rotate_picture', room, tag, initial=initial, target=[0, 0, 0], auto=True, visual={'type': 'fabric'})
|
| 17 |
+
|
| 18 |
+
def dual(room, tag, initial, target, kind='window_align', moduli=(4, 4)):
|
| 19 |
+
return st(kind, room, tag, initial=list(initial), target=[x - 1 for x in target], moduli=list(moduli), auto=False, visual={'type': 'block_faces', 'reference': ['star', 'cross']} if kind == 'block_faces' else {'type': 'window_align', 'reference': [x - 1 for x in target]})
|
| 20 |
+
|
| 21 |
+
def difference(room, tag, target):
|
| 22 |
+
a = ['circle', 'star', 'leaf', 'square', 'triangle', 'cross']
|
| 23 |
+
b = a[:]
|
| 24 |
+
for i in target:
|
| 25 |
+
b[i - 1] = KEYS[(KEYS.index(a[i - 1]) + 1) % 6]
|
| 26 |
+
return st('difference', room, tag, initial=[0] * 6, target=[int(i + 1 in target) for i in range(6)], rows=2, cols=3, visual={'type': 'stamp_compare', 'left': a, 'right': b})
|
| 27 |
+
|
| 28 |
+
def pair(room, tag, targets):
|
| 29 |
+
return st('assign', room, tag, items=[{'id': x, 'name': 'gauge ' + x, 'symbol': x} for x in 'ABCD'], slots=2, target=['ABCD'.index(x) for x in targets], auto=False, visual={'type': 'gauge_pairs', 'reference': list(targets)})
|
| 30 |
+
|
| 31 |
+
def wire(room, tag, ports):
|
| 32 |
+
target = [None] * 4
|
| 33 |
+
for i, p in enumerate(ports):
|
| 34 |
+
target[p - 1] = i
|
| 35 |
+
return st('assign', room, tag, items=[{'id': x, 'name': x + ' connector', 'symbol': x} for x in SYMS[:3]], slots=4, target=target, auto=False, visual={'type': 'wire_trace', 'mapping': ports})
|
| 36 |
+
|
| 37 |
+
def bolts(room, tag, order):
|
| 38 |
+
return st('bolts', room, tag, initial=[0] * 4, target=[1] * 4, order=list(order), visual={'type': 'bolt_chain', 'order': list(order)})
|
| 39 |
+
|
| 40 |
+
def measure(room, tag, code, value, source=None):
|
| 41 |
+
return num(room, tag, code, {'type': 'ruler', 'reading': value, 'unit': 'mm'}, setup={'kind': 'measure', 'item': 'ruler', 'item_name': 'measuring ruler', 'target_name': 'measurement strip', 'consume': False}, tool_source=source)
|
| 42 |
+
|
| 43 |
+
def lamp(room, tag, values):
|
| 44 |
+
return seq(room, tag, values, flash=True)
|
| 45 |
+
|
| 46 |
+
def order(room, tag, values, indices, style='book_order'):
|
| 47 |
+
return seq(room, tag, [str(x) for x in indices], options=['1', '2', '3', '4'], visual_override={'type': style, 'numbers': values})
|
| 48 |
+
|
| 49 |
+
def pipes(room, tag, initial, mirror=False):
|
| 50 |
+
cells = [[0, 1], [0, 0], [1, 0]] if mirror else [[0, 0], [0, 1], [1, 1]]
|
| 51 |
+
target = [0, 1, 3] if mirror else [0, 2, 0]
|
| 52 |
+
return st('rotate_pipes', room, tag, grid=[2, 2], cells=cells, ports=[[1, 3], [0, 1], [0, 1]], initial=initial, target=target, inlet=cells[0] + [1 if mirror else 3], outlet=cells[-1] + [3 if mirror else 1], auto=True, moduli=[2, 4, 4], visual={'type': 'pipes'})
|
| 53 |
+
|
| 54 |
+
def binary(room, tag, target):
|
| 55 |
+
return st('binary_pattern', room, tag, initial=[0] * 4, target=target, rows=2, cols=2, visual={'type': 'binary_swatch', 'cells': target})
|
| 56 |
+
|
| 57 |
+
def weighing(room, tag, code, reading, tare=0):
|
| 58 |
+
return num(room, tag, code, {'type': 'scale', 'reading': reading, 'tare': tare, 'unit': 'g'}, setup={'kind': 'weigh', 'item': 'sample', 'item_name': 'sample tin', 'target_name': 'scale tray', 'consume': True})
|
| 59 |
+
|
| 60 |
+
def lines(*rows, title=''):
|
| 61 |
+
return {'type': 'table', 'rows': list(rows), 'title': title}
|
| 62 |
+
|
| 63 |
+
def grid(rows, **kw):
|
| 64 |
+
return {'type': 'number_grid', 'rows': rows, **kw}
|
| 65 |
+
|
| 66 |
+
def vector(values, **kw):
|
| 67 |
+
return {'type': 'symbol_values', 'symbols': SYMS, 'values': values, **kw}
|
| 68 |
+
LEVELS = {}
|
| 69 |
+
|
| 70 |
+
def add(i, title, rooms, stages, A, B, code):
|
| 71 |
+
for j, s in enumerate(stages):
|
| 72 |
+
if 'visual_override' in s:
|
| 73 |
+
s['visual'] = s.pop('visual_override')
|
| 74 |
+
s['index'] = j
|
| 75 |
+
s['parent'] = None
|
| 76 |
+
for k in range(j - 1, -1, -1):
|
| 77 |
+
if stages[k]['room'] == s['room']:
|
| 78 |
+
s['parent'] = k
|
| 79 |
+
break
|
| 80 |
+
if s['kind'] in ('adjust', 'window_align', 'support_align', 'block_faces'):
|
| 81 |
+
s['initial'] = [x - 1 for x in s['initial']]
|
| 82 |
+
s['name'] = {'bolts': 'inspection bolts', 'rotate_pipes': 'pipe manifold', 'rotate_picture': 'pattern restoration frame', 'assign': 'component fixture', 'sequence': 'signal unit', 'binary_pattern': 'sample pattern keys', 'difference': 'comparison tray', 'support_align': 'frame support', 'window_align': 'inspection windows', 'block_faces': 'reference columns', 'float_key': 'water cylinder', 'balance': 'sample balance', 'pushbox': 'parcel puzzle', 'sliding_puzzle': 'archive sliding tray', 'read_code': 'record cabinet', 'adjust': 'pattern dial'}[s['kind']]
|
| 83 |
+
last = {r: max((j for j, s in enumerate(stages) if s['room'] == r)) for r in ['A', 'B']}
|
| 84 |
+
LEVELS[f'R{i}'] = {'id': f'R{i}', 'title': title, 'room_names': rooms, 'size': [9.6, 5.0], 'room_size': [4.8, 5.0], 'start': [2.4, 2.15, 1.35], 'start_yaw': 90, 'room_views': {'A': [2.4, 2.15, 1.35], 'B': [7.2, 2.15, 1.35]}, 'stages': stages, 'last': last, 'clues': {'A': A, 'B': B}, 'door_code': code, 'door': {'side': 'east', 'start': 0.65, 'width': 1.04}, 'theme': title.lower().split()[0]}
|
| 85 |
+
route = st('rotate_pipes', 'A', 'A2', grid=[4, 3], cells=[[2, 0], [2, 2], [1, 2]], ports=[[0, 1]] * 3, initial=[0, 0, 0], target=[1, 3, 2], auto=True, route_special=True, visual={'type': 'pipes'})
|
| 86 |
+
add(23, 'Service passage', ['Registration room', 'Number room'], [bolts('A', 'A1', 'BDAC'), route, wire('B', 'B1', [3, 1, 4])], {'type': 'route', 'rows': 4, 'cols': 3, 'path': [[3, 0], [2, 0], [2, 1], [2, 2], [1, 2], [1, 1], [0, 1]], 'title': 'S > T / CORNERS'}, grid([[7, 4, 0], [9, 6, 2], [5, 1, 8], [3, 0, 4]]), '5826')
|
| 87 |
+
LEVELS['R23']['stages'][2]['item_source'] = 1
|
| 88 |
+
add(24, 'Gauge workshop', ['Gauge room', 'Spare-parts room'], [pair('A', 'A1', 'BD'), rot('A', 'A2', [1, 2, 3]), num('B', 'B1', '352', {'type': 'count', 'groups': [3, 5, 2], 'object': 'tooth'})], {'type': 'hole_mask', 'rows': 3, 'cols': 4, 'points': [[0, 2], [2, 0], [1, 3], [2, 3]]}, grid([[4, 8, 1, 6], [7, 2, 9, 3], [5, 0, 6, 4]]), '1534')
|
| 89 |
+
add(25, 'Tea samples', ['Tea-sample room', 'Cup store'], [dual('A', 'A1', [4, 4], [3, 2], kind='support_align'), weighing('B', 'B1', '0250', 270, 20), num('B', 'B2', '425', {'type': 'bottle_heights', 'heights': [4, 2, 5], 'levels': 6})], {'type': 'symbol_strip', 'symbols': ['round_lid', 'tall_cup', 'square_can', 'handled_cup'], 'title': 'ROOT > TIP'}, lines(['round_lid', 7], ['tall_cup', 2], ['square_can', 9], ['handled_cup', 4]), '7294')
|
| 90 |
+
add(26, 'Archive index', ['Archive room', 'Reading room'], [st('sliding_puzzle', 'A', 'A1', grid=[2, 3], initial=['D', 'A', 'C', 'B', '', 'E'], target=['A', 'B', 'C', 'D', 'E', ''], auto=True, visual={'type': 'cargo_puzzle'}), dual('A', 'A2', [4, 2], [2, 3]), difference('B', 'B1', [1, 4, 6])], lines(['deer', 'sun'], ['fish', 'moon'], ['bird', 'sun'], ['deer', 'moon']), grid([[4, 7, 2], [8, 1, 6], [5, 0, 3]], row_labels=['deer', 'fish', 'bird'], col_labels=['sun', 'moon', 'star']), '4157')
|
| 91 |
+
add(27, 'Mirror repair', ['Mirror-frame room', 'Display room'], [num('A', 'A1', '425', {'type': 'trace', 'mapping': [4, 2, 5]}), st('float_key', 'B', 'B1', visual={'type': 'float_key'}), dual('B', 'B2', [3, 4], [1, 3], kind='support_align')], {'type': 'hole_mask', 'rows': 2, 'cols': 4, 'points': [[0, 0], [1, 2], [0, 3], [1, 0]]}, grid([[3, 8, 1, 6], [7, 4, 9, 2]], mirror=True), '3967')
|
| 92 |
+
chain = lambda room, tag: st('assign', room, tag, items=[{'id': str(j), 'name': 'binding strip ' + str(j + 1), 'symbol': x + '>' + y} for j, (x, y) in enumerate([('circle', 'leaf'), ('square', 'star'), ('leaf', 'square'), ('star', 'flag')])], slots=4, target=[0, 2, 1, 3], auto=False, visual={'type': 'chain', 'ends': [['circle', 'leaf'], ['square', 'star'], ['leaf', 'square'], ['star', 'flag']]})
|
| 93 |
+
add(28, 'Bookbinding', ['Binding room', 'Card store'], [wire('A', 'A1', [2, 4, 1]), lamp('A', 'A2', ['circle', 'leaf', 'square']), chain('B', 'B1')], lines(['START', 'triangle'], ['NEXT', 1], ['NEXT', 2], ['PREVIOUS', 1], ['NEXT', 3], title='PAGE TURNS / READ EACH STOP'), lines(['triangle', 7], [2, 6], [3, 8], [4, 4], [5, 9], [6, 1], title='PAGES 1 > 6'), '6481')
|
| 94 |
+
add(29, 'Instrument calibration', ['Calibration room', 'Instrument room'], [measure('A', 'A1', '0140', 140), num('B', 'B1', '253', {'type': 'dials', 'values': [2, 5, 3]}), dual('B', 'B2', [1, 3], [4, 5], kind='block_faces', moduli=(6, 6))], vector([2, 1, 3, 2], title='READING - PAD'), vector([7, 5, 9, 3]), '5461')
|
| 95 |
+
add(30, 'Dated records', ['Maintenance registry', 'Record store'], [bolts('A', 'A1', 'ACDB'), binary('A', 'A2', [0, 1, 1, 0]), st('assign', 'B', 'B1', items=[{'id': n, 'name': n + ' cover card', 'symbol': n} for n in ['building', 'tree', 'car']], slots=4, target=[0, 1, None, 2], visual={'type': 'classes', 'classes': ['building', 'plant', 'animal', 'transport']})], vector(['WED', 'MON', 'TUE', 'THU']), grid([[4, 9, 2, 5], [7, 1, 6, 3], [8, 4, 9, 0], [6, 5, 1, 8]], row_labels=SYMS, col_labels=['MON', 'TUE', 'WED', 'THU']), '2748')
|
| 96 |
+
add(31, 'Split numerals', ['Textile sample room', 'Light room'], [order('A', 'A1', [3, 1, 4, 2], [2, 4, 1, 3], style='heights'), pipes('B', 'B1', [1, 0, 1]), measure('B', 'B2', '0230', 230, source=1)], {'type': 'segments', 'values': ['abfg', 'afg', 'abg', 'abg']}, {'type': 'segments', 'values': ['cde', 'cde', 'cd', 'de']}, '8632')
|
| 97 |
+
add(32, 'Postal wheel', ['Mail-sorting room', 'Wheel store'], [st('balance', 'A', 'A1', weights=[1, 2, 4, 8], target_mass=6, visual={'type': 'balance'}), lamp('A', 'A2', ['cross', 'leaf', 'cross', 'circle']), st('pushbox', 'B', 'B1', initial_player=[2, 1], initial_box=[2, 2], goal=[3, 3], grid=[4, 4], visual={'type': 'pushbox'})], {'type': 'ring', 'marks': [0, 2, 5, 9]}, {'type': 'ring', 'numbers': [1, 4, 9, 2, 7, 6, 0, 3, 8, 5, 2, 4], 'triangle': 2}, '9734')
|
| 98 |
+
add(33, 'Filling samples', ['Sample room', 'Measurement room'], [rot('A', 'A1', [2, 1, 3]), seq('B', 'B1', ['left', 'up', 'right'], options=['up', 'right', 'down', 'left']), dual('B', 'B2', [2, 1], [3, 4])], vector([1, 3, 2, 4], title='BEFORE / INCREASE'), vector([8, 5, 9, 6], title='AFTER'), '7272')
|
| 99 |
+
add(34, 'State selectors', ['Power room', 'Indicator room'], [difference('A', 'A1', [2, 3, 5]), seq('A', 'A2', ['2', '3'], options=['1', '2', '3', '4'], distinct=True, visual_override={'type': 'locations', 'points': ['red left ring', 'red right ring', 'blue upper clip', 'blue lower clip'], 'selected': [2, 3]}), order('B', 'B1', [40, 10, 30, 20], [2, 4, 3, 1])], vector(['ON', 'OFF', 'OFF', 'ON']), grid([[6, 1, 8, 4], [3, 7, 2, 9]], row_labels=['ON', 'OFF'], col_labels=SYMS), '6724')
|
| 100 |
+
add(35, 'Shared solid cells', ['Screening room', 'Review room'], [bolts('A', 'A1', 'DBAC'), wire('B', 'B1', [1, 4, 2]), measure('B', 'B2', '0220', 220, source=1)], {'type': 'solid', 'solid': [1, 3, 4, 6, 7, 8], 'title': 'BOTH SOLID / LEFT > RIGHT'}, {'type': 'solid', 'solid': [1, 2, 4, 5, 7, 8], 'numbers': [4, 1, 7, 5, 8, 2, 9, 6]}, '4596')
|
| 101 |
+
add(36, 'Before storage', ['Item registry', 'Storage room'], [seq('A', 'A1', ['circle', 'square', 'leaf', 'star'], options=SYMS, visual_override={'type': 'occlusion', 'symbols': ['circle', 'square', 'leaf', 'star']}), num('A', 'A2', '3068', {'type': 'mirror', 'code': '3068'}), num('B', 'B1', '0825', {'type': 'clock', 'hour': 8, 'minute': 25, 'period': 'AM', 'format': 'HHMM'})], lines(['book:4', 'cup:7', 'ball:2'], ['brush:9', 'hook:3', 'box:5'], ['hat:8', 'bottle:6', 'shoe:1'], ['leaf_clip:5', 'scroll:0', 'clip:7'], title='ORIGINAL'), lines(['book', 'cup'], ['hook', 'box'], ['hat', 'shoe'], ['leaf_clip', 'scroll'], title='CURRENT / MISSING ITEM'), '2967')
|
| 102 |
+
add(37, 'Ordering relations', ['Display room', 'Number room'], [rot('A', 'A1', [3, 2, 1]), lamp('B', 'B1', ['leaf', 'circle', 'leaf']), measure('B', 'B2', '0160', 160, source=1)], lines(['circle', '>', 'star'], ['leaf', '>', 'square']), lines(['star', '>', 'leaf'], ['circle', 8], ['star', 0], ['leaf', 4], ['square', 6]), '8046')
|
| 103 |
+
add(38, 'Toy queue', ['Toy repair room', 'Label room'], [weighing('A', 'A1', '0476', 476), binary('A', 'A2', [1, 0, 0, 1]), num('B', 'B1', '364', {'type': 'count', 'groups': [3, 6, 4], 'object': 'spoke'})], {'type': 'symbol_strip', 'symbols': SYMS}, lines(['1', '< >', '3'], ['2', '< >', '4'], ['circle', 5], ['star', 7], ['square', 9], ['leaf', 2]), '9257')
|
| 104 |
+
add(39, 'Pattern inventory', ['Pattern room', 'Pattern store'], [difference('A', 'A1', [1, 3, 4]), seq('B', 'B1', ['down', 'left', 'up'], options=['up', 'right', 'down', 'left'], visual_override={'type': 'symbol_strip', 'symbols': ['down', 'left', 'up'], 'title': 'S > T'}), num('B', 'B2', '368', {'type': 'successor', 'before': [2, 5, 7]})], {'type': 'symbol_strip', 'symbols': ['circle', 'cross', 'leaf', 'star']}, {'type': 'symbol_grid', 'rows': [['circle', 'cross', 'leaf', 'star', 'square'], ['circle', 'cross', 'leaf', 'star', 'triangle'], ['circle', 'leaf', 'star', 'star', 'triangle'], ['circle', 'star', None, None, None]]}, '4235')
|
| 105 |
+
add(40, 'Assembly supply', ['Assembly room', 'Supply room'], [pair('A', 'A1', 'DC'), pipes('A', 'A2', [1, 3, 0], mirror=True), st('assign', 'B', 'B1', items=[{'id': str(i), 'name': 'assembly strip ' + str(i + 1), 'symbol': x + '>' + y} for i, (x, y) in enumerate(zip(['circle', 'star', 'leaf', 'square'], ['star', 'leaf', 'square', 'flag']))], slots=4, target=[0, 1, 2, 3], visual={'type': 'chain', 'ends': [['circle', 'star'], ['star', 'leaf'], ['leaf', 'square'], ['square', 'flag']]})], vector([1, 3, 2, 4]), vector([6, 2, 5, 1], title='COMBINE THE TWO PILES'), '7575')
|
| 106 |
+
add(41, 'Common samples', ['Sample archive', 'Sample display'], [wire('A', 'A1', [3, 2, 4]), num('B', 'B1', '264', {'type': 'holes', 'positions': [2, 6, 4]}), num('B', 'B2', '580', {'type': 'pattern_map', 'references': ['crosshatch', 'waves', 'dots'], 'samples': [['dots', 0], ['crosshatch', 5], ['grid', 2], ['waves', 8]]})], lines(['round_pot', 'square_box'], ['leaf_clip', 'star_plate'], ['brush', 'comb'], ['ball', 'cup']), lines(['square_box:8', 'round_cup:1'], ['star_plate:4', 'triangle_plate:7'], ['comb:6', 'ruler:2'], ['ball:3', 'hat:9'], title='COMMON ITEM / 1 > 4'), '8463')
|
| 107 |
+
add(42, 'Appointment issue', ['Appointment registry', 'Issue room'], [difference('A', 'A1', [2, 4]), num('A', 'A2', '524', {'type': 'hole_count', 'holes': [[1, 2, 3, 5, 6], [2, 5], [1, 3, 4, 6]]}), order('B', 'B1', ['9/12', '9/03', '9/19', '9/07'], [2, 4, 1, 3])], lines(['X', 'clock:9:15 AM'], ['Y', 'clock:2:30 PM']), lines(['08:00 - 10:00', 26, 13], ['10:00 - 12:00', 71, 68], ['12:00 - 15:00', 49, 52], ['15:00 - 18:00', 80, 97], title='TIME / X / Y'), '2652')
|
| 108 |
+
add(43, 'One step each', ['Sign room', 'Map room'], [seq('A', 'A1', ['leaf', 'square', 'circle', 'star'], options=SYMS, visual_override={'type': 'occlusion', 'symbols': ['leaf', 'square', 'circle', 'star']}), num('B', 'B1', '246', {'type': 'missing_middle', 'rows': [[1, None, 3], [3, None, 5], [5, None, 7]]}), weighing('B', 'B2', '0230', 260, 30)], vector(['right', 'up', 'left', 'down'], title='ONE CELL EACH'), grid([[6, 2, 9], [7, 4, 1], [3, 8, 5]], starts=[['circle', 0, 0], ['star', 2, 2], ['square', 2, 1], ['leaf', 0, 2]]), '2131')
|
| 109 |
+
add(44, 'Samples and standards', ['Sample comparison', 'Standard store'], [num('A', 'A1', '241', {'type': 'odd_one', 'rows': [['circle', 'square', 'circle', 'circle'], ['leaf', 'leaf', 'leaf', 'star'], ['triangle', 'square', 'square', 'square']]}), lamp('A', 'A2', ['square', 'leaf', 'square']), rot('B', 'B1', [1, 3, 2])], vector([3, 7, 2, 6]), lines(['STANDARD', 5, 4, 2, 8], ['HEAVIER', 6, 9, 5, 1], ['EQUAL', 4, 3, 7, 8], ['LIGHTER', 8, 2, 0, 6]), '8976')
|
| 110 |
+
for spec in LEVELS.values():
|
| 111 |
+
spec['interroom'] = {'type': 'open_passage', 'boundary_x': 4.8, 'y_range': [1.8, 2.95], 'door_leaf': False, 'lock': False, 'requires_action': False}
|
| 112 |
+
for s in spec['stages']:
|
| 113 |
+
if s.get('tool_source') is not None:
|
| 114 |
+
s['parent'] = None
|
| 115 |
+
assert len(spec['stages']) == 3 and set((x['room'] for x in spec['stages'])) == {'A', 'B'}
|
| 116 |
+
LEVELS['R25']['stages'][0].update(kind='adjust', name='tea-pattern rings', visual={'type': 'pattern_rings'})
|
| 117 |
+
LEVELS['R33']['stages'][2].update(kind='adjust', name='bottle-shape levers', visual={'type': 'lever_shapes'})
|
| 118 |
+
LEVELS['R28']['stages'][2]['rack_order'] = [1, 3, 0, 2]
|
| 119 |
+
LEVELS['R40']['stages'][2]['rack_order'] = [2, 0, 3, 1]
|
| 120 |
+
LEVELS['R33']['stages'][1]['visual'] = {'type': 'cap_notches', 'directions': ['left', 'up', 'right']}
|
runtime/h2_runtime/medium88_wire_identity.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from medium88_clues import board
|
| 2 |
+
|
| 3 |
+
class WireIdentityMixin:
|
| 4 |
+
|
| 5 |
+
def assign(self, i, s, root):
|
| 6 |
+
super().assign(i, s, root)
|
| 7 |
+
pose = self.extra.get((i, 'wire_pose'))
|
| 8 |
+
if pose is None:
|
| 9 |
+
return
|
| 10 |
+
for j, coil in enumerate(pose['coils']):
|
| 11 |
+
self.box('lead_identification_tie', [0, 0, 0.02], [0.06, 0.1, 0.003], 'ivory', coil)
|
| 12 |
+
path = self.tex / f's{i + 1}_lead_tag_{j}.png'
|
| 13 |
+
board({'type': 'symbol_strip', 'symbols': [s['items'][j]['symbol']]}).save(path)
|
| 14 |
+
mat = self.image_mat(f's{i + 1}_lead_tag_material_{j}', path)
|
| 15 |
+
self.plane('lead_symbol_tag', [0, 0, 0.022], 0.054, 0.08, (1, 0, 0), (0, 1, 0), None, coil, material=mat)
|
runtime/h2_runtime/medium_next_base.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import numpy as np
|
| 6 |
+
from depth_four import DepthScene
|
| 7 |
+
from medium88_scene import MediumScene
|
| 8 |
+
from medium88_specs import LEVELS
|
| 9 |
+
from action_feedback import failure_for
|
| 10 |
+
|
| 11 |
+
def make_spec(rid, title, room_names):
|
| 12 |
+
spec = copy.deepcopy(LEVELS[rid])
|
| 13 |
+
spec.update(title=title, room_names=list(room_names), start=[2.5, 1.25, 1.35], start_yaw=90, depth_revision='physical_next_v1', clues={'A': {}, 'B': {}}, room_views={'A': [1.5, 3.75, 1.35], 'B': [6.25, 3.75, 1.35]}, last={'A': 1, 'B': 2}, stages=[{'kind': 'float_key', 'room': r, 'name': n} for r, n in zip(['A', 'A', 'B'], ['first mechanism', 'second mechanism', 'third mechanism'])])
|
| 14 |
+
return spec
|
| 15 |
+
|
| 16 |
+
def _stage_view_grid(spec):
|
| 17 |
+
positions = {'A': ((1.5, 3.75), (1.25, 2.75)), 'B': ((6.25, 3.75), (8.25, 3.5))}
|
| 18 |
+
counts = {'A': 0, 'B': 0}
|
| 19 |
+
views = []
|
| 20 |
+
for stage in spec['stages']:
|
| 21 |
+
room = stage['room']
|
| 22 |
+
index = counts[room]
|
| 23 |
+
if index >= len(positions[room]):
|
| 24 |
+
raise ValueError('Only two native workstation positions per room: ' + room)
|
| 25 |
+
views.append(list(positions[room][index]))
|
| 26 |
+
counts[room] += 1
|
| 27 |
+
return views
|
| 28 |
+
|
| 29 |
+
class PhysicalGame:
|
| 30 |
+
LABELS = {'exit': 'exit door', 'exit_lock': 'exit code keypad'}
|
| 31 |
+
TEXTS = {}
|
| 32 |
+
|
| 33 |
+
def __init__(self):
|
| 34 |
+
self.states = [{}, {}, {}]
|
| 35 |
+
self.solved = [False] * 3
|
| 36 |
+
self.reward_open = [False] * 3
|
| 37 |
+
self.opened = {'exit': False, 's1_cover': True, 's2_cover': True, 's3_cover': True}
|
| 38 |
+
self.holding = []
|
| 39 |
+
self.taken = set()
|
| 40 |
+
self.possessions = {}
|
| 41 |
+
self.exit_unlocked = False
|
| 42 |
+
self.exited = False
|
| 43 |
+
|
| 44 |
+
def snapshot(self):
|
| 45 |
+
return {'states': copy.deepcopy(self.states), 'solved': list(self.solved), 'reward_open': list(self.reward_open), 'opened': dict(self.opened), 'holding': list(self.holding), 'taken': sorted(self.taken), 'possessions': copy.deepcopy(self.possessions), 'exit_unlocked': self.exit_unlocked, 'exited': self.exited}
|
| 46 |
+
|
| 47 |
+
def _resolve_item(self, value):
|
| 48 |
+
value = str(value).strip().casefold()
|
| 49 |
+
return next((key for key in self.holding if value in (key.casefold(), str(self.LABELS.get(key, key)).casefold())), None)
|
| 50 |
+
|
| 51 |
+
def stage_accessible(self, i):
|
| 52 |
+
return 0 <= i < 3
|
| 53 |
+
|
| 54 |
+
def available(self, key):
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
def readable(self, key):
|
| 58 |
+
return key in self.TEXTS
|
| 59 |
+
|
| 60 |
+
def read_text(self, key):
|
| 61 |
+
value = self.TEXTS.get(key, '')
|
| 62 |
+
return '\n'.join(map(str, value)) if isinstance(value, (list, tuple)) else str(value)
|
| 63 |
+
|
| 64 |
+
def give(self, key):
|
| 65 |
+
if key in self.taken or key in self.holding:
|
| 66 |
+
return False
|
| 67 |
+
self.taken.add(key)
|
| 68 |
+
self.holding.append(key)
|
| 69 |
+
return True
|
| 70 |
+
|
| 71 |
+
def consume(self, key):
|
| 72 |
+
if key not in self.holding:
|
| 73 |
+
return False
|
| 74 |
+
self.holding.remove(key)
|
| 75 |
+
self.taken.add(key)
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
def return_item(self, key):
|
| 79 |
+
self.taken.discard(key)
|
| 80 |
+
if key in self.holding:
|
| 81 |
+
self.holding.remove(key)
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def recompute(self):
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
def interact(self, key, verb, item, a):
|
| 88 |
+
return False
|
| 89 |
+
|
| 90 |
+
def act(self, a):
|
| 91 |
+
verb, key = (a.get('action'), a.get('_hit364', ''))
|
| 92 |
+
if not a.get('_validated364'):
|
| 93 |
+
return {'ok': False, 'text': failure_for(verb)}
|
| 94 |
+
result = False
|
| 95 |
+
if key in ('exit', 'exit_lock'):
|
| 96 |
+
if verb == 'unlock':
|
| 97 |
+
self.possessions['door_input'] = str(a.get('code', ''))
|
| 98 |
+
self.exit_unlocked = self.possessions['door_input'] == str(self.SPEC['door_code'])
|
| 99 |
+
result = self.exit_unlocked
|
| 100 |
+
elif verb == 'close' or (verb == 'open' and self.exit_unlocked):
|
| 101 |
+
self.opened['exit'] = verb == 'open'
|
| 102 |
+
self.exited = self.opened['exit'] and self.exit_unlocked
|
| 103 |
+
result = True
|
| 104 |
+
elif verb == 'read' and self.readable(key):
|
| 105 |
+
result = {'ok': True, 'text': self.read_text(key)}
|
| 106 |
+
elif verb == 'take' and self.available(key) and (key not in self.taken):
|
| 107 |
+
result = self.give(key)
|
| 108 |
+
else:
|
| 109 |
+
result = self.interact(key, verb, self._resolve_item(a.get('item', '')), a)
|
| 110 |
+
if isinstance(result, dict):
|
| 111 |
+
ok, message = (bool(result.get('ok')), str(result.get('text', '')))
|
| 112 |
+
else:
|
| 113 |
+
ok, message = (bool(result), '')
|
| 114 |
+
if ok:
|
| 115 |
+
self.recompute()
|
| 116 |
+
self.reward_open = list(self.solved)
|
| 117 |
+
return {'ok': ok, 'text': message if ok and verb == 'read' else '' if ok else failure_for(verb)}
|
| 118 |
+
|
| 119 |
+
class PhysicalScene(DepthScene):
|
| 120 |
+
LABELS = {}
|
| 121 |
+
|
| 122 |
+
def __init__(self, og, run, spec):
|
| 123 |
+
super().__init__(og, run, spec)
|
| 124 |
+
self.labels = {'exit': 'exit door', 'exit_lock': 'exit code keypad'}
|
| 125 |
+
self.labels.update(self.LABELS)
|
| 126 |
+
self._physical_hidden = set()
|
| 127 |
+
|
| 128 |
+
def _physical_asset_key(self, im, size=None):
|
| 129 |
+
pixels = im.convert('RGBA')
|
| 130 |
+
header = repr((pixels.mode, pixels.size, size)).encode('utf-8')
|
| 131 |
+
return hashlib.sha256(header + b'\x00' + pixels.tobytes()).hexdigest()
|
| 132 |
+
|
| 133 |
+
def _physical_asset(self, im, size=None):
|
| 134 |
+
path = self.tex / ('a_' + self._physical_asset_key(im, size)[:32] + '.png')
|
| 135 |
+
if not path.exists():
|
| 136 |
+
im.save(path)
|
| 137 |
+
return path
|
| 138 |
+
|
| 139 |
+
def face(self, key, parent, pos, w, h, im):
|
| 140 |
+
p = self._physical_asset(im, (w, h))
|
| 141 |
+
mat = self.image_mat('physical_face_' + p.stem, p)
|
| 142 |
+
self.plane(key, pos, w, h, (1, 0, 0), (0, 0, 1), None, parent, material=mat)
|
| 143 |
+
return mat
|
| 144 |
+
|
| 145 |
+
def show_image(self, key, parent, pos, w, h, im):
|
| 146 |
+
if len(key) > 2 and key[0] == 's' and key[1].isdigit() and key.endswith(('_reference', '_evidence')):
|
| 147 |
+
i = int(key[1]) - 1
|
| 148 |
+
stage = self.spec['stages'][i]
|
| 149 |
+
if key == f's{i + 1}_reference' and stage.get('visual', {}).get('type') == 'wire_trace':
|
| 150 |
+
pos, w, h = ([0.12, -0.035, 1.425], 0.92, 0.34)
|
| 151 |
+
elif key == f's{i + 1}_reference':
|
| 152 |
+
pos, w, h = ([0, 0.27, 1.47], 1.1, 0.34)
|
| 153 |
+
elif key == f's{i + 1}_evidence':
|
| 154 |
+
pos, w, h = ([0, 0.27, 1.43], 1.1, 0.38)
|
| 155 |
+
if key.endswith(('_reference', '_evidence', '_complete_reference', '_goal')) and any((parent is root for root in self.roots)):
|
| 156 |
+
self.box(key + '_physical_backing', [pos[0], pos[1] + 0.012, pos[2]], [w + 0.025, 0.022, h + 0.025], 'ivory', parent)
|
| 157 |
+
p = self._physical_asset(im, (w, h))
|
| 158 |
+
mat = self.image_mat('physical_image_' + p.stem, p)
|
| 159 |
+
return self.plane(key, pos, w, h, (1, 0, 0), (0, 0, 1), None, parent, material=mat)
|
| 160 |
+
|
| 161 |
+
def screen(self, key, parent, pos, w, h, im, sig):
|
| 162 |
+
identity = (self._physical_asset_key(im, (w, h)), tuple(pos), w, h, id(parent))
|
| 163 |
+
cache = self.__dict__.setdefault('_physical_screen_assets', {})
|
| 164 |
+
if key in self.images and self.image_sig.get(key) == sig and (cache.get(key) == identity):
|
| 165 |
+
return
|
| 166 |
+
self.image_sig[key] = object()
|
| 167 |
+
super().screen(key, parent, pos, w, h, im, sig)
|
| 168 |
+
cache[key] = identity
|
| 169 |
+
|
| 170 |
+
def button(self, key, parent, pos, symbol='circle', size=0.14):
|
| 171 |
+
node = super().button(key, parent, pos, symbol, size)
|
| 172 |
+
handle = self.custom.get('handle_' + key)
|
| 173 |
+
if handle is not None:
|
| 174 |
+
self.__dict__.setdefault('_generic_button_pairs', {})[key] = (node, handle)
|
| 175 |
+
return node
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def _button_pose(handle):
|
| 179 |
+
return tuple((tuple((float(v) for v in handle[name].Get())) for name in ('translate', 'rotate')))
|
| 180 |
+
|
| 181 |
+
def _button_response_candidate(self, d):
|
| 182 |
+
if (getattr(d, 'current_action', None) or {}).get('action') != 'press' or not (getattr(d, 'current_result', None) or {}).get('ok'):
|
| 183 |
+
return None
|
| 184 |
+
key = (getattr(d, 'current_hit', None) or {}).get('key', '')
|
| 185 |
+
if any((word in key.casefold() for word in ('pump', 'wheel', 'crank'))):
|
| 186 |
+
return None
|
| 187 |
+
pair = self.__dict__.get('_generic_button_pairs', {}).get(key)
|
| 188 |
+
if pair is None or self.target_nodes.get(key) is not pair[0] or self.custom.get('handle_' + key) is not pair[1]:
|
| 189 |
+
return None
|
| 190 |
+
if getattr(d, 'current_visual_feedback', ()):
|
| 191 |
+
return None
|
| 192 |
+
step = getattr(d, 'step', None)
|
| 193 |
+
if step is not None and any((row.get('step') == step for name in ('timeline', 'capture_rows') for row in getattr(d, name, ()))):
|
| 194 |
+
return None
|
| 195 |
+
if not callable(getattr(d, 'capture_feedback_frame', None)):
|
| 196 |
+
return None
|
| 197 |
+
return (key, pair, self._button_pose(pair[1]))
|
| 198 |
+
|
| 199 |
+
def _button_response(self, d, candidate):
|
| 200 |
+
if candidate is None:
|
| 201 |
+
return
|
| 202 |
+
key, (node, handle), old_pose = candidate
|
| 203 |
+
if self.target_nodes.get(key) is not node or self.custom.get('handle_' + key) is not handle:
|
| 204 |
+
return
|
| 205 |
+
pose = self._button_pose(handle)
|
| 206 |
+
if not all((abs(a - b) < 1e-07 for aa, bb in zip(old_pose, pose) for a, b in zip(aa, bb))):
|
| 207 |
+
return
|
| 208 |
+
position, rest = pose
|
| 209 |
+
pressed = list(rest)
|
| 210 |
+
pressed[1] += -12 if rest[1] > 0 else 12
|
| 211 |
+
try:
|
| 212 |
+
for phase, rotation in enumerate((rest, pressed, rest)):
|
| 213 |
+
self.transform(handle, pos=position, rpy=rotation)
|
| 214 |
+
if phase:
|
| 215 |
+
d.frame(warm=4)
|
| 216 |
+
d.capture_feedback_frame()
|
| 217 |
+
d.append('Control handle depresses and springs back', 4)
|
| 218 |
+
finally:
|
| 219 |
+
self.transform(handle, pos=position, rpy=rest)
|
| 220 |
+
|
| 221 |
+
def controls_for(self, i, s, root):
|
| 222 |
+
pass
|
| 223 |
+
|
| 224 |
+
def core_card(self, i, root, reward):
|
| 225 |
+
self.core_cards.append(None)
|
| 226 |
+
|
| 227 |
+
def apply_visuals(self, g):
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
def build(self, g):
|
| 231 |
+
MediumScene.build(self, g)
|
| 232 |
+
self.stage_views = _stage_view_grid(self.spec)
|
| 233 |
+
for key in self.target_nodes:
|
| 234 |
+
if key.startswith('s') and key[1:2].isdigit():
|
| 235 |
+
index = int(key[1]) - 1
|
| 236 |
+
if index < len(self.stage_views):
|
| 237 |
+
self.views[key] = self.stage_views[index]
|
| 238 |
+
self.door_view = [8.25, 1.25]
|
| 239 |
+
self.views['exit'] = list(self.door_view)
|
| 240 |
+
self.views['exit_lock'] = list(self.door_view)
|
| 241 |
+
self.labels.update(g.LABELS)
|
| 242 |
+
if 'light_frame' in self.extra:
|
| 243 |
+
self.visibility(self.extra['light_frame'], False)
|
| 244 |
+
self.target_nodes.pop('light_frame', None)
|
| 245 |
+
self._physical_hidden.add('light_frame')
|
| 246 |
+
assert self.door_lock['prim'].GetParent().GetPath() == self.exit_node['prim'].GetPath()
|
| 247 |
+
self.label('attached_exit_code_label', 'EXIT CODE', [0, -0.034, 0.094], 0.18, 0.023, parent=self.door_lock)
|
| 248 |
+
for j, value in enumerate('123456789*0#'):
|
| 249 |
+
r, c = divmod(j, 3)
|
| 250 |
+
self.box('keypad_key', [(c - 1) * 0.06, -0.036, -0.005 - r * 0.025], [0.035, 0.01, 0.018], 'cream', self.door_lock)
|
| 251 |
+
self.label('keypad_digit_' + str(j), value, [(c - 1) * 0.06, -0.042, -0.005 - r * 0.025], 0.027, 0.016, parent=self.door_lock)
|
| 252 |
+
self.reg('exit', {'meshes': [n for n in self.exit_node['meshes'] if n is not self.door_lock]})
|
| 253 |
+
self.sync(g)
|
| 254 |
+
|
| 255 |
+
def read_board(self, key, parent, pos, lines, w=1.65, h=0.34):
|
| 256 |
+
return self.textboard(key, parent, pos, lines.splitlines() if isinstance(lines, str) else lines, w, h)
|
| 257 |
+
|
| 258 |
+
def tool(self, key, parent, pos, kind=None):
|
| 259 |
+
kind = kind or key
|
| 260 |
+
known = {'wrench', 'rod', 'hook', 'pawl_tool', 'meter', 'wire', 'rubber', 'clamp', 'blockP', 'blockQ', 'band', 'cutters'}
|
| 261 |
+
if kind in known:
|
| 262 |
+
old_prop = self.props.get(kind)
|
| 263 |
+
old_target = self.target_nodes.get(kind)
|
| 264 |
+
node = DepthScene.physical_tool(self, kind, parent, pos, kind)
|
| 265 |
+
if key != kind:
|
| 266 |
+
if old_prop is None:
|
| 267 |
+
self.props.pop(kind, None)
|
| 268 |
+
else:
|
| 269 |
+
self.props[kind] = old_prop
|
| 270 |
+
if old_target is None:
|
| 271 |
+
self.target_nodes.pop(kind, None)
|
| 272 |
+
else:
|
| 273 |
+
self.target_nodes[kind] = old_target
|
| 274 |
+
self.props[key] = node
|
| 275 |
+
self.reg(key, node)
|
| 276 |
+
return node
|
| 277 |
+
node = self.group(key, pos, parent)
|
| 278 |
+
if kind in ('hammer', 'mallet'):
|
| 279 |
+
self.box('wooden_handle', [0, 0, 0], [0.028, 0.035, 0.25], 'wood', node)
|
| 280 |
+
self.box('hammer_head', [0, 0, 0.13], [0.17, 0.065, 0.065], 'steel', node)
|
| 281 |
+
elif kind in ('screwdriver', 'awl'):
|
| 282 |
+
self.cylinder('grip', [0, 0, -0.06], 0.03, 0.14, 'wood', 'z', node)
|
| 283 |
+
self.cylinder('shaft', [0, 0, 0.075], 0.009, 0.15, 'steel', 'z', node)
|
| 284 |
+
self.box('flat_tip', [0, 0, 0.15], [0.025, 0.007, 0.02], 'steel', node)
|
| 285 |
+
elif kind in ('paper', 'card', 'sheet', 'label', 'film'):
|
| 286 |
+
self.box('flat_sheet', [0, 0, 0], [0.2, 0.008, 0.15], 'cream', node)
|
| 287 |
+
elif kind in ('rope', 'cord', 'belt', 'strap'):
|
| 288 |
+
for x in (-0.065, 0.065):
|
| 289 |
+
self.tube('loose_loop', [x, 0, -0.09], [x, 0, 0.09], 0.01, 'rubber', node)
|
| 290 |
+
for z in (-0.09, 0.09):
|
| 291 |
+
self.tube('loop_end', [-0.065, 0, z], [0.065, 0, z], 0.01, 'rubber', node)
|
| 292 |
+
else:
|
| 293 |
+
self.box('handled_component', [0, 0, 0], [0.12, 0.055, 0.12], 'brass', node)
|
| 294 |
+
self.box('component_grip', [0, 0, -0.1], [0.035, 0.04, 0.12], 'wood', node)
|
| 295 |
+
self.props[key] = node
|
| 296 |
+
self.reg(key, node)
|
| 297 |
+
return node
|
| 298 |
+
|
| 299 |
+
def case(self, i, root, key='s2_open', width=0.7):
|
| 300 |
+
return self.smallcase(i, root, key, width)
|
| 301 |
+
|
| 302 |
+
def status(self, key, parent, pos, value, w=0.3, h=0.09):
|
| 303 |
+
self.screen(key, parent, pos, w, h, self.small_text(value), repr(value))
|
| 304 |
+
return self.images[key]
|
| 305 |
+
|
| 306 |
+
def sync(self, g):
|
| 307 |
+
self._dynamic_collision_cache = None
|
| 308 |
+
for i, (off, on) in enumerate(self.status_nodes):
|
| 309 |
+
self.visibility(off, not g.solved[i])
|
| 310 |
+
self.visibility(on, g.solved[i])
|
| 311 |
+
for key, node in self.props.items():
|
| 312 |
+
self.visibility(node, key not in g.holding)
|
| 313 |
+
self.apply_visuals(g)
|
| 314 |
+
if hasattr(self, 'exit_node'):
|
| 315 |
+
self.transform(self.exit_node, rpy=[0, 0, 90 + (100 if g.opened['exit'] else 0)])
|
| 316 |
+
if hasattr(self, 'door_lock'):
|
| 317 |
+
value = g.possessions.get('door_input', '____')
|
| 318 |
+
self.screen('exit_lcd', self.door_lock, [0, -0.034, 0.045], 0.205, 0.04, self.small_text(value), value)
|
| 319 |
+
self.centres = {}
|
| 320 |
+
for key, node in self.target_nodes.items():
|
| 321 |
+
points = self.triangles(node).reshape(-1, 3)
|
| 322 |
+
if points.size:
|
| 323 |
+
self.centres[key] = ((points.min(0) + points.max(0)) / 2).tolist()
|
| 324 |
+
|
| 325 |
+
def _node_visible(self, node):
|
| 326 |
+
prim = node.get('prim')
|
| 327 |
+
if prim is not None and self.G.Imageable(prim).ComputeVisibility() == 'invisible':
|
| 328 |
+
return False
|
| 329 |
+
if 'points' in node:
|
| 330 |
+
return True
|
| 331 |
+
return any((self._node_visible(child) for child in node.get('meshes', [])))
|
| 332 |
+
|
| 333 |
+
def target_enabled(self, key, g):
|
| 334 |
+
return key not in self._physical_hidden and key not in g.holding and (key in self.target_nodes) and self._node_visible(self.target_nodes[key])
|
| 335 |
+
|
| 336 |
+
def visible(self, key, g):
|
| 337 |
+
return self.target_enabled(key, g)
|
| 338 |
+
|
| 339 |
+
def candidates(self, g):
|
| 340 |
+
return self.base_candidates([key for key in self.target_nodes if self.visible(key, g)])
|
| 341 |
+
|
| 342 |
+
def animate(self, d, before):
|
| 343 |
+
response = self._button_response_candidate(d)
|
| 344 |
+
after = d.game.snapshot()
|
| 345 |
+
if before == after:
|
| 346 |
+
if response is not None:
|
| 347 |
+
self.sync(d.game)
|
| 348 |
+
self._button_response(d, response)
|
| 349 |
+
return
|
| 350 |
+
if before['opened']['exit'] != after['opened']['exit']:
|
| 351 |
+
start = 100 if before['opened']['exit'] else 0
|
| 352 |
+
end = 100 if after['opened']['exit'] else 0
|
| 353 |
+
poses = []
|
| 354 |
+
for fraction in (0, 0.2, 0.4, 0.6, 0.8, 1):
|
| 355 |
+
self.sync(d.game)
|
| 356 |
+
self.transform(self.exit_node, rpy=[0, 0, 90 + start + (end - start) * fraction])
|
| 357 |
+
cache = self.G.XformCache()
|
| 358 |
+
door = cache.GetLocalToWorldTransform(self.exit_node['prim'])
|
| 359 |
+
lock = cache.GetLocalToWorldTransform(self.door_lock['prim'])
|
| 360 |
+
local = list(door.GetInverse().Transform(lock.ExtractTranslation()))
|
| 361 |
+
assert max((abs(float(x) - y) for x, y in zip(local, [0.84, 0.075, 1.5]))) < 1e-06
|
| 362 |
+
poses.append({'fraction': fraction, 'door_local_position': local, 'world_position': list(lock.ExtractTranslation())})
|
| 363 |
+
d.frame(warm=4)
|
| 364 |
+
d.append('Door and attached keypad move together', 4)
|
| 365 |
+
if hasattr(d, 'save'):
|
| 366 |
+
d.save('DOOR_ATTACHMENT_' + ('open' if after['opened']['exit'] else 'close') + '.json', {'fixed_local_pose_verified': True, 'poses': poses})
|
| 367 |
+
self.sync(d.game)
|
| 368 |
+
self._button_response(d, response)
|
| 369 |
+
d.frame(warm=8)
|
| 370 |
+
d.append('Observe the physical result', 8)
|
| 371 |
+
|
| 372 |
+
def standard_go(d, i, point=(0, -0.08, 1.18)):
|
| 373 |
+
d.route(d.scene.stage_views[i])
|
| 374 |
+
d.aim(d.scene.world(i, list(point)), 'Observe the mechanism and its real parts')
|
| 375 |
+
|
| 376 |
+
def standard_click(d, key, verb='press', item=None, **kw):
|
| 377 |
+
return d.click(key, verb, item=item, **kw)
|
| 378 |
+
|
| 379 |
+
def observe_clue(d, name):
|
| 380 |
+
if not hasattr(d, 'run'):
|
| 381 |
+
return
|
| 382 |
+
path = Path(d.run) / 'screenshots' / ('clue_' + str(name) + '_native.png')
|
| 383 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 384 |
+
d.clean.save(path)
|
| 385 |
+
observations = getattr(d, 'cross_room_observations', [])
|
| 386 |
+
observations.append({'name': 'clue_' + str(name), 'path': str(path), 'step': d.step, 'native': True})
|
| 387 |
+
d.cross_room_observations = observations
|
| 388 |
+
d.save('CROSS_ROOM_OBSERVATIONS.json', observations)
|
| 389 |
+
|
| 390 |
+
def finish_exit(d, code=None):
|
| 391 |
+
d.route(d.scene.door_view)
|
| 392 |
+
d.aim(d.scene.centres['exit_lock'])
|
| 393 |
+
standard_click(d, 'exit_lock', 'unlock', code=d.game.SPEC['door_code'] if code is None else code)
|
| 394 |
+
standard_click(d, 'exit', 'open')
|
| 395 |
+
|
| 396 |
+
def exit_test(pos, g):
|
| 397 |
+
return bool(g.exited and g.opened['exit'] and g.exit_unlocked)
|
runtime/h2_runtime/medium_v6.py
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import hashlib
|
| 3 |
+
import math
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image, ImageDraw
|
| 7 |
+
from action_feedback import failure_for
|
| 8 |
+
from font_utils import load_font
|
| 9 |
+
ROOM_A = (0.0, 0.0, 4.8, 5.0)
|
| 10 |
+
ROOM_B = (4.8, 0.0, 9.6, 5.0)
|
| 11 |
+
PASSAGE = (1.8, 2.95)
|
| 12 |
+
DOOR_VIEW = [8.75, 1.25]
|
| 13 |
+
EYE = 1.35
|
| 14 |
+
FACING = {'north': ((1, 0, 0), (0, 0, 1)), 'south': ((-1, 0, 0), (0, 0, 1)), 'west': ((0, 1, 0), (0, 0, 1)), 'east': ((0, -1, 0), (0, 0, 1)), 'up': ((1, 0, 0), (0, 1, 0)), 'down': ((1, 0, 0), (0, -1, 0))}
|
| 15 |
+
NORMAL = {'north': (0, -1, 0), 'south': (0, 1, 0), 'west': (1, 0, 0), 'east': (-1, 0, 0), 'up': (0, 0, 1), 'down': (0, 0, -1)}
|
| 16 |
+
WALL_YAW = {'north': 0, 'south': 180, 'west': 90, 'east': -90}
|
| 17 |
+
|
| 18 |
+
class V6Game:
|
| 19 |
+
SPEC = {}
|
| 20 |
+
LABELS = {}
|
| 21 |
+
TEXTS = {}
|
| 22 |
+
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.s = {}
|
| 25 |
+
self.solved = [False, False, False]
|
| 26 |
+
self.opened = {'exit': False}
|
| 27 |
+
self.holding = []
|
| 28 |
+
self.taken = set()
|
| 29 |
+
self.possessions = {}
|
| 30 |
+
self.exit_unlocked = False
|
| 31 |
+
self.exited = False
|
| 32 |
+
self.setup()
|
| 33 |
+
|
| 34 |
+
def setup(self):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
def snapshot(self):
|
| 38 |
+
return {'state': copy.deepcopy(self.s), 'solved': list(self.solved), 'opened': dict(self.opened), 'holding': list(self.holding), 'taken': sorted(self.taken), 'possessions': copy.deepcopy(self.possessions), 'exit_unlocked': self.exit_unlocked, 'exited': self.exited}
|
| 39 |
+
|
| 40 |
+
def _resolve_item(self, value):
|
| 41 |
+
value = str(value or '').strip().casefold()
|
| 42 |
+
return next((k for k in self.holding if value in (k.casefold(), str(self.LABELS.get(k, k)).casefold())), None)
|
| 43 |
+
|
| 44 |
+
def give(self, key):
|
| 45 |
+
if key in self.holding:
|
| 46 |
+
return False
|
| 47 |
+
self.taken.add(key)
|
| 48 |
+
self.holding.append(key)
|
| 49 |
+
return True
|
| 50 |
+
|
| 51 |
+
def consume(self, key):
|
| 52 |
+
if key not in self.holding:
|
| 53 |
+
return False
|
| 54 |
+
self.holding.remove(key)
|
| 55 |
+
return True
|
| 56 |
+
|
| 57 |
+
def interact(self, key, verb, item, a):
|
| 58 |
+
return False
|
| 59 |
+
|
| 60 |
+
def recompute(self):
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
def act(self, a):
|
| 64 |
+
verb, key = (a.get('action'), a.get('_hit364', ''))
|
| 65 |
+
if not a.get('_validated364'):
|
| 66 |
+
return {'ok': False, 'text': failure_for(verb)}
|
| 67 |
+
if key == 'exit_lock' and verb == 'unlock':
|
| 68 |
+
self.possessions['door_input'] = str(a.get('code', ''))
|
| 69 |
+
self.exit_unlocked = self.possessions['door_input'] == str(self.SPEC['door_code'])
|
| 70 |
+
result = self.exit_unlocked
|
| 71 |
+
elif key == 'exit' and verb in ('open', 'close'):
|
| 72 |
+
result = verb == 'close' or self.exit_unlocked
|
| 73 |
+
if result:
|
| 74 |
+
self.opened['exit'] = verb == 'open'
|
| 75 |
+
self.exited = self.opened['exit'] and self.exit_unlocked
|
| 76 |
+
elif verb == 'read' and key in self.TEXTS:
|
| 77 |
+
text = self.TEXTS[key]
|
| 78 |
+
result = {'ok': True, 'text': '\n'.join(text) if isinstance(text, (list, tuple)) else str(text)}
|
| 79 |
+
else:
|
| 80 |
+
result = self.interact(key, verb, self._resolve_item(a.get('item', '')), a)
|
| 81 |
+
ok = bool(result.get('ok')) if isinstance(result, dict) else bool(result)
|
| 82 |
+
text = str(result.get('text', '')) if isinstance(result, dict) else ''
|
| 83 |
+
if ok:
|
| 84 |
+
self.recompute()
|
| 85 |
+
return {'ok': ok, 'text': text if ok and verb == 'read' else '' if ok else failure_for(verb)}
|
| 86 |
+
|
| 87 |
+
def exit_test(pos, g):
|
| 88 |
+
return bool(g.exited and g.opened['exit'] and g.exit_unlocked)
|
| 89 |
+
INK = (34, 40, 42)
|
| 90 |
+
PAPER = (226, 219, 196)
|
| 91 |
+
|
| 92 |
+
def canvas(w=600, h=600, bg=PAPER):
|
| 93 |
+
im = Image.new('RGB', (w, h), bg)
|
| 94 |
+
return (im, ImageDraw.Draw(im))
|
| 95 |
+
|
| 96 |
+
def font(size):
|
| 97 |
+
return load_font(size)
|
| 98 |
+
|
| 99 |
+
def poly_at(points, cx, cy, s, angle=0.0, mirror=False):
|
| 100 |
+
out = []
|
| 101 |
+
c, n = (math.cos(math.radians(angle)), math.sin(math.radians(angle)))
|
| 102 |
+
for x, y in points:
|
| 103 |
+
if mirror:
|
| 104 |
+
x = -x
|
| 105 |
+
out.append((cx + s * (x * c - y * n), cy + s * (x * n + y * c)))
|
| 106 |
+
return out
|
| 107 |
+
|
| 108 |
+
def draw_icon(d, name, cx, cy, s, fill=INK, angle=0.0, mirror=False, width=None):
|
| 109 |
+
P = lambda pts: poly_at(pts, cx, cy, s, angle, mirror)
|
| 110 |
+
w = width or max(2, int(s * 0.12))
|
| 111 |
+
if name == 'hammer':
|
| 112 |
+
d.polygon(P([(-0.1, -0.2), (0.1, -0.2), (0.1, 0.95), (-0.1, 0.95)]), fill=(120, 80, 40))
|
| 113 |
+
d.polygon(P([(-0.65, -0.75), (0.45, -0.75), (0.55, -0.55), (0.75, -0.6), (0.75, -0.25), (-0.65, -0.25)]), fill=fill)
|
| 114 |
+
elif name == 'wrench':
|
| 115 |
+
d.polygon(P([(-0.12, -0.35), (0.12, -0.35), (0.12, 0.9), (-0.12, 0.9)]), fill=fill)
|
| 116 |
+
d.polygon(P([(-0.45, -0.95), (-0.18, -0.95), (-0.18, -0.6), (0.18, -0.6), (0.18, -0.95), (0.45, -0.95), (0.45, -0.45), (0.2, -0.25), (-0.2, -0.25), (-0.45, -0.45)]), fill=fill)
|
| 117 |
+
elif name == 'oilcan':
|
| 118 |
+
d.polygon(P([(-0.55, -0.1), (0.35, -0.1), (0.35, 0.85), (-0.55, 0.85)]), fill=fill)
|
| 119 |
+
d.polygon(P([(-0.25, -0.1), (0.05, -0.1), (0, -0.35), (-0.2, -0.35)]), fill=fill)
|
| 120 |
+
d.polygon(P([(0.3, 0.05), (0.95, -0.75), (1.0, -0.65), (0.4, 0.25)]), fill=fill)
|
| 121 |
+
elif name == 'pliers':
|
| 122 |
+
d.polygon(P([(-0.1, -0.95), (0.1, -0.95), (0.18, -0.1), (-0.18, -0.1)]), fill=fill)
|
| 123 |
+
d.polygon(P([(-0.18, -0.1), (-0.05, -0.05), (-0.45, 0.95), (-0.65, 0.9)]), fill=fill)
|
| 124 |
+
d.polygon(P([(0.18, -0.1), (0.05, -0.05), (0.45, 0.95), (0.65, 0.9)]), fill=fill)
|
| 125 |
+
d.ellipse([x - s * 0.14 for x in P([(0, -0.15)])[0]] + [x + s * 0.14 for x in P([(0, -0.15)])[0]], fill=(200, 60, 40))
|
| 126 |
+
elif name == 'deer':
|
| 127 |
+
d.polygon(P([(-0.6, -0.1), (0.45, -0.1), (0.55, 0.1), (0.45, 0.3), (-0.6, 0.3)]), fill=fill)
|
| 128 |
+
for x in (-0.5, -0.3, 0.25, 0.42):
|
| 129 |
+
d.polygon(P([(x, 0.3), (x + 0.08, 0.3), (x + 0.08, 0.95), (x, 0.95)]), fill=fill)
|
| 130 |
+
d.polygon(P([(0.4, -0.1), (0.55, -0.55), (0.85, -0.5), (0.75, -0.35), (0.6, -0.05)]), fill=fill)
|
| 131 |
+
d.line(P([(0.6, -0.55), (0.5, -0.95), (0.35, -0.8)]), fill=fill, width=w)
|
| 132 |
+
d.line(P([(0.68, -0.55), (0.85, -0.95), (1.0, -0.85)]), fill=fill, width=w)
|
| 133 |
+
elif name == 'fish':
|
| 134 |
+
d.ellipse(P([(-0.7, -0.4)])[0] + P([(0.45, 0.4)])[0], fill=fill) if not angle and (not mirror) else d.polygon(P([(-0.7, 0), (-0.4, -0.38), (0.1, -0.42), (0.45, 0), (0.1, 0.42), (-0.4, 0.38)]), fill=fill)
|
| 135 |
+
d.polygon(P([(0.4, 0), (0.95, -0.45), (0.95, 0.45)]), fill=fill)
|
| 136 |
+
e = P([(-0.42, -0.08)])[0]
|
| 137 |
+
d.ellipse([e[0] - s * 0.07, e[1] - s * 0.07, e[0] + s * 0.07, e[1] + s * 0.07], fill=PAPER)
|
| 138 |
+
elif name == 'bird':
|
| 139 |
+
d.ellipse(P([(-0.45, -0.25)])[0] + P([(0.45, 0.35)])[0], fill=fill)
|
| 140 |
+
d.ellipse(P([(0.25, -0.6)])[0] + P([(0.65, -0.2)])[0], fill=fill)
|
| 141 |
+
d.polygon(P([(0.62, -0.45), (0.95, -0.35), (0.62, -0.3)]), fill=(200, 140, 40))
|
| 142 |
+
d.polygon(P([(-0.4, 0), (-0.95, -0.4), (-0.85, 0.15)]), fill=fill)
|
| 143 |
+
d.line(P([(0, 0.32), (-0.05, 0.85)]), fill=fill, width=w)
|
| 144 |
+
d.line(P([(0.15, 0.32), (0.2, 0.85)]), fill=fill, width=w)
|
| 145 |
+
elif name == 'sun':
|
| 146 |
+
d.ellipse(P([(-0.45, -0.45)])[0] + P([(0.45, 0.45)])[0], fill=fill)
|
| 147 |
+
for k in range(8):
|
| 148 |
+
a = k * math.pi / 4
|
| 149 |
+
d.line(P([(0.6 * math.cos(a), 0.6 * math.sin(a)), (0.95 * math.cos(a), 0.95 * math.sin(a))]), fill=fill, width=w)
|
| 150 |
+
elif name == 'moon':
|
| 151 |
+
outer = [(0.85 * math.cos(math.radians(t)), 0.85 * math.sin(math.radians(t))) for t in range(50, 311, 10)]
|
| 152 |
+
inner = [(0.32 + 0.62 * math.cos(math.radians(t)), 0.62 * math.sin(math.radians(t))) for t in range(280, 79, -10)]
|
| 153 |
+
d.polygon(P(outer + inner), fill=fill)
|
| 154 |
+
elif name == 'star':
|
| 155 |
+
pts = []
|
| 156 |
+
for k in range(10):
|
| 157 |
+
r = 0.95 if k % 2 == 0 else 0.4
|
| 158 |
+
a = -math.pi / 2 + k * math.pi / 5
|
| 159 |
+
pts.append((r * math.cos(a), r * math.sin(a)))
|
| 160 |
+
d.polygon(P(pts), fill=fill)
|
| 161 |
+
elif name == 'circle':
|
| 162 |
+
d.ellipse([cx - 0.8 * s, cy - 0.8 * s, cx + 0.8 * s, cy + 0.8 * s], fill=fill)
|
| 163 |
+
elif name == 'square':
|
| 164 |
+
d.polygon(P([(-0.75, -0.75), (0.75, -0.75), (0.75, 0.75), (-0.75, 0.75)]), fill=fill)
|
| 165 |
+
elif name == 'triangle':
|
| 166 |
+
d.polygon(P([(0, -0.85), (0.85, 0.7), (-0.85, 0.7)]), fill=fill)
|
| 167 |
+
elif name == 'cross':
|
| 168 |
+
d.polygon(P([(-0.25, -0.85), (0.25, -0.85), (0.25, -0.25), (0.85, -0.25), (0.85, 0.25), (0.25, 0.25), (0.25, 0.85), (-0.25, 0.85), (-0.25, 0.25), (-0.85, 0.25), (-0.85, -0.25), (-0.25, -0.25)]), fill=fill)
|
| 169 |
+
elif name == 'leaf':
|
| 170 |
+
pts = [(0.55 * math.sin(math.pi * k / 12), -0.9 + 1.8 * k / 12) for k in range(13)] + [(-0.55 * math.sin(math.pi * k / 12), 0.9 - 1.8 * k / 12) for k in range(13)]
|
| 171 |
+
d.polygon(P(pts), fill=fill)
|
| 172 |
+
d.line(P([(0, -0.7), (0, 0.95)]), fill=PAPER, width=max(2, int(s * 0.08)))
|
| 173 |
+
else:
|
| 174 |
+
d.text((cx, cy), name, font=font(int(s * 0.5)), fill=fill, anchor='mm')
|
| 175 |
+
|
| 176 |
+
def outline_image(shape, w_px=240, h_px=160, ink=(250, 250, 244), bg=(70, 74, 76)):
|
| 177 |
+
im, d = canvas(w_px, h_px, bg)
|
| 178 |
+
W, H, m = (w_px, h_px, 16)
|
| 179 |
+
|
| 180 |
+
def dash(pts, closed=True):
|
| 181 |
+
pts = list(pts) + ([pts[0]] if closed else [])
|
| 182 |
+
for (ax, ay), (bx, by) in zip(pts, pts[1:]):
|
| 183 |
+
n = max(1, int(math.hypot(bx - ax, by - ay) / 14))
|
| 184 |
+
for k in range(n):
|
| 185 |
+
t0, t1 = (k / n, (k + 0.55) / n)
|
| 186 |
+
d.line([(ax + (bx - ax) * t0, ay + (by - ay) * t0), (ax + (bx - ax) * t1, ay + (by - ay) * t1)], fill=ink, width=6)
|
| 187 |
+
if shape == 'circle':
|
| 188 |
+
r = min(W, H) / 2 - m
|
| 189 |
+
dash([(W / 2 + r * math.cos(k * math.pi / 18), H / 2 + r * math.sin(k * math.pi / 18)) for k in range(36)])
|
| 190 |
+
elif shape == 'coil':
|
| 191 |
+
for r in (min(W, H) / 2 - m, min(W, H) / 2 - m - 18):
|
| 192 |
+
dash([(W / 2 + r * math.cos(k * math.pi / 18), H / 2 + r * math.sin(k * math.pi / 18)) for k in range(36)])
|
| 193 |
+
elif shape == 'tkey':
|
| 194 |
+
dash([(m, m), (W - m, m), (W - m, m + 30), (W / 2 + 14, m + 30), (W / 2 + 14, H - m), (W / 2 - 14, H - m), (W / 2 - 14, m + 30), (m, m + 30)])
|
| 195 |
+
elif shape == 'wedge':
|
| 196 |
+
dash([(m, H - m), (W - m, H - m), (W - m, m), (m, H - m - 30)])
|
| 197 |
+
elif shape == 'bar':
|
| 198 |
+
dash([(m, H / 2 - 14), (W - m, H / 2 - 14), (W - m, H / 2 + 14), (m, H / 2 + 14)])
|
| 199 |
+
elif shape == 'clamp':
|
| 200 |
+
dash([(m + 20, m), (W - m - 20, m), (W - m - 20, H - m), (m + 20, H - m)])
|
| 201 |
+
dash([(W - m - 20, H / 2 - 18), (W - 4, H / 2 - 18), (W - 4, H / 2 + 18), (W - m - 20, H / 2 + 18)])
|
| 202 |
+
elif shape == 'crowbar':
|
| 203 |
+
t, r = (12, (H - 2 * m - 24) / 2)
|
| 204 |
+
cx, cy = (m + r + t + 4, H - m - t - r)
|
| 205 |
+
line = [(W - m - t, H - m - t), (cx, H - m - t)]
|
| 206 |
+
line += [(cx - r * math.sin(math.radians(a)), cy + r * math.cos(math.radians(a))) for a in range(15, 181, 15)]
|
| 207 |
+
line.append((line[-1][0] + 30, line[-1][1]))
|
| 208 |
+
|
| 209 |
+
def side(sign):
|
| 210 |
+
out = []
|
| 211 |
+
for k, (x, y) in enumerate(line):
|
| 212 |
+
(ax, ay), (bx, by) = (line[max(0, k - 1)], line[min(len(line) - 1, k + 1)])
|
| 213 |
+
n = math.hypot(bx - ax, by - ay) or 1
|
| 214 |
+
out.append((x - sign * t * (by - ay) / n, y + sign * t * (bx - ax) / n))
|
| 215 |
+
return out
|
| 216 |
+
dash(side(1) + side(-1)[::-1])
|
| 217 |
+
elif shape == 'hook':
|
| 218 |
+
dash([(W / 2, m), (W / 2, H - m - 30), (W / 2 + 30, H - m)], closed=False)
|
| 219 |
+
else:
|
| 220 |
+
dash([(m, m), (W - m, m), (W - m, H - m), (m, H - m)])
|
| 221 |
+
return im
|
| 222 |
+
|
| 223 |
+
def note_image(text, w_px=900, h_px=170):
|
| 224 |
+
im, d = canvas(w_px, h_px, (238, 232, 214))
|
| 225 |
+
d.rectangle([6, 6, w_px - 6, h_px - 6], outline=INK, width=5)
|
| 226 |
+
size = 76
|
| 227 |
+
while d.textlength(text, font=font(size)) > w_px - 60 and size > 30:
|
| 228 |
+
size -= 4
|
| 229 |
+
d.text((w_px / 2, h_px / 2), text, font=font(size), fill=INK, anchor='mm')
|
| 230 |
+
return im
|
| 231 |
+
|
| 232 |
+
def mark_image(kind):
|
| 233 |
+
im, d = canvas(240, 240, (232, 196, 40))
|
| 234 |
+
if kind == 'turn':
|
| 235 |
+
arc_arrow(d, [44, 44, 196, 196], 200, 520, INK, width=20, head=40)
|
| 236 |
+
elif kind == 'flip':
|
| 237 |
+
d.line([(50, 92), (178, 92)], fill=INK, width=18)
|
| 238 |
+
d.polygon([(200, 92), (166, 64), (166, 120)], fill=INK)
|
| 239 |
+
d.line([(62, 150), (190, 150)], fill=INK, width=18)
|
| 240 |
+
d.polygon([(40, 150), (74, 122), (74, 178)], fill=INK)
|
| 241 |
+
elif kind == 'slide':
|
| 242 |
+
d.line([(60, 120), (180, 120)], fill=INK, width=20)
|
| 243 |
+
d.polygon([(30, 120), (70, 86), (70, 154)], fill=INK)
|
| 244 |
+
d.polygon([(210, 120), (170, 86), (170, 154)], fill=INK)
|
| 245 |
+
elif kind == 'pull':
|
| 246 |
+
d.line([(120, 40), (120, 150)], fill=INK, width=22)
|
| 247 |
+
d.polygon([(120, 205), (80, 140), (160, 140)], fill=INK)
|
| 248 |
+
return im
|
| 249 |
+
|
| 250 |
+
def arc_arrow(d, box, start, end, fill, width=10, head=28):
|
| 251 |
+
d.arc(box, min(start, end), max(start, end), fill=fill, width=width)
|
| 252 |
+
cx, cy = ((box[0] + box[2]) / 2, (box[1] + box[3]) / 2)
|
| 253 |
+
rx, ry = ((box[2] - box[0]) / 2 - width / 2, (box[3] - box[1]) / 2 - width / 2)
|
| 254 |
+
t = math.radians(end)
|
| 255 |
+
px, py = (cx + rx * math.cos(t), cy + ry * math.sin(t))
|
| 256 |
+
sgn = 1 if end > start else -1
|
| 257 |
+
tx, ty = (-rx * math.sin(t) * sgn, ry * math.cos(t) * sgn)
|
| 258 |
+
n = math.hypot(tx, ty) or 1
|
| 259 |
+
ux, uy = (tx / n, ty / n)
|
| 260 |
+
d.polygon([(px + ux * head, py + uy * head), (px - uy * head * 0.6, py + ux * head * 0.6), (px + uy * head * 0.6, py - ux * head * 0.6)], fill=fill)
|
| 261 |
+
|
| 262 |
+
def save_png(scene, im, prefix='img'):
|
| 263 |
+
data = im.tobytes() + repr(im.size).encode()
|
| 264 |
+
p = scene.tex / (prefix + '_' + hashlib.sha256(data).hexdigest()[:20] + '.png')
|
| 265 |
+
if not p.exists():
|
| 266 |
+
im.save(p)
|
| 267 |
+
return p
|
| 268 |
+
|
| 269 |
+
def _room_art():
|
| 270 |
+
from room_art364 import RoomArt
|
| 271 |
+
return RoomArt
|
| 272 |
+
|
| 273 |
+
class V6Scene:
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
def make_scene_class(level_scene):
|
| 277 |
+
RoomArt = _room_art()
|
| 278 |
+
|
| 279 |
+
class Base(RoomArt):
|
| 280 |
+
WALL_A = (0.3, 0.36, 0.35)
|
| 281 |
+
WALL_B = (0.36, 0.31, 0.25)
|
| 282 |
+
FLOOR_A = None
|
| 283 |
+
FLOOR_B = None
|
| 284 |
+
ROOM_NAMES = ('', '')
|
| 285 |
+
|
| 286 |
+
def __init__(self, og, run):
|
| 287 |
+
super().__init__(og, run)
|
| 288 |
+
self.labels = {'exit': 'exit door', 'exit_lock': 'exit code keypad'}
|
| 289 |
+
self.shown = {}
|
| 290 |
+
self.screens = {}
|
| 291 |
+
self.hinges = {}
|
| 292 |
+
self.slides = {}
|
| 293 |
+
self.dynamic = []
|
| 294 |
+
self.custom = {}
|
| 295 |
+
self._collision_cache = None
|
| 296 |
+
self.spec = {'stages': []}
|
| 297 |
+
self.stage_centres = []
|
| 298 |
+
|
| 299 |
+
def group(self, key, pos=(0, 0, 0), parent=None):
|
| 300 |
+
base = str(parent['prim'].GetPath()) if parent else '/World/redesign364'
|
| 301 |
+
used = self.__dict__.setdefault('_group_paths', set())
|
| 302 |
+
name, n = (key, 1)
|
| 303 |
+
while base + '/' + name in used:
|
| 304 |
+
n += 1
|
| 305 |
+
name = '%s_%d' % (key, n)
|
| 306 |
+
used.add(base + '/' + name)
|
| 307 |
+
return super().group(name, pos, parent)
|
| 308 |
+
|
| 309 |
+
def palette(self):
|
| 310 |
+
super().palette()
|
| 311 |
+
for name, color, rough in [('cream', (0.7, 0.68, 0.6), 0.95), ('ivory', (0.75, 0.72, 0.62), 0.95), ('dark_panel', (0.035, 0.05, 0.06), 0.6), ('blue', (0.1, 0.22, 0.42), 0.7), ('copper', (0.62, 0.32, 0.16), 0.4), ('green_paint', (0.16, 0.3, 0.22), 0.8), ('red_paint', (0.48, 0.1, 0.07), 0.7), ('white', (0.85, 0.85, 0.82), 0.7), ('ceramic', (0.86, 0.84, 0.78), 0.25), ('teal', (0.12, 0.36, 0.38), 0.7), ('black', (0.03, 0.03, 0.03), 0.6), ('yellow', (0.78, 0.62, 0.12), 0.7), ('felt', (0.2, 0.3, 0.26), 1.0)]:
|
| 312 |
+
self.mat(name, color, rough=rough)
|
| 313 |
+
self.mat('led_off', (0.06, 0.05, 0.04), rough=0.4)
|
| 314 |
+
self.mat('led_on', (0.9, 0.7, 0.3), rough=0.3, emission=(4.0, 2.6, 0.9))
|
| 315 |
+
self.mat('led_green', (0.2, 0.8, 0.3), rough=0.3, emission=(0.4, 2.5, 0.6))
|
| 316 |
+
self.mat('led_red', (0.8, 0.15, 0.1), rough=0.3, emission=(2.5, 0.25, 0.15))
|
| 317 |
+
|
| 318 |
+
def image_mat(self, key, path):
|
| 319 |
+
m = self.mat(key, texture=path, rough=1.0)
|
| 320 |
+
with self.og.sim.editing_usd():
|
| 321 |
+
s = self.S.Shader(self.stage.GetPrimAtPath(str(m.GetPath()) + '/surface'))
|
| 322 |
+
t = self.S.Shader(self.stage.GetPrimAtPath(str(m.GetPath()) + '/texture'))
|
| 323 |
+
s.GetInput('diffuseColor').DisconnectSource()
|
| 324 |
+
s.GetInput('diffuseColor').Set(self.F.Vec3f(0, 0, 0))
|
| 325 |
+
s.CreateInput('useSpecularWorkflow', self.D.ValueTypeNames.Int).Set(1)
|
| 326 |
+
s.CreateInput('specularColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(0, 0, 0))
|
| 327 |
+
t.CreateInput('scale', self.D.ValueTypeNames.Float4).Set(self.F.Vec4f(0.65, 0.65, 0.65, 1))
|
| 328 |
+
t.CreateInput('sourceColorSpace', self.D.ValueTypeNames.Token).Set('sRGB')
|
| 329 |
+
s.CreateInput('emissiveColor', self.D.ValueTypeNames.Color3f).ConnectToSource(t.ConnectableAPI(), 'rgb')
|
| 330 |
+
return m
|
| 331 |
+
|
| 332 |
+
def reg(self, key, node, label=None):
|
| 333 |
+
self.add_target(key, node)
|
| 334 |
+
if label:
|
| 335 |
+
self.labels[key] = label
|
| 336 |
+
return node
|
| 337 |
+
|
| 338 |
+
def show(self, node, on):
|
| 339 |
+
on = bool(on)
|
| 340 |
+
if self.shown.get(id(node)) is not on:
|
| 341 |
+
self.visibility(node, on)
|
| 342 |
+
self.shown[id(node)] = on
|
| 343 |
+
|
| 344 |
+
def centre(self, key):
|
| 345 |
+
return centre_of(self, key)
|
| 346 |
+
|
| 347 |
+
def label_for(self, key):
|
| 348 |
+
return self.labels.get(key, key.replace('_', ' '))
|
| 349 |
+
|
| 350 |
+
def enabled(self, key, g):
|
| 351 |
+
return True
|
| 352 |
+
|
| 353 |
+
def visible(self, key, g):
|
| 354 |
+
node = self.target_nodes.get(key)
|
| 355 |
+
return node is not None and key not in g.holding and self.shown.get(id(node), True) and self.enabled(key, g)
|
| 356 |
+
|
| 357 |
+
def candidates(self, g):
|
| 358 |
+
return self.base_candidates([k for k in self.target_nodes if self.visible(k, g)])
|
| 359 |
+
|
| 360 |
+
def picture(self, key, im, c, w, h, facing='north', parent=None, frame=0.03, frame_mat='darkwood', spin=0.0):
|
| 361 |
+
right, up = (np.array(v, float) for v in FACING[facing])
|
| 362 |
+
if spin:
|
| 363 |
+
a = math.radians(spin)
|
| 364 |
+
right, up = (right * math.cos(a) - up * math.sin(a), up * math.cos(a) + right * math.sin(a))
|
| 365 |
+
frame = 0
|
| 366 |
+
p = save_png(self, im, key)
|
| 367 |
+
mat = self.image_mat('pic_' + p.stem, p)
|
| 368 |
+
n = np.array(NORMAL[facing], float)
|
| 369 |
+
if frame:
|
| 370 |
+
depth = 0.02
|
| 371 |
+
back = np.array(c, float) - n * depth / 2
|
| 372 |
+
size = np.abs(np.array(right)) * (w + 2 * frame) + np.abs(np.array(up)) * (h + 2 * frame) + np.abs(n) * depth
|
| 373 |
+
self.box(key + '_frame', back.tolist(), size.tolist(), frame_mat, parent, bevel=0.004)
|
| 374 |
+
return self.plane(key, (np.array(c, float) + n * 0.002).tolist(), w, h, right, up, None, parent, material=mat)
|
| 375 |
+
|
| 376 |
+
def outline(self, key, shape, c, w, h, facing='north', parent=None, bg=(70, 74, 76), ink=(250, 250, 244)):
|
| 377 |
+
px = (max(60, int(w * 1200)), max(60, int(h * 1200)))
|
| 378 |
+
return self.picture(key, outline_image(shape, px[0], px[1], ink=ink, bg=bg), c, w, h, facing, parent, frame=0)
|
| 379 |
+
|
| 380 |
+
def mark(self, key, kind, c, r=0.022, facing='north', parent=None, spin=0.0):
|
| 381 |
+
return self.disc(key + '_mark_' + kind, mark_image(kind), c, r, facing, parent, spin=spin)
|
| 382 |
+
|
| 383 |
+
def disc(self, key, im, c, r, facing='north', parent=None, spin=0.0, n=48):
|
| 384 |
+
right, up = (np.array(v, float) for v in FACING[facing])
|
| 385 |
+
a = math.radians(spin)
|
| 386 |
+
right, up = (right * math.cos(a) - up * math.sin(a), up * math.cos(a) + right * math.sin(a))
|
| 387 |
+
centre = np.array(c, float) + np.array(NORMAL[facing], float) * 0.002
|
| 388 |
+
pts = [centre.tolist()] + [(centre + r * (math.cos(2 * math.pi * k / n) * right + math.sin(2 * math.pi * k / n) * up)).tolist() for k in range(n)]
|
| 389 |
+
faces = [[0, 1 + k, 1 + (k + 1) % n] for k in range(n)]
|
| 390 |
+
uvp = [(0.5, 0.5)] + [(0.5 + 0.5 * math.cos(2 * math.pi * k / n), 0.5 + 0.5 * math.sin(2 * math.pi * k / n)) for k in range(n)]
|
| 391 |
+
p = save_png(self, im, key)
|
| 392 |
+
mat = self.image_mat('pic_' + p.stem, p)
|
| 393 |
+
return self.mesh(key, pts, faces, mat, parent, uv=[uvp[i] for f in faces for i in f])
|
| 394 |
+
|
| 395 |
+
def screen(self, key, im, c, w, h, facing='north', parent=None, round_=False):
|
| 396 |
+
sig = hashlib.sha256(im.tobytes()).hexdigest()
|
| 397 |
+
slot = self.screens.setdefault(key, {'faces': {}, 'current': None})
|
| 398 |
+
if slot['current'] == sig:
|
| 399 |
+
return slot['faces'][sig]
|
| 400 |
+
if sig not in slot['faces']:
|
| 401 |
+
slot['faces'][sig] = self.disc(key + '_' + sig[:10], im, c, w / 2, facing, parent) if round_ else self.picture(key + '_' + sig[:10], im, c, w, h, facing, parent, frame=0)
|
| 402 |
+
for s, node in slot['faces'].items():
|
| 403 |
+
self.show(node, s == sig)
|
| 404 |
+
slot['current'] = sig
|
| 405 |
+
return slot['faces'][sig]
|
| 406 |
+
|
| 407 |
+
def root(self, key, x, y, wall='north', z=0.0):
|
| 408 |
+
g = self.group(key, [x, y, z])
|
| 409 |
+
self.transform(g, rpy=[0, 0, WALL_YAW[wall]])
|
| 410 |
+
return g
|
| 411 |
+
|
| 412 |
+
def body(self, key, w, d, h, mat='paint', parent=None, z0=0.0, open_front=True, legs=0.0):
|
| 413 |
+
t = 0.025
|
| 414 |
+
zb = z0 + legs
|
| 415 |
+
self.box(key + '_back', [0, d / 2 - t / 2, zb + h / 2], [w, t, h], mat, parent)
|
| 416 |
+
for sx in (-1, 1):
|
| 417 |
+
self.box(key + '_side', [sx * (w / 2 - t / 2), 0, zb + h / 2], [t, d, h], mat, parent)
|
| 418 |
+
self.box(key + '_top', [0, 0, zb + h - t / 2], [w, d, t], mat, parent)
|
| 419 |
+
self.box(key + '_bottom', [0, 0, zb + t / 2], [w, d, t], mat, parent)
|
| 420 |
+
if legs:
|
| 421 |
+
for sx in (-1, 1):
|
| 422 |
+
for sy in (-1, 1):
|
| 423 |
+
self.box(key + '_leg', [sx * (w / 2 - 0.04), sy * (d / 2 - 0.04), z0 + legs / 2], [0.04, 0.04, legs], 'iron', parent)
|
| 424 |
+
if not open_front:
|
| 425 |
+
self.box(key + '_front', [0, -d / 2 + t / 2, zb + h / 2], [w, t, h], mat, parent)
|
| 426 |
+
|
| 427 |
+
def shelf(self, key, w, d, z, parent=None, mat='wood'):
|
| 428 |
+
return self.box(key, [0, 0, z], [w, d, 0.025], mat, parent)
|
| 429 |
+
|
| 430 |
+
def hinged_door(self, key, parent, hinge, w, h, side='left', mat='paint', thick=0.025, handle=True, open_deg=105):
|
| 431 |
+
g = self.group(key, hinge, parent)
|
| 432 |
+
sx = 1 if side == 'left' else -1
|
| 433 |
+
self.box(key + '_leaf', [sx * w / 2, -thick / 2, h / 2], [w, thick, h], mat, g, bevel=0.006)
|
| 434 |
+
if handle:
|
| 435 |
+
self.box(key + '_handle', [sx * (w - 0.06), -thick - 0.02, h / 2], [0.025, 0.03, 0.14], 'brass', g)
|
| 436 |
+
self.hinges[key] = (g, 0.0, sx * -open_deg)
|
| 437 |
+
return g
|
| 438 |
+
|
| 439 |
+
def drawer(self, key, parent, c, w, d, h, mat='paint', pull=0.32):
|
| 440 |
+
g = self.group(key, c, parent)
|
| 441 |
+
t = 0.018
|
| 442 |
+
self.box(key + '_front', [0, -d / 2, 0], [w + 0.02, t * 1.4, h], mat, g)
|
| 443 |
+
self.box(key + '_handle', [0, -d / 2 - 0.025, 0], [min(0.16, w * 0.5), 0.025, 0.025], 'brass', g)
|
| 444 |
+
self.box(key + '_floor', [0, 0, -h / 2 + t / 2], [w, d, t], 'wood', g)
|
| 445 |
+
for sx in (-1, 1):
|
| 446 |
+
self.box(key + '_wall', [sx * (w / 2 - t / 2), 0, 0], [t, d, h * 0.8], 'wood', g)
|
| 447 |
+
self.box(key + '_rear', [0, d / 2 - t / 2, 0], [w, t, h * 0.8], 'wood', g)
|
| 448 |
+
self.slides[key] = (g, list(c), pull)
|
| 449 |
+
return g
|
| 450 |
+
|
| 451 |
+
def knob(self, key, parent, c, r=0.05, mat='black', axis='y'):
|
| 452 |
+
g = self.group(key, c, parent)
|
| 453 |
+
self.cylinder(key + '_body', [0, 0, 0], r, 0.04, mat, axis, g, n=24)
|
| 454 |
+
return g
|
| 455 |
+
|
| 456 |
+
def lamp(self, key, parent, c, r=0.025):
|
| 457 |
+
off = self.cylinder(key + '_off', c, r, 0.02, 'led_off', 'y', parent)
|
| 458 |
+
on = self.cylinder(key + '_on', [c[0], c[1] - 0.004, c[2]], r, 0.02, 'led_on', 'y', parent)
|
| 459 |
+
self.custom[key] = (off, on)
|
| 460 |
+
return (off, on)
|
| 461 |
+
|
| 462 |
+
def set_lamp(self, key, on):
|
| 463 |
+
off, lit = self.custom[key]
|
| 464 |
+
self.show(off, not on)
|
| 465 |
+
self.show(lit, on)
|
| 466 |
+
|
| 467 |
+
def shell(self):
|
| 468 |
+
names = self.ROOM_NAMES
|
| 469 |
+
wood = self.mats['wood']
|
| 470 |
+
for room, origin, openings, wall, floor in [('room_A', (0, 0), {'east': [PASSAGE]}, self.WALL_A, self.FLOOR_A), ('room_B', (4.8, 0), {'west': [PASSAGE], 'east': [(0.65, 1.72)]}, self.WALL_B, self.FLOOR_B)]:
|
| 471 |
+
self.mats['paint'] = self.mat(room + '_wall_paint', wall, rough=0.88)
|
| 472 |
+
if floor is not None:
|
| 473 |
+
self.mats['wood'] = self.mat(room + '_floor', texture=self.tex / 'wood.png', rough=0.7) if floor == 'wood' else self.mat(room + '_floor', floor, rough=0.9)
|
| 474 |
+
self.room_shell(room, origin, (4.8, 5.0), openings=openings)
|
| 475 |
+
self.mats['wood'] = wood
|
| 476 |
+
self.mats['paint'] = self.mat('furniture_paint', (0.3, 0.36, 0.37), rough=0.85)
|
| 477 |
+
self.box('foundation', [4.8, 2.5, -0.08], [9.76, 5.16, 0.1], 'darkwood')
|
| 478 |
+
if names[0]:
|
| 479 |
+
self.label('room_A_name', names[0], [2.4, 4.935, 2.3], 1.2, 0.14)
|
| 480 |
+
if names[1]:
|
| 481 |
+
self.label('room_B_name', names[1], [7.2, 4.935, 2.3], 1.2, 0.14)
|
| 482 |
+
|
| 483 |
+
def exit_door(self):
|
| 484 |
+
self.exit_node = self.door('exit_leaf', [9.53, 0.68, 0], 1.04)
|
| 485 |
+
self.transform(self.exit_node, rpy=[0, 0, 90])
|
| 486 |
+
self.reg('exit', self.exit_node)
|
| 487 |
+
for y in (0.62, 1.78):
|
| 488 |
+
self.box('exit_frame', [9.5, y, 1.15], [0.14, 0.07, 2.3], 'darkwood')
|
| 489 |
+
self.box('exit_lintel', [9.5, 1.2, 2.32], [0.14, 1.23, 0.07], 'darkwood')
|
| 490 |
+
pad = self.group('exit_keypad', [9.51, 2.05, 1.22])
|
| 491 |
+
self.box('keypad_body', [0, 0, 0], [0.05, 0.19, 0.27], 'iron', pad)
|
| 492 |
+
self.label('keypad_title', 'EXIT CODE', [-0.027, 0, 0.108], 0.16, 0.028, right=(0, -1, 0), up=(0, 0, 1), parent=pad)
|
| 493 |
+
for j, v in enumerate('123456789*0#'):
|
| 494 |
+
r, c = divmod(j, 3)
|
| 495 |
+
y, z = ((c - 1) * 0.05, -0.02 - r * 0.032)
|
| 496 |
+
self.box('keypad_key', [-0.03, y, z], [0.012, 0.036, 0.026], 'cream', pad)
|
| 497 |
+
self.label('keypad_digit', v, [-0.037, y, z], 0.02, 0.02, right=(0, -1, 0), up=(0, 0, 1), parent=pad)
|
| 498 |
+
self.keypad = pad
|
| 499 |
+
self.reg('exit_lock', pad)
|
| 500 |
+
|
| 501 |
+
def lcd(self, value):
|
| 502 |
+
im = Image.new('RGB', (400, 110), (44, 62, 52))
|
| 503 |
+
d = ImageDraw.Draw(im)
|
| 504 |
+
d.text((200, 55), str(value), font=font(78), anchor='mm', fill=(215, 226, 185))
|
| 505 |
+
return im
|
| 506 |
+
|
| 507 |
+
def obstacle_of(self, node, pad=0.0):
|
| 508 |
+
p = self.triangles(node).reshape(-1, 3)
|
| 509 |
+
lo, hi = (p.min(0), p.max(0))
|
| 510 |
+
self.add_obstacle(lo[0] - pad, lo[1] - pad, hi[0] + pad, hi[1] + pad)
|
| 511 |
+
|
| 512 |
+
def blocked(self, x, y, g):
|
| 513 |
+
if self.static_blocked(x, y):
|
| 514 |
+
return True
|
| 515 |
+
if not (0.18 < x < 9.42 and 0.18 < y < 4.82):
|
| 516 |
+
return True
|
| 517 |
+
sig = tuple(sorted((k for k, (_, fn) in self.dyn_items() if fn(g))))
|
| 518 |
+
if self._collision_cache is None or self._collision_cache[0] != sig:
|
| 519 |
+
boxes = []
|
| 520 |
+
for k, (node, fn) in self.dyn_items():
|
| 521 |
+
if fn(g):
|
| 522 |
+
p = self.triangles(node).reshape(-1, 3)
|
| 523 |
+
boxes.append((p.min(0), p.max(0)))
|
| 524 |
+
self._collision_cache = (sig, boxes)
|
| 525 |
+
return any((lo[0] - 0.12 < x < hi[0] + 0.12 and lo[1] - 0.12 < y < hi[1] + 0.12 and (lo[2] < 1.6) for lo, hi in self._collision_cache[1]))
|
| 526 |
+
|
| 527 |
+
def dyn_items(self):
|
| 528 |
+
return [(k, v) for k, v in enumerate(self.dynamic)]
|
| 529 |
+
|
| 530 |
+
def build(self, g):
|
| 531 |
+
self.labels.update(g.LABELS)
|
| 532 |
+
self.shell()
|
| 533 |
+
self.exit_door()
|
| 534 |
+
self.layout(g)
|
| 535 |
+
self.sync(g)
|
| 536 |
+
|
| 537 |
+
def layout(self, g):
|
| 538 |
+
pass
|
| 539 |
+
|
| 540 |
+
def update(self, g):
|
| 541 |
+
pass
|
| 542 |
+
|
| 543 |
+
def door_open(self, key, g):
|
| 544 |
+
return False
|
| 545 |
+
|
| 546 |
+
def sync(self, g):
|
| 547 |
+
self._collision_cache = None
|
| 548 |
+
self.transform(self.exit_node, rpy=[0, 0, 90 + (100 if g.opened['exit'] else 0)])
|
| 549 |
+
self.screen('exit_lcd', self.lcd(g.possessions.get('door_input', '____')), [-0.027, 0, 0.065], 0.15, 0.04, 'east', self.keypad)
|
| 550 |
+
for key, (node, closed, opened) in self.hinges.items():
|
| 551 |
+
self.transform(node, rpy=[0, 0, opened if self.door_open(key, g) else closed])
|
| 552 |
+
for key, (node, c, pull) in self.slides.items():
|
| 553 |
+
self.transform(node, pos=[c[0], c[1] - (pull if self.door_open(key, g) else 0.0), c[2]])
|
| 554 |
+
self.update(g)
|
| 555 |
+
NO_TWEEN = ()
|
| 556 |
+
|
| 557 |
+
def animate(self, d, before):
|
| 558 |
+
vis0 = dict(self.shown)
|
| 559 |
+
rec = {}
|
| 560 |
+
base_transform = self.transform
|
| 561 |
+
|
| 562 |
+
def spy(group, pos=None, rpy=None):
|
| 563 |
+
if id(group) not in rec:
|
| 564 |
+
rec[id(group)] = (group, tuple(group['translate'].Get()), tuple(group['rotate'].Get()))
|
| 565 |
+
base_transform(group, pos, rpy)
|
| 566 |
+
self.transform = spy
|
| 567 |
+
try:
|
| 568 |
+
self.sync(d.game)
|
| 569 |
+
finally:
|
| 570 |
+
del self.transform
|
| 571 |
+
skip = {id(self.exit_node)}
|
| 572 |
+
for k in self.NO_TWEEN:
|
| 573 |
+
v = self.custom.get(k)
|
| 574 |
+
for n in v if isinstance(v, (list, tuple)) else v.values() if isinstance(v, dict) else [v]:
|
| 575 |
+
if isinstance(n, dict):
|
| 576 |
+
skip.add(id(n))
|
| 577 |
+
moves = []
|
| 578 |
+
for key, (grp, p0, r0) in rec.items():
|
| 579 |
+
p1, r1 = (tuple(grp['translate'].Get()), tuple(grp['rotate'].Get()))
|
| 580 |
+
dp = math.dist(p0, p1)
|
| 581 |
+
dr = max((abs(a - b) for a, b in zip(r0, r1)))
|
| 582 |
+
visible = vis0.get(key, True) and self.shown.get(key, True)
|
| 583 |
+
if key not in skip and visible and (dp < 0.6) and (dp > 0.0001 or dr > 0.5):
|
| 584 |
+
moves.append((grp, p0, r0, p1, r1))
|
| 585 |
+
if moves:
|
| 586 |
+
for f in (1 / 3, 2 / 3):
|
| 587 |
+
for grp, p0, r0, p1, r1 in moves:
|
| 588 |
+
base_transform(grp, [a + (b - a) * f for a, b in zip(p0, p1)], [a + (b - a) * f for a, b in zip(r0, r1)])
|
| 589 |
+
d.frame(warm=4)
|
| 590 |
+
d.append('mechanism moves', 3)
|
| 591 |
+
for grp, p0, r0, p1, r1 in moves:
|
| 592 |
+
base_transform(grp, list(p1), list(r1))
|
| 593 |
+
if hasattr(self, 'motion'):
|
| 594 |
+
self.motion(d, before)
|
| 595 |
+
if before['opened']['exit'] != d.game.opened['exit']:
|
| 596 |
+
for f in (0.25, 0.5, 0.75):
|
| 597 |
+
self.transform(self.exit_node, rpy=[0, 0, 90 + 100 * (f if d.game.opened['exit'] else 1 - f)])
|
| 598 |
+
d.frame(warm=4)
|
| 599 |
+
d.append('exit door moves', 3)
|
| 600 |
+
self.sync(d.game)
|
| 601 |
+
attrs = {k: v for k, v in level_scene.__dict__.items() if not k.startswith('__')}
|
| 602 |
+
return type(level_scene.__name__, (Base,), attrs)
|
| 603 |
+
|
| 604 |
+
def scene_factory(level_scene):
|
| 605 |
+
cache = {}
|
| 606 |
+
|
| 607 |
+
def Scene(og, run):
|
| 608 |
+
if 'cls' not in cache:
|
| 609 |
+
cache['cls'] = make_scene_class(level_scene)
|
| 610 |
+
return cache['cls'](og, run)
|
| 611 |
+
return Scene
|
| 612 |
+
|
| 613 |
+
def go(d, xy):
|
| 614 |
+
d.route(list(xy))
|
| 615 |
+
|
| 616 |
+
def look(d, point):
|
| 617 |
+
d.aim(list(point), 'look at the work area')
|
| 618 |
+
|
| 619 |
+
def click(d, key, verb='press', item=None, **kw):
|
| 620 |
+
if key in d.scene.target_nodes:
|
| 621 |
+
c = d.scene.centre(key)
|
| 622 |
+
dx, dy, dz = (c[0] - d.pos[0], c[1] - d.pos[1], c[2] - d.pos[2])
|
| 623 |
+
yaw = math.atan2(dy, dx)
|
| 624 |
+
pitch = math.atan2(dz, math.hypot(dx, dy))
|
| 625 |
+
off_yaw = abs((yaw - d.yaw + math.pi) % (2 * math.pi) - math.pi)
|
| 626 |
+
if max(off_yaw, abs(pitch - d.pitch)) > math.radians(15):
|
| 627 |
+
look(d, c)
|
| 628 |
+
return d.click(key, verb, item=item, **kw)
|
| 629 |
+
|
| 630 |
+
def observe(d, name, point=None):
|
| 631 |
+
if point is not None:
|
| 632 |
+
look(d, point)
|
| 633 |
+
path = Path(d.run) / 'screenshots' / ('clue_' + str(name) + '_native.png')
|
| 634 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 635 |
+
d.clean.save(path)
|
| 636 |
+
d.append('observe ' + str(name), 18)
|
| 637 |
+
rows = getattr(d, 'cross_room_observations', [])
|
| 638 |
+
rows.append({'name': 'clue_' + str(name), 'path': str(path), 'step': d.step, 'native': True})
|
| 639 |
+
d.cross_room_observations = rows
|
| 640 |
+
d.save('CROSS_ROOM_OBSERVATIONS.json', rows)
|
| 641 |
+
|
| 642 |
+
def finish(d):
|
| 643 |
+
go(d, DOOR_VIEW)
|
| 644 |
+
look(d, d.scene.centre('exit_lock'))
|
| 645 |
+
click(d, 'exit_lock', 'unlock', code=d.game.SPEC['door_code'])
|
| 646 |
+
look(d, [9.5, 1.2, 1.2])
|
| 647 |
+
click(d, 'exit', 'open')
|
| 648 |
+
|
| 649 |
+
def centre_of(scene, key):
|
| 650 |
+
p = scene.triangles(scene.target_nodes[key]).reshape(-1, 3)
|
| 651 |
+
return ((p.min(0) + p.max(0)) / 2).tolist()
|
| 652 |
+
|
| 653 |
+
def intro_capture(d):
|
| 654 |
+
from preview_four import capture
|
| 655 |
+
capture(d)
|
| 656 |
+
|
| 657 |
+
def cpu_act(g, key, verb='press', item=None, **kw):
|
| 658 |
+
a = {'action': verb, '_validated364': True, '_hit364': key, 'item': item or ''}
|
| 659 |
+
a.update(kw)
|
| 660 |
+
return g.act(a)['ok']
|
runtime/h2_runtime/model_content554.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import json, base64
|
| 4 |
+
from observation1280 import WIDTH, HEIGHT, rules_for_budget
|
| 5 |
+
ACTION_FIELDS = ('action', 'distance', 'direction', 'degrees', 'part', 'code', 'point', 'photo', 'target', 'item', 'query')
|
| 6 |
+
|
| 7 |
+
def _paths(row, decision=False):
|
| 8 |
+
if decision:
|
| 9 |
+
value = row.get('decision_images') or ([row['decision_image']] if row.get('decision_image') else None)
|
| 10 |
+
if value:
|
| 11 |
+
return tuple((Path(p) for p in value))
|
| 12 |
+
return tuple((Path(p) for p in row.get('images') or ([row['image']] if row.get('image') else [])))
|
| 13 |
+
|
| 14 |
+
def _body(row):
|
| 15 |
+
action = {k: v for k, v in row.get('action', {}).items() if k in ACTION_FIELDS}
|
| 16 |
+
feedback = row.get('feedback', row.get('result', ''))
|
| 17 |
+
if isinstance(feedback, dict):
|
| 18 |
+
feedback = feedback.get('text', '')
|
| 19 |
+
return json.dumps(action, ensure_ascii=False) + ' -> ' + str(feedback or '')
|
| 20 |
+
|
| 21 |
+
def build_prompt_parts(packet, include_recent=True):
|
| 22 |
+
cap = int(packet.get('action_limit', 80))
|
| 23 |
+
holding = ', '.join(packet.get('holding', [])) or 'nothing'
|
| 24 |
+
notes = packet.get('notes', [])
|
| 25 |
+
note_text = '\nYour notes:\n' + ('\n'.join((f"{n['number']}. [step {n['step']}] {n['text']}" for n in notes)) if notes else '(none yet)')
|
| 26 |
+
header = rules_for_budget(cap) + f"\n\nYou are holding: {holding}.\nActions left: {packet.get('actions_left', max(0, cap - int(packet.get('step', 0))))}.\nRecalls left: {packet.get('recalls_left', 8)}.\n" + note_text + '\n\nYour last 10 steps:'
|
| 27 |
+
parts = [header]
|
| 28 |
+
now = _paths(packet)
|
| 29 |
+
shown = {}
|
| 30 |
+
recent = packet.get('recent', [])[-10:] if include_recent else []
|
| 31 |
+
if not recent:
|
| 32 |
+
parts.append('\n(none yet)')
|
| 33 |
+
for row in recent:
|
| 34 |
+
views = _paths(row, decision=True)
|
| 35 |
+
step = row['step']
|
| 36 |
+
body = _body(row)
|
| 37 |
+
if not views:
|
| 38 |
+
parts.append(f'\n[step {step}] ' + body)
|
| 39 |
+
elif views == now:
|
| 40 |
+
parts.append(f'\n[step {step}] (same view as your current view) ' + body)
|
| 41 |
+
elif views in shown:
|
| 42 |
+
parts.append(f'\n[step {step}] (same view as step {shown[views]}) ' + body)
|
| 43 |
+
else:
|
| 44 |
+
shown[views] = step
|
| 45 |
+
parts.extend([f'\n[step {step}]\n', *views, '\n' + body])
|
| 46 |
+
recalls = packet.get('recall_log', [])
|
| 47 |
+
if recalls:
|
| 48 |
+
agg = {}
|
| 49 |
+
for r in recalls:
|
| 50 |
+
query = str(r.get('query', '')).strip()
|
| 51 |
+
if query:
|
| 52 |
+
agg[query] = (int(r.get('found', 0)), agg.get(query, (0, 0))[1] + 1)
|
| 53 |
+
if agg:
|
| 54 |
+
|
| 55 |
+
def entry(q, n, c):
|
| 56 |
+
return json.dumps(q, ensure_ascii=False) + ' -> ' + (str(n) + (' entry' if n == 1 else ' entries') if n else 'nothing found') + (f' (asked {c} times)' if c > 1 else '')
|
| 57 |
+
parts.append('\nRecalls so far this game: ' + '; '.join((entry(q, n, c) for q, (n, c) in agg.items())) + '.')
|
| 58 |
+
if packet.get('recall_requested'):
|
| 59 |
+
parts.append('\n\nResult of the recall you just made:\n' + str(packet.get('recall_feedback', '')))
|
| 60 |
+
for row in packet.get('recall', []):
|
| 61 |
+
parts.extend([f"\n [step {row['step']}]\n", *_paths(row, decision=True), '\n ' + _body(row)])
|
| 62 |
+
if now:
|
| 63 |
+
parts.extend(['\n\nYour current view:\n', *now, '\nThe last photo above is your current view; you can only act on things in it. Reply with one JSON object.'])
|
| 64 |
+
else:
|
| 65 |
+
parts.append('\n\nThere is no photo in front of you yet. Reply with one JSON object.')
|
| 66 |
+
return parts
|
| 67 |
+
|
| 68 |
+
def build_model_user_content(packet, include_recent=True):
|
| 69 |
+
content = []
|
| 70 |
+
for value in build_prompt_parts(packet, include_recent):
|
| 71 |
+
if isinstance(value, Path):
|
| 72 |
+
if value.suffix.lower() not in ('.png', '.jpg', '.jpeg'):
|
| 73 |
+
raise ValueError('Expected a local PNG/JPEG observation')
|
| 74 |
+
with Image.open(value) as im:
|
| 75 |
+
if im.size != (WIDTH, HEIGHT):
|
| 76 |
+
raise ValueError('Model input must remain1280x640; no resizing fallback')
|
| 77 |
+
mime = 'image/png' if value.suffix.lower() == '.png' else 'image/jpeg'
|
| 78 |
+
content.append({'type': 'image_url', 'image_url': {'url': 'data:' + mime + ';base64,' + base64.b64encode(value.read_bytes()).decode('ascii')}})
|
| 79 |
+
else:
|
| 80 |
+
content.append({'type': 'text', 'text': str(value)})
|
| 81 |
+
return content
|
runtime/h2_runtime/native_primitives364.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 5 |
+
from font_utils import load_font
|
| 6 |
+
|
| 7 |
+
class Art:
|
| 8 |
+
|
| 9 |
+
def __init__(self, og, run):
|
| 10 |
+
from pxr import UsdGeom, UsdShade, Gf, Sdf
|
| 11 |
+
self.og = og
|
| 12 |
+
self.stage = og.sim.stage
|
| 13 |
+
self.G = UsdGeom
|
| 14 |
+
self.S = UsdShade
|
| 15 |
+
self.F = Gf
|
| 16 |
+
self.D = Sdf
|
| 17 |
+
self.run = Path(run)
|
| 18 |
+
self.tex = self.run / 'textures'
|
| 19 |
+
self.tex.mkdir(exist_ok=True)
|
| 20 |
+
self.nodes = {}
|
| 21 |
+
self.groups = {}
|
| 22 |
+
self.mats = {}
|
| 23 |
+
self.count = 0
|
| 24 |
+
self.textures()
|
| 25 |
+
self.palette()
|
| 26 |
+
|
| 27 |
+
def textures(self):
|
| 28 |
+
rng = np.random.default_rng(361)
|
| 29 |
+
h = w = 768
|
| 30 |
+
y, x = np.mgrid[:h, :w]
|
| 31 |
+
grain = np.sin(x * 0.065 + np.sin(y * 0.007) * 5) + 0.5 * np.sin(x * 0.2 + np.sin(y * 0.012) * 3) + 0.2 * rng.normal(size=(h, w))
|
| 32 |
+
bands = 2.5 * np.sin(y * 0.004) + grain * 9
|
| 33 |
+
wood = np.clip(np.array([132, 87, 48])[None, None, :] + bands[:, :, None] * np.array([1.0, 0.78, 0.52]), 0, 255).astype('uint8')
|
| 34 |
+
Image.fromarray(wood).save(self.tex / 'wood.png')
|
| 35 |
+
wall = np.clip(np.array([151, 156, 147])[None, None, :] + rng.normal(0, 2, (h, w, 1)) + 3 * np.sin(x * 0.009)[:, :, None], 0, 255).astype('uint8')
|
| 36 |
+
Image.fromarray(wall).save(self.tex / 'plaster.png')
|
| 37 |
+
paint = np.clip(np.array([70, 96, 107])[None, None, :] + rng.normal(0, 2.2, (h, w, 1)), 0, 255).astype('uint8')
|
| 38 |
+
im = Image.fromarray(paint)
|
| 39 |
+
d = ImageDraw.Draw(im)
|
| 40 |
+
for _ in range(220):
|
| 41 |
+
a, b = rng.integers(0, 768, 2)
|
| 42 |
+
d.line((int(a), int(b), int(a + rng.integers(2, 14)), int(b + rng.integers(-3, 4))), fill=(76, 84, 82), width=1)
|
| 43 |
+
im.save(self.tex / 'paint.png')
|
| 44 |
+
from scipy.ndimage import gaussian_filter
|
| 45 |
+
grime = gaussian_filter(rng.normal(0, 1, (h, w)), 24)
|
| 46 |
+
grime = (grime - grime.mean()) / (grime.std() + 1e-06)
|
| 47 |
+
fine = rng.normal(0, 2, (h, w))
|
| 48 |
+
dirt = np.clip(np.array([147, 130, 99])[None, None, :] + grime[:, :, None] * np.array([11, 10, 8]) + fine[:, :, None], 0, 255).astype('uint8')
|
| 49 |
+
im = Image.fromarray(dirt)
|
| 50 |
+
d = ImageDraw.Draw(im)
|
| 51 |
+
for _ in range(900):
|
| 52 |
+
a, b = rng.integers(0, 768, 2)
|
| 53 |
+
rad = int(rng.integers(1, 5))
|
| 54 |
+
d.ellipse((int(a), int(b), int(a + rad), int(b + rad)), fill=(111, 99, 78))
|
| 55 |
+
im.save(self.tex / 'dust.png')
|
| 56 |
+
|
| 57 |
+
def mat(self, name, color=(0.5, 0.5, 0.5), rough=0.6, metal=0.0, texture=None, emission=None, opacity=1.0):
|
| 58 |
+
if name in self.mats:
|
| 59 |
+
return self.mats[name]
|
| 60 |
+
with self.og.sim.editing_usd():
|
| 61 |
+
p = '/World/redesign364/materials/' + name
|
| 62 |
+
m = self.S.Material.Define(self.stage, p)
|
| 63 |
+
s = self.S.Shader.Define(self.stage, p + '/surface')
|
| 64 |
+
s.CreateIdAttr('UsdPreviewSurface')
|
| 65 |
+
s.CreateInput('diffuseColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(*color))
|
| 66 |
+
s.CreateInput('roughness', self.D.ValueTypeNames.Float).Set(rough)
|
| 67 |
+
s.CreateInput('metallic', self.D.ValueTypeNames.Float).Set(metal)
|
| 68 |
+
if opacity < 1:
|
| 69 |
+
s.CreateInput('opacity', self.D.ValueTypeNames.Float).Set(opacity)
|
| 70 |
+
if name == 'dust':
|
| 71 |
+
s.CreateInput('useSpecularWorkflow', self.D.ValueTypeNames.Int).Set(1)
|
| 72 |
+
s.CreateInput('specularColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(0, 0, 0))
|
| 73 |
+
if emission:
|
| 74 |
+
s.CreateInput('emissiveColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(*emission))
|
| 75 |
+
if texture:
|
| 76 |
+
t = self.S.Shader.Define(self.stage, p + '/texture')
|
| 77 |
+
t.CreateIdAttr('UsdUVTexture')
|
| 78 |
+
t.CreateInput('file', self.D.ValueTypeNames.Asset).Set(str(texture))
|
| 79 |
+
t.CreateOutput('rgb', self.D.ValueTypeNames.Float3)
|
| 80 |
+
st = self.S.Shader.Define(self.stage, p + '/st')
|
| 81 |
+
st.CreateIdAttr('UsdPrimvarReader_float2')
|
| 82 |
+
st.CreateInput('varname', self.D.ValueTypeNames.Token).Set('st')
|
| 83 |
+
t.CreateInput('st', self.D.ValueTypeNames.Float2).ConnectToSource(st.ConnectableAPI(), 'result')
|
| 84 |
+
s.CreateInput('diffuseColor', self.D.ValueTypeNames.Color3f).ConnectToSource(t.ConnectableAPI(), 'rgb')
|
| 85 |
+
m.CreateSurfaceOutput().ConnectToSource(s.ConnectableAPI(), 'surface')
|
| 86 |
+
self.mats[name] = m
|
| 87 |
+
return m
|
| 88 |
+
|
| 89 |
+
def palette(self):
|
| 90 |
+
self.mat('wood', texture=self.tex / 'wood.png', rough=0.65)
|
| 91 |
+
self.mat('darkwood', (0.17, 0.095, 0.045), rough=0.7)
|
| 92 |
+
self.mat('paint', texture=self.tex / 'paint.png', rough=0.52, metal=0.22)
|
| 93 |
+
self.mat('plaster', texture=self.tex / 'plaster.png', rough=0.94)
|
| 94 |
+
self.mat('steel', (0.46, 0.52, 0.55), rough=0.38, metal=0.55)
|
| 95 |
+
self.mat('iron', (0.055, 0.066, 0.07), rough=0.5, metal=0.7)
|
| 96 |
+
self.mat('brass', (0.7, 0.47, 0.16), rough=0.38, metal=0.65)
|
| 97 |
+
self.mat('rubber', (0.035, 0.043, 0.045), rough=0.84)
|
| 98 |
+
self.mat('paper', (0.78, 0.74, 0.62), rough=0.95)
|
| 99 |
+
self.mat('cloth', (0.16, 0.23, 0.22), rough=0.98)
|
| 100 |
+
self.mat('red', (0.4, 0.12, 0.065), rough=0.6)
|
| 101 |
+
self.mat('bristle', (0.61, 0.43, 0.23), rough=0.94)
|
| 102 |
+
self.mat('glass', (0.15, 0.23, 0.24), rough=0.12, metal=0.1, opacity=0.12)
|
| 103 |
+
self.mat('lamp', (0.92, 0.68, 0.34), rough=0.3, emission=(3.0, 1.6, 0.55))
|
| 104 |
+
self.mat('green', (0.09, 0.25, 0.12), rough=0.3, emission=(0.08, 0.55, 0.13))
|
| 105 |
+
self.mat('dust', texture=self.tex / 'dust.png', rough=1.0, opacity=1.0)
|
| 106 |
+
self.mat('drawer_felt', (0.24, 0.38, 0.41), rough=1.0)
|
| 107 |
+
self.mat('key_gold', (0.9, 0.57, 0.13), rough=0.44, metal=0.45)
|
| 108 |
+
|
| 109 |
+
def group(self, key, pos=(0, 0, 0), parent=None):
|
| 110 |
+
with self.og.sim.editing_usd():
|
| 111 |
+
base = str(parent['prim'].GetPath()) if parent else '/World/redesign364'
|
| 112 |
+
x = self.G.Xform.Define(self.stage, base + '/' + key)
|
| 113 |
+
t = x.AddTranslateOp()
|
| 114 |
+
t.Set(self.F.Vec3d(*pos))
|
| 115 |
+
rot = x.AddRotateXYZOp()
|
| 116 |
+
rot.Set(self.F.Vec3f(0, 0, 0))
|
| 117 |
+
node = {'prim': x.GetPrim(), 'translate': t, 'rotate': rot, 'meshes': []}
|
| 118 |
+
self.groups[key] = node
|
| 119 |
+
return node
|
| 120 |
+
|
| 121 |
+
def transform(self, group, pos=None, rpy=None):
|
| 122 |
+
with self.og.sim.editing_usd():
|
| 123 |
+
xform = self.G.Xformable(group['prim'])
|
| 124 |
+
|
| 125 |
+
def operation(key, kind, create):
|
| 126 |
+
if group.get(key) is not None:
|
| 127 |
+
return group[key]
|
| 128 |
+
ops = [op for op in xform.GetOrderedXformOps() if op.GetOpType() == kind and (not op.IsInverseOp())]
|
| 129 |
+
preferred = [op for op in ops if str(op.GetOpName()) == 'xformOp:' + key]
|
| 130 |
+
if len(preferred) == 1:
|
| 131 |
+
op = preferred[0]
|
| 132 |
+
elif len(ops) == 1:
|
| 133 |
+
op = ops[0]
|
| 134 |
+
elif ops:
|
| 135 |
+
raise ValueError('Ambiguous authored ' + key + ' xform ops')
|
| 136 |
+
else:
|
| 137 |
+
op = create()
|
| 138 |
+
group[key] = op
|
| 139 |
+
return op
|
| 140 |
+
|
| 141 |
+
def vector(op, values):
|
| 142 |
+
vector_type = self.F.Vec3d if op.GetPrecision() == self.G.XformOp.PrecisionDouble else self.F.Vec3f
|
| 143 |
+
op.Set(vector_type(*map(float, values)))
|
| 144 |
+
if pos is not None:
|
| 145 |
+
vector(operation('translate', self.G.XformOp.TypeTranslate, xform.AddTranslateOp), pos)
|
| 146 |
+
if rpy is not None:
|
| 147 |
+
vector(operation('rotate', self.G.XformOp.TypeRotateXYZ, xform.AddRotateXYZOp), rpy)
|
| 148 |
+
|
| 149 |
+
def mesh(self, key, points, faces, material='wood', parent=None, uv=None):
|
| 150 |
+
mat = self.mats[material] if isinstance(material, str) else material
|
| 151 |
+
self.count += 1
|
| 152 |
+
base = str(parent['prim'].GetPath()) if parent else '/World/redesign364/geometry'
|
| 153 |
+
path = base + '/' + key + '_' + str(self.count)
|
| 154 |
+
points = np.asarray(points, float)
|
| 155 |
+
indices = [int(i) for f in faces for i in f]
|
| 156 |
+
if uv is None:
|
| 157 |
+
lo = points.min(0)
|
| 158 |
+
size = np.maximum(points.max(0) - lo, 0.001)
|
| 159 |
+
uv = []
|
| 160 |
+
for face in faces:
|
| 161 |
+
pp = points[list(face)]
|
| 162 |
+
normal = np.abs(np.cross(pp[1] - pp[0], pp[2] - pp[0]))
|
| 163 |
+
axes = [i for i in range(3) if i != int(normal.argmax())]
|
| 164 |
+
uv.extend([((points[i, axes[0]] - lo[axes[0]]) / size[axes[0]], (points[i, axes[1]] - lo[axes[1]]) / size[axes[1]]) for i in face])
|
| 165 |
+
with self.og.sim.editing_usd():
|
| 166 |
+
m = self.G.Mesh.Define(self.stage, path)
|
| 167 |
+
m.CreatePointsAttr([self.F.Vec3f(*v) for v in points])
|
| 168 |
+
m.CreateFaceVertexCountsAttr([len(f) for f in faces])
|
| 169 |
+
m.CreateFaceVertexIndicesAttr(indices)
|
| 170 |
+
m.CreateSubdivisionSchemeAttr('none')
|
| 171 |
+
m.CreateDoubleSidedAttr(True)
|
| 172 |
+
self.G.PrimvarsAPI(m).CreatePrimvar('st', self.D.ValueTypeNames.TexCoord2fArray, self.G.Tokens.faceVarying).Set(uv)
|
| 173 |
+
self.S.MaterialBindingAPI.Apply(m.GetPrim()).Bind(mat)
|
| 174 |
+
node = {'prim': m.GetPrim(), 'points': points, 'faces': faces, 'meshes': []}
|
| 175 |
+
if parent:
|
| 176 |
+
parent['meshes'].append(node)
|
| 177 |
+
self.nodes[key] = node
|
| 178 |
+
return node
|
| 179 |
+
|
| 180 |
+
def box(self, key, c, size, mat='wood', parent=None, bevel=0.008):
|
| 181 |
+
from scipy.spatial import ConvexHull
|
| 182 |
+
c = np.asarray(c, float)
|
| 183 |
+
h = np.asarray(size, float) / 2
|
| 184 |
+
b = min(bevel, float(min(h)) * 0.35)
|
| 185 |
+
pts = []
|
| 186 |
+
for axis in range(3):
|
| 187 |
+
for sx in [-1, 1]:
|
| 188 |
+
for sy in [-1, 1]:
|
| 189 |
+
for sz in [-1, 1]:
|
| 190 |
+
v = (h - b) * np.array([sx, sy, sz])
|
| 191 |
+
v[axis] = h[axis] * [sx, sy, sz][axis]
|
| 192 |
+
pts.append(c + v)
|
| 193 |
+
pts = np.array(pts)
|
| 194 |
+
hull = ConvexHull(pts)
|
| 195 |
+
faces = []
|
| 196 |
+
for tri, eq in zip(hull.simplices, hull.equations):
|
| 197 |
+
f = list(map(int, tri))
|
| 198 |
+
p = pts[f]
|
| 199 |
+
if np.dot(np.cross(p[1] - p[0], p[2] - p[0]), eq[:3]) < 0:
|
| 200 |
+
f = f[::-1]
|
| 201 |
+
faces.append(f)
|
| 202 |
+
return self.mesh(key, pts, faces, mat, parent)
|
| 203 |
+
|
| 204 |
+
def cylinder(self, key, c, radius, length, mat='steel', axis='z', parent=None, n=18):
|
| 205 |
+
c = np.array(c, float)
|
| 206 |
+
pts = []
|
| 207 |
+
for end in [-0.5, 0.5]:
|
| 208 |
+
for i in range(n):
|
| 209 |
+
a = 2 * math.pi * i / n
|
| 210 |
+
v = np.array([radius * math.cos(a), radius * math.sin(a), length * end])
|
| 211 |
+
if axis == 'x':
|
| 212 |
+
v = v[[2, 0, 1]]
|
| 213 |
+
if axis == 'y':
|
| 214 |
+
v = v[[0, 2, 1]]
|
| 215 |
+
pts.append(c + v)
|
| 216 |
+
faces = [list(range(n - 1, -1, -1)), list(range(n, n * 2))]
|
| 217 |
+
faces += [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)]
|
| 218 |
+
return self.mesh(key, pts, faces, mat, parent)
|
| 219 |
+
|
| 220 |
+
def tube(self, key, a, b, radius=0.025, mat='steel', parent=None):
|
| 221 |
+
from scipy.spatial.transform import Rotation
|
| 222 |
+
a = np.array(a, float)
|
| 223 |
+
b = np.array(b, float)
|
| 224 |
+
delta = b - a
|
| 225 |
+
ln = np.linalg.norm(delta)
|
| 226 |
+
z = delta / ln
|
| 227 |
+
right = np.cross(z, [0, 0, 1] if abs(z[2]) < 0.95 else [0, 1, 0])
|
| 228 |
+
right /= np.linalg.norm(right)
|
| 229 |
+
up = np.cross(z, right)
|
| 230 |
+
pts = []
|
| 231 |
+
n = 16
|
| 232 |
+
for end in [a, b]:
|
| 233 |
+
for i in range(n):
|
| 234 |
+
t = 2 * math.pi * i / n
|
| 235 |
+
pts.append(end + radius * (right * math.cos(t) + up * math.sin(t)))
|
| 236 |
+
faces = [list(range(n - 1, -1, -1)), list(range(n, n * 2))] + [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)]
|
| 237 |
+
return self.mesh(key, pts, faces, mat, parent)
|
| 238 |
+
|
| 239 |
+
def plane(self, key, c, w, h, right, up, texture, parent=None, material=None):
|
| 240 |
+
c = np.array(c, float)
|
| 241 |
+
r = np.array(right, float) * w / 2
|
| 242 |
+
u = np.array(up, float) * h / 2
|
| 243 |
+
if material is None:
|
| 244 |
+
material = self.mat('image_' + key, texture=texture, rough=0.9, emission=None)
|
| 245 |
+
return self.mesh(key, [c - r - u, c + r - u, c + r + u, c - r + u], [[0, 1, 2, 3]], material, parent, uv=[(0, 0), (1, 0), (1, 1), (0, 1)])
|
| 246 |
+
|
| 247 |
+
def visibility(self, node, on):
|
| 248 |
+
with self.og.sim.editing_usd():
|
| 249 |
+
self.G.Imageable(node['prim']).GetVisibilityAttr().Set(self.G.Tokens.inherited if on else self.G.Tokens.invisible)
|
| 250 |
+
|
| 251 |
+
def triangles(self, node):
|
| 252 |
+
result = []
|
| 253 |
+
cache = self.G.XformCache()
|
| 254 |
+
meshes = node['meshes'] if node.get('meshes') else [node]
|
| 255 |
+
for mesh in meshes:
|
| 256 |
+
if 'points' not in mesh:
|
| 257 |
+
continue
|
| 258 |
+
T = cache.GetLocalToWorldTransform(mesh['prim'])
|
| 259 |
+
pts = np.array([list(T.Transform(self.F.Vec3d(*p))) for p in mesh['points']])
|
| 260 |
+
for f in mesh['faces']:
|
| 261 |
+
for i in range(1, len(f) - 1):
|
| 262 |
+
result.append(pts[[f[0], f[i], f[i + 1]]])
|
| 263 |
+
return np.array(result)
|
| 264 |
+
|
| 265 |
+
def candidate(self, key, node):
|
| 266 |
+
tri = self.triangles(node)
|
| 267 |
+
p = tri.reshape(-1, 3)
|
| 268 |
+
return {'key': key, 'room': 'workshop', 'lo': p.min(0).tolist(), 'hi': p.max(0).tolist(), 'triangles': tri.tolist()}
|
| 269 |
+
|
| 270 |
+
def label_image(self, key, text, width=800, height=200):
|
| 271 |
+
im = Image.new('RGB', (width, height), (202, 187, 152))
|
| 272 |
+
d = ImageDraw.Draw(im)
|
| 273 |
+
f = load_font(int(height * 0.35))
|
| 274 |
+
d.text((height * 0.12, height * 0.25), text, font=f, fill=(38, 48, 47))
|
| 275 |
+
p = self.tex / (key + '.png')
|
| 276 |
+
im.save(p)
|
| 277 |
+
return p
|
| 278 |
+
|
| 279 |
+
def framed(self, key, c, w, h, right, up, texture, parent=None):
|
| 280 |
+
c = np.array(c, float)
|
| 281 |
+
r = np.array(right, float)
|
| 282 |
+
u = np.array(up, float)
|
| 283 |
+
normal = np.cross(r, u)
|
| 284 |
+
if abs(normal[1]) > 0.9:
|
| 285 |
+
for i in [-1, 1]:
|
| 286 |
+
self.box(key + '_side', c + r * i * (w / 2 + 0.025), [0.045, 0.06, h + 0.1], 'darkwood', parent)
|
| 287 |
+
for i in [-1, 1]:
|
| 288 |
+
self.box(key + '_edge', c + u * i * (h / 2 + 0.025), [w + 0.1, 0.06, 0.045], 'darkwood', parent)
|
| 289 |
+
elif abs(normal[0]) > 0.9:
|
| 290 |
+
for i in [-1, 1]:
|
| 291 |
+
self.box(key + '_side', c + r * i * (w / 2 + 0.025), [0.06, 0.045, h + 0.1], 'darkwood', parent)
|
| 292 |
+
for i in [-1, 1]:
|
| 293 |
+
self.box(key + '_edge', c + u * i * (h / 2 + 0.025), [0.06, w + 0.1, 0.045], 'darkwood', parent)
|
| 294 |
+
return self.plane(key, c + normal * 0.007, w, h, right, up, texture, parent)
|
| 295 |
+
|
| 296 |
+
def tool(self, key):
|
| 297 |
+
g = self.group('tool_' + key, [0, 0, -8])
|
| 298 |
+
if key == 'hammer':
|
| 299 |
+
self.box('hammer_handle', [0, 0, -0.035], [0.034, 0.04, 0.29], 'wood', g, bevel=0.012)
|
| 300 |
+
self.box('hammer_collar', [0, 0, 0.095], [0.045, 0.05, 0.055], 'iron', g)
|
| 301 |
+
self.box('hammer_head', [0, 0, 0.13], [0.19, 0.065, 0.065], 'steel', g)
|
| 302 |
+
self.cylinder('hammer_face', [-0.115, 0, 0.13], 0.047, 0.045, 'steel', 'x', g)
|
| 303 |
+
for y in [-0.022, 0.022]:
|
| 304 |
+
self.tube('hammer_claw', [0.07, y, 0.14], [0.13, y, 0.15], 0.019, 'steel', g)
|
| 305 |
+
self.tube('hammer_claw_tip', [0.13, y, 0.15], [0.18, y, 0.095], 0.013, 'steel', g)
|
| 306 |
+
elif key == 'screwdriver':
|
| 307 |
+
self.cylinder('driver_handle', [0, 0, -0.075], 0.032, 0.145, 'red', 'z', g)
|
| 308 |
+
for x in [-0.024, 0.024]:
|
| 309 |
+
self.box('driver_grip', [x, -0.012, -0.075], [0.008, 0.045, 0.105], 'iron', g, bevel=0.002)
|
| 310 |
+
self.cylinder('driver_collar', [0, 0, 0.005], 0.023, 0.025, 'steel', 'z', g)
|
| 311 |
+
self.cylinder('driver_shaft', [0, 0, 0.08], 0.008, 0.15, 'steel', 'z', g)
|
| 312 |
+
self.box('driver_flat_tip', [0, 0, 0.165], [0.022, 0.008, 0.035], 'steel', g, bevel=0.002)
|
| 313 |
+
elif key == 'brush':
|
| 314 |
+
self.box('brush_handle', [0, 0, -0.075], [0.037, 0.035, 0.17], 'wood', g, bevel=0.012)
|
| 315 |
+
self.box('brush_ferrule', [0, 0, 0.027], [0.105, 0.035, 0.07], 'steel', g)
|
| 316 |
+
self.box('brush_bristles', [0, 0, 0.105], [0.115, 0.035, 0.1], 'bristle', g, bevel=0.002)
|
| 317 |
+
for x in np.linspace(-0.049, 0.049, 10):
|
| 318 |
+
self.box('bristle_line', [float(x), -0.019, 0.105], [0.003, 0.003, 0.095], 'darkwood', g, bevel=0.0004)
|
| 319 |
+
elif key == 'wrench':
|
| 320 |
+
self.box('wrench_handle', [0, 0, -0.035], [0.042, 0.025, 0.26], 'steel', g, bevel=0.01)
|
| 321 |
+
self.box('wrench_neck', [0, 0, 0.1], [0.06, 0.028, 0.07], 'steel', g)
|
| 322 |
+
for side in [-1, 1]:
|
| 323 |
+
self.box('wrench_jaw', [side * 0.046, 0, 0.15], [0.035, 0.032, 0.09], 'steel', g, bevel=0.008)
|
| 324 |
+
self.box('wrench_tip', [side * 0.037, 0, 0.195], [0.04, 0.032, 0.024], 'steel', g, bevel=0.005)
|
| 325 |
+
self.cylinder('wrench_eye', [0, 0, -0.17], 0.035, 0.026, 'steel', 'y', g)
|
| 326 |
+
self.cylinder('wrench_eye_hole', [0, -0.015, -0.17], 0.013, 0.004, 'iron', 'y', g)
|
| 327 |
+
elif key == 'key':
|
| 328 |
+
n = 32
|
| 329 |
+
pts = []
|
| 330 |
+
for y in [-0.009, 0.009]:
|
| 331 |
+
for radius in [0.035, 0.021]:
|
| 332 |
+
for i in range(n):
|
| 333 |
+
t = 2 * math.pi * i / n
|
| 334 |
+
pts.append([radius * math.cos(t), y, 0.055 + radius * math.sin(t)])
|
| 335 |
+
faces = []
|
| 336 |
+
for i in range(n):
|
| 337 |
+
j = (i + 1) % n
|
| 338 |
+
faces += [[i, j, n + j, n + i], [2 * n + i, 3 * n + i, 3 * n + j, 2 * n + j], [i, 2 * n + i, 2 * n + j, j], [n + i, n + j, 3 * n + j, 3 * n + i]]
|
| 339 |
+
self.mesh('key_ring', pts, faces, 'key_gold', g)
|
| 340 |
+
self.box('key_shaft', [0, 0, -0.025], [0.015, 0.016, 0.12], 'key_gold', g, bevel=0.003)
|
| 341 |
+
self.box('key_bit', [0.022, 0, -0.065], [0.045, 0.016, 0.04], 'key_gold', g, bevel=0.003)
|
| 342 |
+
with self.og.sim.editing_usd():
|
| 343 |
+
self.G.Xformable(g['prim']).AddScaleOp().Set(self.F.Vec3f(1.35, 1.35, 1.35))
|
| 344 |
+
return g
|
| 345 |
+
|
| 346 |
+
def build(self, photo_paths=None):
|
| 347 |
+
for i in range(24):
|
| 348 |
+
self.box('floor_plank', [0.125 + i * 0.25, 2.5, -0.02], [0.247, 5.02, 0.05], 'wood', bevel=0.002)
|
| 349 |
+
for c, size in [([0, 2.5, 1.4], [0.14, 5.2, 2.8]), ([6, 2.5, 1.4], [0.14, 5.2, 2.8]), ([3, 5, 1.4], [6.1, 0.14, 2.8]), ([1.2, 0, 1.4], [2.4, 0.14, 2.8]), ([4.8, 0, 1.4], [2.4, 0.14, 2.8])]:
|
| 350 |
+
self.box('wall', c, size, 'plaster')
|
| 351 |
+
self.box('door_header', [3, 0, 2.58], [1.25, 0.16, 0.44], 'darkwood')
|
| 352 |
+
for c, size in [([0.09, 2.5, 0.45], [0.05, 5.0, 0.9]), ([5.91, 2.5, 0.45], [0.05, 5.0, 0.9]), ([3, 4.91, 0.45], [5.85, 0.05, 0.9])]:
|
| 353 |
+
self.box('wainscot', c, size, 'paint')
|
| 354 |
+
for x in [0.12, 5.88]:
|
| 355 |
+
self.box('skirting', [x, 2.5, 0.09], [0.08, 4.9, 0.16], 'darkwood')
|
| 356 |
+
self.box('dado', [x, 2.5, 0.92], [0.08, 4.9, 0.055], 'darkwood')
|
| 357 |
+
self.box('north_skirting', [3, 4.88, 0.09], [5.9, 0.09, 0.16], 'darkwood')
|
| 358 |
+
self.box('north_dado', [3, 4.88, 0.92], [5.9, 0.09, 0.055], 'darkwood')
|
| 359 |
+
for y in [0.35, 2.5, 4.65]:
|
| 360 |
+
self.box('ceiling_beam', [3, y, 2.72], [6, 0.12, 0.16], 'darkwood')
|
| 361 |
+
self.box('ceiling', [3, 2.5, 2.84], [6.2, 5.2, 0.1], 'plaster')
|
| 362 |
+
self.box('bench_top', [2.85, 4.55, 0.88], [1.65, 0.72, 0.1], 'wood', bevel=0.025)
|
| 363 |
+
for x in [2.12, 3.58]:
|
| 364 |
+
for y in [4.28, 4.82]:
|
| 365 |
+
self.box('bench_leg', [x, y, 0.44], [0.075, 0.075, 0.83], 'iron')
|
| 366 |
+
self.box('bench_stretcher', [2.85, 4.62, 0.2], [1.48, 0.06, 0.07], 'iron')
|
| 367 |
+
self.box('bench_shelf', [2.85, 4.55, 0.27], [1.48, 0.6, 0.06], 'wood')
|
| 368 |
+
for i in range(3):
|
| 369 |
+
self.cylinder('parts_tin', [2.15 + i * 0.19, 4.73, 0.99], 0.065, 0.15, 'paint')
|
| 370 |
+
self.cylinder('tin_lid', [2.15 + i * 0.19, 4.73, 1.07], 0.068, 0.02, 'steel')
|
| 371 |
+
self.box('folded_rag', [3.48, 4.55, 0.95], [0.28, 0.24, 0.035], 'cloth')
|
| 372 |
+
self.cylinder('lamp_base', [3.48, 4.77, 0.98], 0.11, 0.05, 'iron')
|
| 373 |
+
self.tube('lamp_stem', [3.48, 4.77, 1.0], [3.48, 4.77, 1.42], 0.018, 'steel')
|
| 374 |
+
self.tube('lamp_arm', [3.48, 4.77, 1.42], [3.22, 4.58, 1.48], 0.022, 'steel')
|
| 375 |
+
self.cylinder('lamp_shade', [3.22, 4.58, 1.46], 0.13, 0.1, 'paint')
|
| 376 |
+
self.cylinder('lamp_diffuser', [3.22, 4.58, 1.4], 0.105, 0.008, 'lamp')
|
| 377 |
+
self.box('case_stand_top', [1.0, 0.95, 0.46], [0.95, 0.62, 0.07], 'wood')
|
| 378 |
+
for x in [0.6, 1.4]:
|
| 379 |
+
for y in [0.71, 1.19]:
|
| 380 |
+
self.box('stand_leg', [x, y, 0.23], [0.07, 0.07, 0.44], 'iron')
|
| 381 |
+
for c, size in [([1.0, 0.7, 0.64], [0.72, 0.045, 0.28]), ([1.0, 1.2, 0.64], [0.72, 0.045, 0.28]), ([0.66, 0.95, 0.64], [0.045, 0.5, 0.28]), ([1.34, 0.95, 0.64], [0.045, 0.5, 0.28]), ([1.0, 0.95, 0.515], [0.72, 0.5, 0.035])]:
|
| 382 |
+
self.box('case_body', c, size, 'wood')
|
| 383 |
+
case = self.group('case_lid', [1.0, 1.21, 0.79])
|
| 384 |
+
self.box('case_lid_leaf', [0, -0.26, 0], [0.78, 0.56, 0.055], 'darkwood', case)
|
| 385 |
+
for x in [-0.29, 0.29]:
|
| 386 |
+
self.box('case_hinge', [x, -0.015, 0.028], [0.1, 0.06, 0.025], 'brass', case)
|
| 387 |
+
self.box('case_latch', [0, -0.54, -0.055], [0.08, 0.04, 0.085], 'brass', case)
|
| 388 |
+
for c, size in [([0.18, 4.0, 1.03], [0.08, 0.85, 2.05]), ([0.5, 3.58, 1.03], [0.66, 0.07, 2.05]), ([0.5, 4.42, 1.03], [0.66, 0.07, 2.05]), ([0.5, 4.0, 2.02], [0.66, 0.9, 0.06]), ([0.5, 4.0, 0.1], [0.66, 0.9, 0.1])]:
|
| 389 |
+
self.box('locker_body', c, size, 'paint')
|
| 390 |
+
for z in [0.55, 1.05, 1.55]:
|
| 391 |
+
self.box('locker_shelf', [0.5, 4.0, z], [0.6, 0.78, 0.035], 'steel')
|
| 392 |
+
locker = self.group('locker_door', [0.84, 4.43, 0])
|
| 393 |
+
self.box('locker_leaf', [0, -0.43, 1.05], [0.055, 0.86, 1.93], 'paint', locker)
|
| 394 |
+
self.box('locker_handle', [0.06, -0.71, 1.13], [0.08, 0.04, 0.18], 'brass', locker)
|
| 395 |
+
for z in [1.1, 1.25]:
|
| 396 |
+
self.cylinder('brush_clip', [-0.045, -0.43, z], 0.022, 0.065, 'brass', 'x', locker)
|
| 397 |
+
for z in [1.7, 1.78, 1.86]:
|
| 398 |
+
self.box('locker_vent', [0.032, -0.43, z], [0.008, 0.38, 0.018], 'iron', locker, bevel=0.002)
|
| 399 |
+
for z in [0.2, 0.36, 0.52, 0.68]:
|
| 400 |
+
self.box('crate_front', [0.82, 2.08, z], [0.06, 0.73, 0.145], 'wood')
|
| 401 |
+
self.box('crate_back', [0.16, 2.08, z], [0.06, 0.73, 0.145], 'wood')
|
| 402 |
+
for y in [1.71, 2.45]:
|
| 403 |
+
self.box('crate_side', [0.49, y, z], [0.66, 0.06, 0.145], 'wood')
|
| 404 |
+
self.box('crate_bottom', [0.49, 2.08, 0.12], [0.66, 0.72, 0.06], 'darkwood')
|
| 405 |
+
self.box('crate_padded_insert', [0.49, 2.08, 0.49], [0.59, 0.64, 0.045], 'cloth')
|
| 406 |
+
crate = self.group('crate_lid', [0.49, 2.47, 0.78])
|
| 407 |
+
self.box('crate_top', [0, -0.39, 0], [0.78, 0.82, 0.065], 'wood', crate)
|
| 408 |
+
for x in [-0.28, 0.28]:
|
| 409 |
+
self.box('crate_batten', [x, -0.39, 0.05], [0.07, 0.76, 0.035], 'darkwood', crate)
|
| 410 |
+
nail = self.group('crate_fasteners', [0.49, 2.47, 0.78])
|
| 411 |
+
for x in [-0.28, 0.28]:
|
| 412 |
+
self.cylinder('raised_nail', [x, -0.7, 0.085], 0.02, 0.055, 'iron', 'z', nail)
|
| 413 |
+
self.cylinder('nail_head', [x, -0.7, 0.115], 0.03, 0.012, 'steel', 'z', nail)
|
| 414 |
+
for c, size in [([5.7, 2.3, 0.72], [0.1, 1.15, 1.35]), ([5.3, 1.75, 0.72], [0.86, 0.08, 1.35]), ([5.3, 2.85, 0.72], [0.86, 0.08, 1.35]), ([5.3, 2.3, 0.1], [0.9, 1.2, 0.15]), ([5.3, 2.3, 1.38], [0.9, 1.2, 0.1])]:
|
| 415 |
+
self.box('pump_body', c, size, 'paint')
|
| 416 |
+
self.cylinder('pump_motor', [5.35, 2.3, 1.65], 0.24, 0.55, 'iron', 'x')
|
| 417 |
+
for x in [5.05, 5.2, 5.35, 5.5, 5.65]:
|
| 418 |
+
self.cylinder('motor_rib', [x, 2.3, 1.65], 0.255, 0.035, 'steel', 'x')
|
| 419 |
+
self.tube('pipe_a', [5.6, 2.3, 1.7], [5.6, 2.3, 2.2], 0.065)
|
| 420 |
+
self.tube('pipe_b', [5.6, 2.3, 2.2], [5.88, 2.3, 2.2], 0.065)
|
| 421 |
+
self.cylinder('pipe_flange', [5.6, 2.3, 2.05], 0.12, 0.06, 'brass', 'z')
|
| 422 |
+
self.box('service_ledge', [5.28, 2.3, 0.55], [0.65, 0.9, 0.06], 'steel')
|
| 423 |
+
hatch = self.group('pump_hatch', [4.86, 2.88, 0])
|
| 424 |
+
self.box('hatch_leaf', [0, -0.58, 0.78], [0.055, 1.13, 1.12], 'paint', hatch)
|
| 425 |
+
self.box('hatch_handle', [-0.06, -0.85, 0.78], [0.06, 0.06, 0.21], 'steel', hatch)
|
| 426 |
+
screw = self.group('hatch_screw', [4.82, 2.3, 1.13])
|
| 427 |
+
self.cylinder('screw_head', [0, 0, 0], 0.044, 0.025, 'steel', 'x', screw)
|
| 428 |
+
self.box('screw_slot', [-0.014, 0, 0], [0.004, 0.058, 0.01], 'iron', screw, bevel=0.0005)
|
| 429 |
+
self.box('rack_board', [4.7, 4.86, 1.63], [1.25, 0.1, 1.25], 'wood', bevel=0.025)
|
| 430 |
+
for x in [4.07, 5.33]:
|
| 431 |
+
self.box('rack_rail', [x, 4.79, 1.63], [0.055, 0.07, 1.29], 'darkwood')
|
| 432 |
+
for z in [1.0, 2.26]:
|
| 433 |
+
self.box('rack_rail', [4.7, 4.79, z], [1.3, 0.07, 0.055], 'darkwood')
|
| 434 |
+
self.box('rack_corner1', [4.13, 4.73, 2.2], [0.18, 0.025, 0.035], 'brass')
|
| 435 |
+
self.box('rack_corner2', [4.06, 4.73, 2.13], [0.035, 0.025, 0.18], 'brass')
|
| 436 |
+
slots = [(4.42, 4.7, 1.94), (4.98, 4.7, 1.94), (4.42, 4.7, 1.4), (4.98, 4.7, 1.4)]
|
| 437 |
+
slotnodes = []
|
| 438 |
+
for i, c in enumerate(slots):
|
| 439 |
+
p = np.array(c)
|
| 440 |
+
pad = self.box('holder' + str(i), p + [0, 0.035, -0.03], [0.17, 0.025, 0.22], 'paint')
|
| 441 |
+
for dx in [-0.055, 0.055]:
|
| 442 |
+
self.cylinder('holder_pin', [p[0] + dx, p[1] - 0.005, p[2] - 0.05], 0.012, 0.1, 'brass', 'y')
|
| 443 |
+
slotnodes.append(pad)
|
| 444 |
+
self.tube('rack_latch_link', [4.1, 4.75, 1.0], [4.1, 4.75, 0.74], 0.015, 'brass')
|
| 445 |
+
for c, size in [([4.7, 4.9, 0.58], [1.15, 0.08, 0.8]), ([4.13, 4.69, 0.58], [0.07, 0.5, 0.8]), ([5.27, 4.69, 0.58], [0.07, 0.5, 0.8]), ([4.7, 4.69, 0.97], [1.15, 0.5, 0.07]), ([4.7, 4.69, 0.2], [1.15, 0.5, 0.08])]:
|
| 446 |
+
self.box('keycab_body', c, size, 'paint')
|
| 447 |
+
drawer = self.group('key_drawer', [4.7, 4.69, 0.47])
|
| 448 |
+
self.box('drawer_tray', [0, 0, 0], [0.99, 0.43, 0.05], 'wood', drawer)
|
| 449 |
+
self.box('drawer_lining', [0, 0, 0.035], [0.93, 0.37, 0.012], 'drawer_felt', drawer)
|
| 450 |
+
for x in [-0.49, 0.49]:
|
| 451 |
+
self.box('drawer_front_side', [x, -0.24, 0.135], [0.08, 0.05, 0.28], 'paint', drawer)
|
| 452 |
+
self.box('drawer_sidewall', [x, 0, 0.075], [0.03, 0.43, 0.12], 'wood', drawer)
|
| 453 |
+
self.box('drawer_slide', [x * 0.97, 0, -0.035], [0.025, 0.44, 0.035], 'steel', drawer)
|
| 454 |
+
for z in [-0.005, 0.275]:
|
| 455 |
+
self.box('drawer_front_rail', [0, -0.24, z], [1.06, 0.05, 0.05], 'paint', drawer)
|
| 456 |
+
glass = self.plane('drawer_glass', [0, -0.268, 0.135], 0.89, 0.21, [1, 0, 0], [0, 0, 1], None, drawer, material=self.mats['glass'])
|
| 457 |
+
self.box('drawer_handle', [0, -0.3, 0.26], [0.28, 0.055, 0.045], 'brass', drawer)
|
| 458 |
+
label = self.label_image('shift_label', 'SHIFT HANDOVER', 900, 160)
|
| 459 |
+
self.plane('shift_label', [4.7, 4.412, 0.92], 0.63, 0.11, [1, 0, 0], [0, 0, 1], label)
|
| 460 |
+
self.box('keycab_light_strip', [4.7, 4.65, 0.882], [0.32, 0.08, 0.018], 'lamp')
|
| 461 |
+
lamp = self.cylinder('rack_status', [5.18, 4.42, 0.91], 0.025, 0.02, 'brass', 'y')
|
| 462 |
+
for x in [2.4, 3.6]:
|
| 463 |
+
self.box('door_jamb', [x, 0.05, 1.17], [0.12, 0.2, 2.35], 'darkwood')
|
| 464 |
+
door = self.group('exit_door', [2.46, 0.09, 0])
|
| 465 |
+
self.box('door_leaf', [0.54, 0, 1.13], [1.08, 0.1, 2.22], 'wood', door, bevel=0.025)
|
| 466 |
+
for z in [0.27, 1.95]:
|
| 467 |
+
self.box('door_iron_band', [0.54, 0.06, z], [1.02, 0.04, 0.1], 'iron', door)
|
| 468 |
+
self.box('door_lock_plate', [0.93, 0.075, 1.03], [0.13, 0.04, 0.24], 'brass', door)
|
| 469 |
+
self.cylinder('door_knob', [0.93, 0.13, 1.1], 0.045, 0.08, 'steel', 'y', door)
|
| 470 |
+
self.cylinder('keyhole', [0.93, 0.101, 0.99], 0.02, 0.006, 'iron', 'y', door)
|
| 471 |
+
self.box('porch', [3.0, -0.5, -0.025], [1.5, 1.0, 0.05], 'wood')
|
| 472 |
+
book = self.group('album_stand', [2.71, 4.46, 1.12])
|
| 473 |
+
self.transform(book, rpy=[60, 0, 0])
|
| 474 |
+
album = self.group('album_cover', [-0.23, 0, 0.035], parent=book)
|
| 475 |
+
self.box('album_cover_leaf', [0.23, 0, 0.01], [0.46, 0.42, 0.045], 'darkwood', album)
|
| 476 |
+
self.box('album_pages', [0, 0, 0], [0.45, 0.42, 0.035], 'paper', book)
|
| 477 |
+
self.box('album_spine', [-0.25, 0, 0], [0.04, 0.45, 0.06], 'red', book)
|
| 478 |
+
self.box('reading_stand_back', [2.71, 4.59, 1.11], [0.48, 0.06, 0.34], 'darkwood')
|
| 479 |
+
self.box('reading_stand_lip', [2.71, 4.33, 0.957], [0.5, 0.055, 0.04], 'brass')
|
| 480 |
+
placeholder = self.label_image('photo_placeholder', '', 600, 600)
|
| 481 |
+
photo1 = self.plane('photo1', [0, 0, 0.022], 0.41, 0.36, [1, 0, 0], [0, 1, 0], placeholder, book)
|
| 482 |
+
photo2 = self.framed('photo2', [0.105, 2.99, 1.55], 0.42, 0.63, [0, 1, 0], [0, 0, 1], placeholder)
|
| 483 |
+
dust = self.plane('photo_dust', [0.119, 2.99, 1.55], 0.375, 0.565, [0, 1, 0], [0, 0, 1], None, material=self.mats['dust'])
|
| 484 |
+
self.tube('wall_conduit', [0.2, 4.78, 2.42], [5.8, 4.78, 2.42], 0.018, 'steel')
|
| 485 |
+
for x in [1.9, 3.8]:
|
| 486 |
+
self.tube('conduit_drop', [x, 4.78, 2.42], [x, 4.78, 1.2], 0.018, 'steel')
|
| 487 |
+
self.box('side_shelf', [5.75, 3.75, 1.68], [0.4, 0.85, 0.045], 'wood')
|
| 488 |
+
for y in [3.5, 3.75, 4.0]:
|
| 489 |
+
self.cylinder('shelf_can', [5.72, y, 1.78], 0.08, 0.18, 'paint')
|
| 490 |
+
self.cylinder('shelf_can_lid', [5.72, y, 1.88], 0.085, 0.015, 'steel')
|
| 491 |
+
self.box('rug', [3.0, 2.2, 0.006], [2.0, 1.2, 0.012], 'cloth', bevel=0.002)
|
| 492 |
+
self.box('window_back', [0.085, 1.85, 2.06], [0.035, 1.18, 0.85], 'iron')
|
| 493 |
+
self.mat('window_glow', (0.13, 0.22, 0.28), rough=0.5, emission=(0.15, 0.27, 0.35))
|
| 494 |
+
self.box('window_glass', [0.11, 1.85, 2.06], [0.02, 1.08, 0.76], 'window_glow')
|
| 495 |
+
for y in [1.28, 1.85, 2.42]:
|
| 496 |
+
self.box('window_frame', [0.14, y, 2.06], [0.05, 0.05, 0.85], 'darkwood')
|
| 497 |
+
for z in [1.64, 2.48]:
|
| 498 |
+
self.box('window_frame', [0.14, 1.85, z], [0.05, 1.18, 0.05], 'darkwood')
|
| 499 |
+
for x, y in [(2.4, 2.7), (4.7, 4.0)]:
|
| 500 |
+
self.tube('light_cord', [x, y, 2.72], [x, y, 2.52], 0.009, 'iron')
|
| 501 |
+
self.cylinder('ceiling_shade', [x, y, 2.49], 0.23, 0.1, 'paint')
|
| 502 |
+
self.cylinder('ceiling_diffuser', [x, y, 2.43], 0.2, 0.015, 'lamp')
|
| 503 |
+
self.box('entry_light_frame', [3.0, 0.5, 2.58], [1.29, 0.39, 0.055], 'paint')
|
| 504 |
+
self.box('entry_light_diffuser', [3.0, 0.5, 2.555], [1.2, 0.3, 0.012], 'lamp')
|
| 505 |
+
tools = {key: self.tool(key) for key in ['hammer', 'screwdriver', 'brush', 'wrench', 'key']}
|
| 506 |
+
return dict(case=case, locker=locker, crate=crate, nails=nail, hatch=hatch, screw=screw, drawer=drawer, exit=door, album=album, photo1=photo1, photo2=photo2, dust=dust, tools=tools, slots=slots, slotnodes=slotnodes, glass=glass, status=lamp)
|
runtime/h2_runtime/observation1280.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
WIDTH = 1280
|
| 3 |
+
HEIGHT = 640
|
| 4 |
+
FX = FY = 640.0
|
| 5 |
+
CX = 640.0
|
| 6 |
+
CY = 320.0
|
| 7 |
+
PROFILE = 'new88_native_1280x640_v1'
|
| 8 |
+
MODEL_TEMPLATE_ID = 'user_approved_exact_20261027'
|
| 9 |
+
PROMPT_PARENT_SHA256 = '019c4439ee80a1855fc8bfc53470be855a19d0278fd9a46a9028d141e39c6966'
|
| 10 |
+
MODEL_INSTRUCTIONS = 'You are a robot locked in a room. Your goal is to get out of the room.The door is locked. What opens it is not told in this message; you have to find out by searching the room.Papers and notes in the room may give you hints.Things can be hidden inside furniture that opens, and some things are locked themselves.To win, open the exit door.\nEach turn you see what you are holding, your own notes, your last 10 steps and, at the end, a photo of your current view.Each of the last steps is shown with the photo you were looking at when you chose it, the action you took and any available feedback(recalls are listed separately). Older steps are NOT shown; they are kept in your memory, which you can search with recall.\nChoose exactly one action:\n{"action": "walk", "distance": 0.25 | 0.5 | 1.0}\n{"action": "turn", "direction": "left" | "right" | "up" | "down", "degrees": 10-120}\n(left / right turn you in place; up / down tilt your head)\n{"action": "step_back", "distance": 0.1-0.6}\n{"action": "side_step", "direction": "left" | "right", "distance": 0.1-0.5}\n(step back or sideways while keeping your facing direction)\n{"action": "open", "point": [x, y], "target": "<what>"}\n{"action": "close", "point": [x, y], "target": "<what>"}\n{"action": "take", "point": [x, y], "target": "<what>"}\n{"action": "read", "point": [x, y], "target": "<what>"} the item in your hand needs no point\n{"action": "unlock", "point": [x, y], "target": "<what>", "code": "<digits>"} a locked item in your hand needs no point\n{"action": "use", "point": [x, y], "target": "<what>"} uses/place the item in your hand on the thing you point at,or on another item in your hand (that one needs no point; "target" names it)\n(when you hold several items, add "item": "<a word for the one you mean>" to read / use)\n{"action": "press", "point": [x, y], "target": "<what>"}\n{"action": "recall", "query": "<words to search your memory for>"}\n(recall searches only the steps older than your last 10 steps, by the actions you took and what happened, and shows each step it finds with the photo you were looking at then.)\nRecall has a separate budget and does not use an action. Every recall attempt uses one recall, even if nothing is found. When Recalls left is 0, recall is unavailable.\n"point" says which thing you mean: the position of that thing in the photo of your current view, in pixels: x from 0 (left edge) to 1280 (right edge) and y from 0 (top) to 640 (bottom). "target" is one or two words naming the whole thing you point at (cabinet, door, note, ...).\nYou can only act on things in your current view, and you must be close to them. \nWhen you look for something, scan by turning in one direction; do not spin or alternate left and right turns. If you could not move, do not repeat the same walk; turn or step back instead.\nDo not guess codes. Only enter a code that you have actually found written somewhere in the room;trying numbers one after another is not allowed.\nYou can add "note": "<one sentence>" to any action to write down what you think is important; your notes are shown to you every turn (at most 20 notes; "drop_notes": [<note numbers>] removes notes).\nEvery reply must include "thought": one short sentence on why you take this action.\nReply with exactly one JSON object:\n{"thought": "<why you take this action>", "action": "<one of the actions above>", ...its parameters...}\nYou have at most 80 actions.'
|
| 11 |
+
|
| 12 |
+
def rules_for_budget(limit=80):
|
| 13 |
+
return MODEL_INSTRUCTIONS.replace('You have at most 80 actions.', f'You have at most {int(limit)} actions.')
|
| 14 |
+
|
| 15 |
+
def validate_action(action, recalls_left=5):
|
| 16 |
+
from protocol import validate_action as legacy_validate
|
| 17 |
+
original = None
|
| 18 |
+
if isinstance(action, dict) and 'point' in action:
|
| 19 |
+
original = action['point']
|
| 20 |
+
if not isinstance(original, list) or len(original) != 2:
|
| 21 |
+
raise ValueError('point requires [x,y] in1280x640 pixels')
|
| 22 |
+
if any((type(v) not in (int, float) or not math.isfinite(v) for v in original)):
|
| 23 |
+
raise ValueError('point must contain finite pixel coordinates')
|
| 24 |
+
if not (0 <= original[0] < WIDTH and 0 <= original[1] < HEIGHT):
|
| 25 |
+
raise ValueError('point out of range: 0<=x<1280, 0<=y<640')
|
| 26 |
+
check = dict(action, point=[original[0] * 640 / WIDTH, original[1] * 360 / HEIGHT])
|
| 27 |
+
else:
|
| 28 |
+
check = action
|
| 29 |
+
clean = legacy_validate(check, recalls_left)
|
| 30 |
+
if original is not None:
|
| 31 |
+
clean['point'] = list(original)
|
| 32 |
+
return clean
|
| 33 |
+
|
| 34 |
+
def prepare_observation(rgb, depth):
|
| 35 |
+
import numpy as np
|
| 36 |
+
from PIL import Image
|
| 37 |
+
if rgb.shape[:2] != (HEIGHT, WIDTH) or depth.shape != (HEIGHT, WIDTH):
|
| 38 |
+
raise ValueError('Native RGB/depth must both be1280x640; no resize/upscale fallback')
|
| 39 |
+
return (Image.fromarray(rgb[:, :, :3]).copy(), np.asarray(depth, dtype=np.float32).copy())
|
runtime/h2_runtime/oracle355.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import heapq
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
GRID = 0.25
|
| 6 |
+
|
| 7 |
+
def _wrap(angle):
|
| 8 |
+
return (angle + math.pi) % (2 * math.pi) - math.pi
|
| 9 |
+
|
| 10 |
+
def _turn_actions(delta, vertical=False):
|
| 11 |
+
degrees = int(round(math.degrees(delta) / 10)) * 10
|
| 12 |
+
direction = ('up' if degrees > 0 else 'down') if vertical else 'left' if degrees > 0 else 'right'
|
| 13 |
+
remaining = abs(degrees)
|
| 14 |
+
actions = []
|
| 15 |
+
while remaining:
|
| 16 |
+
amount = min(120, remaining)
|
| 17 |
+
actions.append(dict(action='turn', direction=direction, degrees=amount))
|
| 18 |
+
remaining -= amount
|
| 19 |
+
return actions
|
| 20 |
+
|
| 21 |
+
def _edge_clear(a, b, blocked):
|
| 22 |
+
n = max(1, math.ceil(math.dist(a, b) / 0.04))
|
| 23 |
+
for i in range(1, n + 1):
|
| 24 |
+
f = i / n
|
| 25 |
+
if blocked(a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f):
|
| 26 |
+
return False
|
| 27 |
+
return True
|
| 28 |
+
|
| 29 |
+
def route_nodes(start_xy, dest_xy, blocked, max_nodes=50000):
|
| 30 |
+
if len(start_xy) < 2 or len(dest_xy) < 2 or (not all((math.isfinite(float(x)) for x in (*start_xy[:2], *dest_xy[:2])))):
|
| 31 |
+
raise ValueError('Finite start/destination XY coordinates required.')
|
| 32 |
+
start = tuple((int(round(float(v) / GRID)) for v in start_xy[:2]))
|
| 33 |
+
goal = tuple((int(round(float(v) / GRID)) for v in dest_xy[:2]))
|
| 34 |
+
xy = lambda n: (n[0] * GRID, n[1] * GRID)
|
| 35 |
+
if math.dist(xy(start), start_xy[:2]) > 0.005:
|
| 36 |
+
raise ValueError('Start is not on .25m lattice; do not silently snap real pose.')
|
| 37 |
+
if blocked(*xy(start)):
|
| 38 |
+
raise ValueError('Route start is blocked.')
|
| 39 |
+
if blocked(*xy(goal)):
|
| 40 |
+
raise ValueError('Rounded destination stand point is blocked: %s' % (xy(goal),))
|
| 41 |
+
h = lambda n: abs(n[0] - goal[0]) + abs(n[1] - goal[1])
|
| 42 |
+
queue = [(h(start), 0, start)]
|
| 43 |
+
costs, parents = ({start: 0}, {})
|
| 44 |
+
expanded = 0
|
| 45 |
+
while queue:
|
| 46 |
+
_, cost, node = heapq.heappop(queue)
|
| 47 |
+
if cost != costs[node]:
|
| 48 |
+
continue
|
| 49 |
+
if node == goal:
|
| 50 |
+
path = [node]
|
| 51 |
+
while node != start:
|
| 52 |
+
node = parents[node]
|
| 53 |
+
path.append(node)
|
| 54 |
+
return [xy(n) for n in reversed(path)]
|
| 55 |
+
expanded += 1
|
| 56 |
+
if expanded > max_nodes:
|
| 57 |
+
raise RuntimeError('No route within offline oracle node budget.')
|
| 58 |
+
for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
|
| 59 |
+
nxt = (node[0] + dx, node[1] + dy)
|
| 60 |
+
if cost + 1 >= costs.get(nxt, math.inf) or not _edge_clear(xy(node), xy(nxt), blocked):
|
| 61 |
+
continue
|
| 62 |
+
costs[nxt] = cost + 1
|
| 63 |
+
parents[nxt] = node
|
| 64 |
+
heapq.heappush(queue, (cost + 1 + h(nxt), cost + 1, nxt))
|
| 65 |
+
raise RuntimeError('No collision-free route to stand point.')
|
| 66 |
+
|
| 67 |
+
def plan_route(start_xy, dest_xy, blocked, yaw=0.0):
|
| 68 |
+
if not math.isfinite(yaw):
|
| 69 |
+
raise ValueError('Finite yaw required.')
|
| 70 |
+
nearest = math.radians(round(math.degrees(yaw) / 10) * 10)
|
| 71 |
+
if abs(_wrap(yaw - nearest)) > 0.0001:
|
| 72 |
+
raise ValueError('Yaw is not on 10-degree lattice; cannot promise exact cardinal route.')
|
| 73 |
+
nodes = route_nodes(start_xy, dest_xy, blocked)
|
| 74 |
+
runs = []
|
| 75 |
+
for a, b in zip(nodes, nodes[1:]):
|
| 76 |
+
direction = (round((b[0] - a[0]) / GRID), round((b[1] - a[1]) / GRID))
|
| 77 |
+
if runs and runs[-1][0] == direction:
|
| 78 |
+
runs[-1][1] += 1
|
| 79 |
+
else:
|
| 80 |
+
runs.append([direction, 1])
|
| 81 |
+
actions = []
|
| 82 |
+
for (dx, dy), cells in runs:
|
| 83 |
+
heading = math.atan2(dy, dx)
|
| 84 |
+
actions.extend(_turn_actions(_wrap(heading - yaw)))
|
| 85 |
+
yaw = heading
|
| 86 |
+
for size in (4, 2, 1):
|
| 87 |
+
number, cells = divmod(cells, size)
|
| 88 |
+
actions.extend((dict(action='walk', distance=size * GRID) for _ in range(number)))
|
| 89 |
+
return actions
|
| 90 |
+
|
| 91 |
+
def aim_actions(pos, yaw, pitch, target3d, eye_height=1.35):
|
| 92 |
+
if len(pos) < 2 or len(target3d) != 3:
|
| 93 |
+
raise ValueError('pos needs XY/XYZ and target needs XYZ.')
|
| 94 |
+
x, y = map(float, pos[:2])
|
| 95 |
+
z = float(pos[2]) if len(pos) > 2 else float(eye_height)
|
| 96 |
+
dx, dy, dz = (float(target3d[0]) - x, float(target3d[1]) - y, float(target3d[2]) - z)
|
| 97 |
+
if not all((math.isfinite(v) for v in (dx, dy, dz, yaw, pitch))):
|
| 98 |
+
raise ValueError('Finite pose and target required.')
|
| 99 |
+
horizontal = math.hypot(dx, dy)
|
| 100 |
+
desired_yaw = math.atan2(dy, dx) if horizontal > 1e-09 else yaw
|
| 101 |
+
desired_pitch = max(-math.pi / 3, min(math.pi / 3, math.atan2(dz, horizontal)))
|
| 102 |
+
return _turn_actions(_wrap(desired_yaw - yaw)) + _turn_actions(desired_pitch - pitch, vertical=True)
|
| 103 |
+
|
| 104 |
+
def self_test():
|
| 105 |
+
|
| 106 |
+
def blocked(x, y):
|
| 107 |
+
return abs(x) > 2 or abs(y) > 2 or (abs(x) < 0.1 and y < 0.75)
|
| 108 |
+
start, goal = ((-1.0, 0.0), (1.0, 0.0))
|
| 109 |
+
actions = plan_route(start, goal, blocked, yaw=math.radians(30))
|
| 110 |
+
p = list(start)
|
| 111 |
+
yaw = math.radians(30)
|
| 112 |
+
for a in actions:
|
| 113 |
+
if a['action'] == 'turn':
|
| 114 |
+
assert 10 <= a['degrees'] <= 120 and a['degrees'] % 10 == 0
|
| 115 |
+
yaw += math.radians(a['degrees']) * (1 if a['direction'] == 'left' else -1)
|
| 116 |
+
else:
|
| 117 |
+
assert a['distance'] in (0.25, 0.5, 1.0)
|
| 118 |
+
nxt = [p[0] + a['distance'] * math.cos(yaw), p[1] + a['distance'] * math.sin(yaw)]
|
| 119 |
+
assert _edge_clear(p, nxt, blocked)
|
| 120 |
+
p = nxt
|
| 121 |
+
assert math.dist(p, goal) < 1e-08
|
| 122 |
+
count = 0
|
| 123 |
+
for degrees in range(-180, 180, 10):
|
| 124 |
+
for desired in range(-175, 180, 7):
|
| 125 |
+
yaw = math.radians(degrees)
|
| 126 |
+
pitch = 0.0
|
| 127 |
+
t = [math.cos(math.radians(desired)), math.sin(math.radians(desired)), 1.55]
|
| 128 |
+
for a in aim_actions([0, 0, 1.35], yaw, pitch, t):
|
| 129 |
+
delta = math.radians(a['degrees'])
|
| 130 |
+
if a['direction'] in ('left', 'right'):
|
| 131 |
+
yaw += delta * (1 if a['direction'] == 'left' else -1)
|
| 132 |
+
else:
|
| 133 |
+
pitch += delta * (1 if a['direction'] == 'up' else -1)
|
| 134 |
+
assert abs(_wrap(yaw - math.radians(desired))) <= math.radians(5.00001)
|
| 135 |
+
assert abs(pitch - math.atan2(0.2, 1.0)) <= math.radians(5.00001)
|
| 136 |
+
count += 1
|
| 137 |
+
print(json.dumps(dict(passed=True, route_actions=len(actions), route_final=p, aim_cases=count, paid_calls=0, sdk_loaded=False, scope='offline CPU planner, not native route execution')))
|
| 138 |
+
if __name__ == '__main__':
|
| 139 |
+
self_test()
|
runtime/h2_runtime/oracle560.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import heapq, math
|
| 2 |
+
from oracle355 import _edge_clear, _turn_actions, _wrap, GRID
|
| 3 |
+
|
| 4 |
+
def plan_route(start_xy, dest_xy, blocked, yaw=0.0):
|
| 5 |
+
start = tuple((round(float(x) / GRID) for x in start_xy[:2]))
|
| 6 |
+
goal = tuple((round(float(x) / GRID) for x in dest_xy[:2]))
|
| 7 |
+
xy = lambda n: (n[0] * GRID, n[1] * GRID)
|
| 8 |
+
if math.dist(xy(start), start_xy[:2]) > 0.005:
|
| 9 |
+
raise ValueError('Non-lattice start, no snapping allowed')
|
| 10 |
+
if blocked(*xy(start)) or blocked(*xy(goal)):
|
| 11 |
+
raise ValueError('Blocked route endpoint')
|
| 12 |
+
if start == goal:
|
| 13 |
+
return []
|
| 14 |
+
queue = [(0, 0.0, start)]
|
| 15 |
+
cost = {start: (0, 0.0)}
|
| 16 |
+
parent = {}
|
| 17 |
+
while queue:
|
| 18 |
+
count, length, n = heapq.heappop(queue)
|
| 19 |
+
if cost[n] != (count, length):
|
| 20 |
+
continue
|
| 21 |
+
if n == goal:
|
| 22 |
+
break
|
| 23 |
+
for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
|
| 24 |
+
for step in (4, 2, 1):
|
| 25 |
+
nn = (n[0] + dx * step, n[1] + dy * step)
|
| 26 |
+
v = (count + 1, length + step * GRID)
|
| 27 |
+
if v >= cost.get(nn, (math.inf, math.inf)) or not _edge_clear(xy(n), xy(nn), blocked):
|
| 28 |
+
continue
|
| 29 |
+
cost[nn] = v
|
| 30 |
+
parent[nn] = (n, (dx, dy), step)
|
| 31 |
+
heapq.heappush(queue, (v[0], v[1], nn))
|
| 32 |
+
else:
|
| 33 |
+
raise RuntimeError('No swept-clear path')
|
| 34 |
+
edges = []
|
| 35 |
+
n = goal
|
| 36 |
+
while n != start:
|
| 37 |
+
n0, heading, step = parent[n]
|
| 38 |
+
edges.append((heading, step))
|
| 39 |
+
n = n0
|
| 40 |
+
edges.reverse()
|
| 41 |
+
options = []
|
| 42 |
+
for k in range(4):
|
| 43 |
+
heading = k * math.pi / 2
|
| 44 |
+
turns = _turn_actions(_wrap(heading - yaw))
|
| 45 |
+
options.append((len(turns), abs(_wrap(heading - yaw)), k, turns))
|
| 46 |
+
_, _, k, actions = min(options)
|
| 47 |
+
actions = list(actions)
|
| 48 |
+
for (dx, dy), step in edges:
|
| 49 |
+
direction = (round(math.atan2(dy, dx) / (math.pi / 2)) - k) % 4
|
| 50 |
+
action = {'action': 'walk' if direction == 0 else 'step_back' if direction == 2 else 'side_step', 'distance': step * GRID}
|
| 51 |
+
if direction in (1, 3):
|
| 52 |
+
action['direction'] = 'left' if direction == 1 else 'right'
|
| 53 |
+
actions.append(action)
|
| 54 |
+
return actions
|
runtime/h2_runtime/pixel355.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import itertools
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def _rotation(quat_xyzw):
|
| 7 |
+
q = np.asarray(quat_xyzw, dtype=float).reshape(4)
|
| 8 |
+
if not np.all(np.isfinite(q)) or np.linalg.norm(q) < 1e-12:
|
| 9 |
+
raise ValueError('Quaternion must be finite, nonzero, and XYZW.')
|
| 10 |
+
x, y, z, w = q / np.linalg.norm(q)
|
| 11 |
+
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]], dtype=float)
|
| 12 |
+
|
| 13 |
+
def _inputs(camera_pos, quat_xyzw, depth, fx, fy, tolerance):
|
| 14 |
+
origin = np.asarray(camera_pos, dtype=float).reshape(3)
|
| 15 |
+
if not np.all(np.isfinite(origin)):
|
| 16 |
+
raise ValueError('Camera position must be finite.')
|
| 17 |
+
values = np.asarray(depth)
|
| 18 |
+
if values.shape == (640, 1280, 1):
|
| 19 |
+
values = values[:, :, 0]
|
| 20 |
+
if values.shape != (640, 1280):
|
| 21 |
+
raise ValueError('Use the current model-view 1280x640 depth array; resample with nearest-neighbour, not bilinear.')
|
| 22 |
+
fy = float(fx if fy is None else fy)
|
| 23 |
+
fx = float(fx)
|
| 24 |
+
if not math.isfinite(fx) or not math.isfinite(fy) or min(fx, fy) <= 0:
|
| 25 |
+
raise ValueError('Focal lengths must be positive and finite.')
|
| 26 |
+
tolerance = float(tolerance)
|
| 27 |
+
if not math.isfinite(tolerance) or not 0 <= tolerance <= 0.08:
|
| 28 |
+
raise ValueError('Depth tolerance must be between 0 and 0.08 metres.')
|
| 29 |
+
return (origin, _rotation(quat_xyzw), values, fx, fy, tolerance)
|
| 30 |
+
|
| 31 |
+
def _box(candidate):
|
| 32 |
+
if not isinstance(candidate, dict) or not {'key', 'room', 'lo', 'hi'} <= set(candidate):
|
| 33 |
+
raise ValueError('Each candidate requires key, room, lo, hi.')
|
| 34 |
+
lo = np.asarray(candidate['lo'], dtype=float).reshape(3)
|
| 35 |
+
hi = np.asarray(candidate['hi'], dtype=float).reshape(3)
|
| 36 |
+
if not np.all(np.isfinite(lo)) or not np.all(np.isfinite(hi)) or np.any(hi < lo):
|
| 37 |
+
raise ValueError('Invalid world AABB.')
|
| 38 |
+
return (lo, hi)
|
| 39 |
+
|
| 40 |
+
def _slab(origin, direction, lo, hi):
|
| 41 |
+
near, far = (-math.inf, math.inf)
|
| 42 |
+
for i in range(3):
|
| 43 |
+
if abs(direction[i]) < 1e-12:
|
| 44 |
+
if origin[i] < lo[i] or origin[i] > hi[i]:
|
| 45 |
+
return None
|
| 46 |
+
continue
|
| 47 |
+
a, b = ((lo[i] - origin[i]) / direction[i], (hi[i] - origin[i]) / direction[i])
|
| 48 |
+
near, far = (max(near, min(a, b)), min(far, max(a, b)))
|
| 49 |
+
if far < near:
|
| 50 |
+
return None
|
| 51 |
+
if far <= 0 or not math.isfinite(far):
|
| 52 |
+
return None
|
| 53 |
+
return (max(0.0, float(near)), float(far))
|
| 54 |
+
|
| 55 |
+
def _triangle_hit(origin, direction, triangles):
|
| 56 |
+
tri = np.asarray(triangles, dtype=float)
|
| 57 |
+
if tri.size == 0:
|
| 58 |
+
return None
|
| 59 |
+
if tri.ndim != 3 or tri.shape[1:] != (3, 3) or (not np.all(np.isfinite(tri))):
|
| 60 |
+
raise ValueError('triangles must be finite world coordinates with shape [N,3,3].')
|
| 61 |
+
edge1, edge2 = (tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
|
| 62 |
+
pvec = np.cross(direction, edge2)
|
| 63 |
+
det = np.einsum('ij,ij->i', edge1, pvec)
|
| 64 |
+
mask = np.abs(det) > 1e-10
|
| 65 |
+
inv = np.zeros_like(det)
|
| 66 |
+
np.divide(1.0, det, out=inv, where=mask)
|
| 67 |
+
tvec = origin - tri[:, 0]
|
| 68 |
+
u = np.einsum('ij,ij->i', tvec, pvec) * inv
|
| 69 |
+
qvec = np.cross(tvec, edge1)
|
| 70 |
+
v = qvec @ direction * inv
|
| 71 |
+
t = np.einsum('ij,ij->i', edge2, qvec) * inv
|
| 72 |
+
eps = 1e-08
|
| 73 |
+
mask &= (u >= -eps) & (v >= -eps) & (u + v <= 1 + eps) & (t > 1e-07)
|
| 74 |
+
valid = np.flatnonzero(mask)
|
| 75 |
+
if not len(valid):
|
| 76 |
+
return None
|
| 77 |
+
index = int(valid[np.argmin(t[valid])])
|
| 78 |
+
return (float(t[index]), index)
|
| 79 |
+
|
| 80 |
+
def pick(point, camera_pos, quat_XYZW, depth_1280x640, candidates, *, fx=640.0, fy=None, cx=640.0, cy=320.0, actor_xy=None, tolerance=0.08, mesh_tolerance=0.04):
|
| 81 |
+
origin, R, depth, fx, fy, tolerance = _inputs(camera_pos, quat_XYZW, depth_1280x640, fx, fy, tolerance)
|
| 82 |
+
mesh_tolerance = float(mesh_tolerance)
|
| 83 |
+
if not math.isfinite(mesh_tolerance) or not 0 <= mesh_tolerance <= 0.05:
|
| 84 |
+
raise ValueError('Mesh/depth tolerance must be between 0 and 0.05 metres.')
|
| 85 |
+
p = np.asarray(point, dtype=float)
|
| 86 |
+
if p.shape != (2,) or not np.all(np.isfinite(p)) or (not (0 <= p[0] < 1280 and 0 <= p[1] < 640)):
|
| 87 |
+
return None
|
| 88 |
+
ix, iy = (min(1279, int(math.floor(p[0] + 0.5))), min(639, int(math.floor(p[1] + 0.5))))
|
| 89 |
+
observed = float(depth[iy, ix])
|
| 90 |
+
if not math.isfinite(observed) or observed <= 0:
|
| 91 |
+
return None
|
| 92 |
+
camera_ray = np.array([(ix - float(cx)) / fx, -(iy - float(cy)) / fy, -1.0])
|
| 93 |
+
world_ray = R @ camera_ray
|
| 94 |
+
actor = origin[:2] if actor_xy is None else np.asarray(actor_xy, dtype=float).reshape(2)
|
| 95 |
+
if not np.all(np.isfinite(actor)):
|
| 96 |
+
raise ValueError('Actor XY must be finite.')
|
| 97 |
+
matches = []
|
| 98 |
+
for candidate in candidates:
|
| 99 |
+
lo, hi = _box(candidate)
|
| 100 |
+
interval = _slab(origin, world_ray, lo, hi)
|
| 101 |
+
if interval is None:
|
| 102 |
+
continue
|
| 103 |
+
near, far = interval
|
| 104 |
+
if observed < near - tolerance or observed > far + min(tolerance, 0.001):
|
| 105 |
+
continue
|
| 106 |
+
mesh_depth, triangle_index = (None, None)
|
| 107 |
+
if 'triangles' in candidate:
|
| 108 |
+
intersection = _triangle_hit(origin, world_ray, candidate['triangles'])
|
| 109 |
+
if intersection is None:
|
| 110 |
+
continue
|
| 111 |
+
mesh_depth, triangle_index = intersection
|
| 112 |
+
if abs(mesh_depth - observed) > mesh_tolerance:
|
| 113 |
+
continue
|
| 114 |
+
footprint = np.clip(actor, lo[:2], hi[:2])
|
| 115 |
+
distance = float(np.linalg.norm(actor - footprint))
|
| 116 |
+
error = abs(observed - (mesh_depth if mesh_depth is not None else near))
|
| 117 |
+
volume = float(np.prod(np.maximum(hi - lo, 1e-08)))
|
| 118 |
+
hit = {'key': candidate['key'], 'room': candidate['room'], 'distance': distance, 'visible': True, 'occluded': False, 'point': [ix, iy], 'observed_depth': observed, 'aabb_near_depth': near, 'aabb_far_depth': far, 'depth_surface_error': error, 'depth_tolerance': tolerance, 'mesh_verified': mesh_depth is not None, 'mesh_depth': mesh_depth, 'mesh_tolerance': mesh_tolerance, 'triangle_index': triangle_index, 'world_hit': (origin + world_ray * observed).tolist(), 'lo': lo.tolist(), 'hi': hi.tolist(), 'ray_depth_units': 'camera_forward_z'}
|
| 119 |
+
matches.append((error, volume, near, hit))
|
| 120 |
+
if not matches:
|
| 121 |
+
return None
|
| 122 |
+
best_error = min((row[0] for row in matches))
|
| 123 |
+
near_surface = [row for row in matches if row[0] <= best_error + 0.001]
|
| 124 |
+
return min(near_surface, key=lambda row: (row[1], row[2], row[0]))[3]
|
| 125 |
+
|
| 126 |
+
def projected_bbox(candidate, camera_pos, quat_XYZW, *, fx=640.0, fy=None, cx=640.0, cy=320.0):
|
| 127 |
+
origin = np.asarray(camera_pos, dtype=float).reshape(3)
|
| 128 |
+
R = _rotation(quat_XYZW)
|
| 129 |
+
lo, hi = _box(candidate)
|
| 130 |
+
world = np.array(list(itertools.product(*zip(lo, hi))))
|
| 131 |
+
camera = (world - origin) @ R
|
| 132 |
+
near = 0.0001
|
| 133 |
+
points = [v for v in camera if -v[2] >= near]
|
| 134 |
+
for i in range(8):
|
| 135 |
+
for mask in (1, 2, 4):
|
| 136 |
+
j = i ^ mask
|
| 137 |
+
if i >= j:
|
| 138 |
+
continue
|
| 139 |
+
a, b = (camera[i], camera[j])
|
| 140 |
+
za, zb = (-a[2], -b[2])
|
| 141 |
+
if (za < near) != (zb < near):
|
| 142 |
+
u = (near - za) / (zb - za)
|
| 143 |
+
points.append(a + u * (b - a))
|
| 144 |
+
if not points:
|
| 145 |
+
return None
|
| 146 |
+
points = np.asarray(points)
|
| 147 |
+
fy = fx if fy is None else fy
|
| 148 |
+
xs = float(cx) + float(fx) * points[:, 0] / -points[:, 2]
|
| 149 |
+
ys = float(cy) - float(fy) * points[:, 1] / -points[:, 2]
|
| 150 |
+
x0, x1, y0, y1 = (float(xs.min()), float(xs.max()), float(ys.min()), float(ys.max()))
|
| 151 |
+
if x1 < 0 or x0 > 1279 or y1 < 0 or (y0 > 639):
|
| 152 |
+
return None
|
| 153 |
+
return [max(0.0, x0), max(0.0, y0), min(1279.0, x1), min(639.0, y1)]
|
| 154 |
+
|
| 155 |
+
def find_point(key, camera_pos, quat_XYZW, depth_1280x640, candidates, *, fx=640.0, fy=None, cx=640.0, cy=320.0, actor_xy=None, tolerance=0.08, mesh_tolerance=0.04, grid=25, return_hit=False):
|
| 156 |
+
_inputs(camera_pos, quat_XYZW, depth_1280x640, fx, fy, tolerance)
|
| 157 |
+
if type(grid) is not int or not 2 <= grid <= 101:
|
| 158 |
+
raise ValueError('grid must be an integer from 2 to 101.')
|
| 159 |
+
candidates = list(candidates)
|
| 160 |
+
matches = [c for c in candidates if c.get('key') == key]
|
| 161 |
+
for candidate in matches:
|
| 162 |
+
box = projected_bbox(candidate, camera_pos, quat_XYZW, fx=fx, fy=fy, cx=cx, cy=cy)
|
| 163 |
+
if box is None:
|
| 164 |
+
continue
|
| 165 |
+
x0, y0, x1, y1 = box
|
| 166 |
+
xs = np.unique(np.rint(np.linspace(x0, x1, min(grid, max(2, int(math.ceil(x1 - x0)) + 1))))).astype(int)
|
| 167 |
+
ys = np.unique(np.rint(np.linspace(y0, y1, min(grid, max(2, int(math.ceil(y1 - y0)) + 1))))).astype(int)
|
| 168 |
+
midx, midy = ((x0 + x1) / 2, (y0 + y1) / 2)
|
| 169 |
+
samples = sorted(itertools.product(xs, ys), key=lambda p: (p[0] - midx) ** 2 + (p[1] - midy) ** 2)
|
| 170 |
+
for x, y in samples:
|
| 171 |
+
hit = pick([int(x), int(y)], camera_pos, quat_XYZW, depth_1280x640, candidates, fx=fx, fy=fy, cx=cx, cy=cy, actor_xy=actor_xy, tolerance=tolerance, mesh_tolerance=mesh_tolerance)
|
| 172 |
+
if hit is not None and hit['key'] == key:
|
| 173 |
+
return hit if return_hit else hit['point']
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
def self_test():
|
| 177 |
+
camera = [0, 0, 0]
|
| 178 |
+
q = [0, 0, 0, 1]
|
| 179 |
+
target = {'key': 'object', 'room': 'A', 'lo': [-0.2, -0.2, -2.1], 'hi': [0.2, 0.2, -1.9]}
|
| 180 |
+
depth = np.full((640, 1280), 1.9, dtype=np.float32)
|
| 181 |
+
tests = []
|
| 182 |
+
|
| 183 |
+
def check(name, condition):
|
| 184 |
+
assert condition, name
|
| 185 |
+
tests.append(name)
|
| 186 |
+
h = pick([640, 320], camera, q, depth, [target])
|
| 187 |
+
check('front_hit', h is not None and h['key'] == 'object')
|
| 188 |
+
check('z_depth_not_ray_length', h['ray_depth_units'] == 'camera_forward_z')
|
| 189 |
+
check('occluder_rejected', pick([640, 320], camera, q, np.full_like(depth, 1.0), [target]) is None)
|
| 190 |
+
check('hole_background_rejected', pick([640, 320], camera, q, np.full_like(depth, 2.3), [target]) is None)
|
| 191 |
+
check('close_hole_background_rejected', pick([640, 320], camera, q, np.full_like(depth, 2.11), [target]) is None)
|
| 192 |
+
check('outside_box_rejected', pick([0, 0], camera, q, depth, [target]) is None)
|
| 193 |
+
check('invalid_zero_depth', pick([640, 320], camera, q, np.zeros_like(depth), [target]) is None)
|
| 194 |
+
check('invalid_inf_depth', pick([640, 320], camera, q, np.full_like(depth, np.inf), [target]) is None)
|
| 195 |
+
check('invalid_nan_depth', pick([640, 320], camera, q, np.full_like(depth, np.nan), [target]) is None)
|
| 196 |
+
check('no_text_argument', 'target' not in __import__('inspect').signature(pick).parameters)
|
| 197 |
+
child = {'key': 'small', 'room': 'A', 'lo': [-0.05, -0.05, -2.0], 'hi': [0.05, 0.05, -1.9]}
|
| 198 |
+
check('nested_small_surface', pick([640, 320], camera, q, depth, [target, child])['key'] == 'small')
|
| 199 |
+
rotq = [0, -math.sqrt(0.5), 0, math.sqrt(0.5)]
|
| 200 |
+
side = {'key': 'right', 'room': 'B', 'lo': [1.9, -0.2, -0.2], 'hi': [2.1, 0.2, 0.2]}
|
| 201 |
+
sidehit = pick([640, 320], camera, rotq, depth, [side], actor_xy=[0, 1])
|
| 202 |
+
check('xyzw_rotation', sidehit is not None and sidehit['key'] == 'right')
|
| 203 |
+
check('footprint_distance', abs(sidehit['distance'] - math.hypot(1.9, 0.8)) < 1e-06)
|
| 204 |
+
point = find_point('object', camera, q, depth, [target])
|
| 205 |
+
check('oracle_point_rechecks', point is not None and pick(point, camera, q, depth, [target])['key'] == 'object')
|
| 206 |
+
check('oracle_occlusion_no_bypass', find_point('object', camera, q, np.ones_like(depth), [target]) is None)
|
| 207 |
+
check('oracle_missing_no_bypass', find_point('absent', camera, q, depth, [target]) is None)
|
| 208 |
+
narrow = np.full_like(depth, 1.0)
|
| 209 |
+
narrow[320, 640] = 1.9
|
| 210 |
+
check('oracle_visible_pixel', find_point('object', camera, q, narrow, [target]) == [640, 320])
|
| 211 |
+
off = {'key': 'off', 'room': 'A', 'lo': [1.6, -0.1, -2.1], 'hi': [2.0, 0.1, -1.9]}
|
| 212 |
+
check('off_axis_z_depth', pick([1240, 320], camera, q, depth, [off]) is not None)
|
| 213 |
+
rejected = False
|
| 214 |
+
try:
|
| 215 |
+
pick([640, 320], camera, q, depth, [target], tolerance=0.081)
|
| 216 |
+
except ValueError:
|
| 217 |
+
rejected = True
|
| 218 |
+
check('tolerance_max_008', rejected)
|
| 219 |
+
|
| 220 |
+
def quad(x0, x1, y0, y1, z):
|
| 221 |
+
return np.array([[[x0, y0, z], [x1, y0, z], [x1, y1, z]], [[x0, y0, z], [x1, y1, z], [x0, y1, z]]], dtype=float)
|
| 222 |
+
solid = dict(target, triangles=quad(-0.2, 0.2, -0.2, 0.2, -1.9))
|
| 223 |
+
check('triangle_front_hit', pick([640, 320], camera, q, depth, [solid])['mesh_verified'])
|
| 224 |
+
reverse = dict(solid, triangles=solid['triangles'][:, ::-1, :])
|
| 225 |
+
check('triangle_double_sided', pick([640, 320], camera, q, depth, [reverse])['mesh_verified'])
|
| 226 |
+
hole = dict(target, triangles=np.concatenate([quad(-0.2, -0.05, -0.2, 0.2, -1.9), quad(0.05, 0.2, -0.2, 0.2, -1.9)]))
|
| 227 |
+
check('triangle_hole_no_bbox_fallback', pick([640, 320], camera, q, depth, [hole]) is None)
|
| 228 |
+
check('triangle_empty_no_bbox_fallback', pick([640, 320], camera, q, depth, [dict(target, triangles=[])]) is None)
|
| 229 |
+
check('triangle_native_depth_mismatch', pick([640, 320], camera, q, np.full_like(depth, 1.85), [solid]) is None)
|
| 230 |
+
layers = dict(target, triangles=np.concatenate([quad(-0.2, 0.2, -0.2, 0.2, -1.9), quad(-0.2, 0.2, -0.2, 0.2, -2.0)]))
|
| 231 |
+
check('triangle_nearest_surface_only', pick([640, 320], camera, q, np.full_like(depth, 2.0), [layers]) is None)
|
| 232 |
+
offmesh = dict(off, triangles=quad(1.6, 2.0, -0.1, 0.1, -1.9))
|
| 233 |
+
check('triangle_nonunit_ray_z', abs(pick([1240, 320], camera, q, depth, [offmesh])['mesh_depth'] - 1.9) < 1e-06)
|
| 234 |
+
oracle_hit = find_point('object', camera, q, depth, [hole], return_hit=True)
|
| 235 |
+
check('triangle_oracle_rechecks_mesh', oracle_hit is not None and oracle_hit['mesh_verified'] and (oracle_hit['point'] != [640, 320]))
|
| 236 |
+
rejected = False
|
| 237 |
+
try:
|
| 238 |
+
pick([640, 320], camera, q, depth, [solid], mesh_tolerance=0.051)
|
| 239 |
+
except ValueError:
|
| 240 |
+
rejected = True
|
| 241 |
+
check('triangle_tolerance_max_005', rejected)
|
| 242 |
+
import json
|
| 243 |
+
print(json.dumps({'passed': len(tests), 'checks': tests, 'sdk_loaded': False, 'api_calls': 0}))
|
| 244 |
+
if __name__ == '__main__':
|
| 245 |
+
self_test()
|
runtime/h2_runtime/preview_four.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, copy, json, hashlib
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
def capture(d):
|
| 5 |
+
from pxr import UsdGeom, Usd, UsdLux
|
| 6 |
+
initial = copy.deepcopy(d.game.snapshot())
|
| 7 |
+
out = d.run / 'screenshots/initial'
|
| 8 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 9 |
+
stage = d.og.sim.stage
|
| 10 |
+
hidden = []
|
| 11 |
+
bounds = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_, UsdGeom.Tokens.render], useExtentsHint=True)
|
| 12 |
+
for p in stage.Traverse():
|
| 13 |
+
if not (p.IsA(UsdGeom.Mesh) or p.IsA(UsdLux.RectLight)):
|
| 14 |
+
continue
|
| 15 |
+
if any((k in p.GetName().lower() for k in ['ceiling', 'roof', 'beam', 'lamp', 'lintel'])):
|
| 16 |
+
try:
|
| 17 |
+
above = bounds.ComputeWorldBound(p).ComputeAlignedBox().GetMin()[2] > 2
|
| 18 |
+
except Exception:
|
| 19 |
+
above = False
|
| 20 |
+
if above:
|
| 21 |
+
at = UsdGeom.Imageable(p).GetVisibilityAttr()
|
| 22 |
+
hidden.append((at, at.HasAuthoredValueOpinion(), at.Get()))
|
| 23 |
+
with d.og.sim.editing_usd():
|
| 24 |
+
UsdGeom.Imageable(p).CreateVisibilityAttr().Set(UsdGeom.Tokens.invisible)
|
| 25 |
+
try:
|
| 26 |
+
with d.og.sim.editing_usd():
|
| 27 |
+
UsdLux.DomeLight.Define(stage, '/World/medium_overview_fill').CreateIntensityAttr(1000.0)
|
| 28 |
+
d.camera.set_attribute('projection', 'orthographic')
|
| 29 |
+
d.camera.horizontal_aperture = 108.0
|
| 30 |
+
d.camera.set_attribute('verticalAperture', 54.0)
|
| 31 |
+
d.raw([4.8, 2.5, 6.8], [4.8, 2.5, 0], warm=24).save(out / 'top.png')
|
| 32 |
+
finally:
|
| 33 |
+
with d.og.sim.editing_usd():
|
| 34 |
+
stage.RemovePrim('/World/medium_overview_fill')
|
| 35 |
+
for at, authored, val in hidden:
|
| 36 |
+
if authored:
|
| 37 |
+
at.Set(val)
|
| 38 |
+
else:
|
| 39 |
+
at.Clear()
|
| 40 |
+
d.camera.set_attribute('projection', 'perspective')
|
| 41 |
+
d.camera.horizontal_aperture = 28.0
|
| 42 |
+
d.camera.set_attribute('verticalAperture', 14.0)
|
| 43 |
+
for room, pos in [('A', [2.4, 2.0, 1.35]), ('B', [7.2, 2.0, 1.35])]:
|
| 44 |
+
for name, a in [('front', 90), ('back', 270), ('left', 180), ('right', 0)]:
|
| 45 |
+
f = [math.cos(math.radians(a)), math.sin(math.radians(a)), 0]
|
| 46 |
+
look = [x + y for x, y in zip(pos, f)]
|
| 47 |
+
d.raw(pos, look, warm=16).save(out / f'room_{room}_{name}.png')
|
| 48 |
+
assert d.game.snapshot() == initial
|
| 49 |
+
d.frame(warm=24)
|
| 50 |
+
records = {p.name: {'path': str(p), 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} for p in out.glob('*.png')}
|
| 51 |
+
assert len(records) == 9
|
| 52 |
+
(out / 'CAPTURE.json').write_text(json.dumps({'images': records, 'presentation_only': True, 'initial_state_unchanged': True, 'room_stands': {'A': [2.4, 2.0, 1.35], 'B': [7.2, 2.0, 1.35]}, 'native_images': 9, 'model_calls': 0}, ensure_ascii=False, indent=2), encoding='utf-8')
|
runtime/h2_runtime/protocol.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
ACTIONS = ('walk', 'turn', 'step_back', 'side_step', 'open', 'close', 'take', 'read', 'unlock', 'use', 'press', 'recall')
|
| 6 |
+
POINTED = ('open', 'close', 'take', 'read', 'unlock', 'use', 'press')
|
| 7 |
+
FIELDS = set('thought action distance direction degrees point photo target part code item query note drop_notes'.split())
|
| 8 |
+
|
| 9 |
+
def read_json(path):
|
| 10 |
+
return json.loads(Path(path).read_text(encoding='utf-8-sig'))
|
| 11 |
+
|
| 12 |
+
def save_json(path, value):
|
| 13 |
+
path = Path(path)
|
| 14 |
+
temp = path.with_name(path.name + '.tmp')
|
| 15 |
+
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
|
| 16 |
+
os.replace(temp, path)
|
| 17 |
+
|
| 18 |
+
def number(x, low, high, label):
|
| 19 |
+
if type(x) not in (int, float) or not math.isfinite(x) or (not low <= x <= high):
|
| 20 |
+
raise ValueError(label + ' 超出范围')
|
| 21 |
+
|
| 22 |
+
def validate_action(action, recalls_left=5):
|
| 23 |
+
if not isinstance(action, dict) or set(action) - FIELDS:
|
| 24 |
+
raise ValueError('动作包含未知或内部字段')
|
| 25 |
+
a = dict(action)
|
| 26 |
+
kind = a.get('action')
|
| 27 |
+
if kind not in ACTIONS:
|
| 28 |
+
raise ValueError('不支持的动作;note 应附在一个动作上')
|
| 29 |
+
for key in ('thought', 'target', 'code', 'item', 'query', 'note'):
|
| 30 |
+
if key in a and (not isinstance(a[key], str) or len(a[key]) > (200 if key == 'note' else 500)):
|
| 31 |
+
raise ValueError(key + ' 必须是长度合适的文字')
|
| 32 |
+
if kind == 'recall' and recalls_left <= 0:
|
| 33 |
+
raise ValueError('Recalls left 为 0,不能再 recall')
|
| 34 |
+
if kind == 'walk':
|
| 35 |
+
number(a.get('distance'), 0.1, 1.0, 'distance')
|
| 36 |
+
if a.get('distance') not in (0.25, 0.5, 1.0):
|
| 37 |
+
raise ValueError('walk 距离为 0.25/0.5/1 米')
|
| 38 |
+
if kind in ('step_back', 'side_step'):
|
| 39 |
+
number(a.get('distance'), 0.1, 0.6 if kind == 'step_back' else 0.5, 'distance')
|
| 40 |
+
if kind == 'turn':
|
| 41 |
+
number(a.get('degrees'), 10, 120, 'degrees')
|
| 42 |
+
if kind in ('turn', 'side_step') and a.get('direction') not in (('left', 'right', 'up', 'down') if kind == 'turn' else ('left', 'right')):
|
| 43 |
+
raise ValueError('direction 不合法')
|
| 44 |
+
if 'point' in a:
|
| 45 |
+
p = a['point']
|
| 46 |
+
if not isinstance(p, list) or len(p) != 2:
|
| 47 |
+
raise ValueError('point 需要 [x,y]')
|
| 48 |
+
number(p[0], 0, 640, 'x')
|
| 49 |
+
number(p[1], 0, 360, 'y')
|
| 50 |
+
if 'photo' in a and (type(a['photo']) is not int or not 1 <= a['photo'] <= 2):
|
| 51 |
+
raise ValueError('photo 为当前观察组图片编号')
|
| 52 |
+
held_item_only = kind in ('read', 'unlock', 'use') and 'point' not in a and bool(a.get('item', '').strip())
|
| 53 |
+
if kind in POINTED and (not a.get('target', '').strip()) and (not held_item_only):
|
| 54 |
+
raise ValueError('请填写你指的物体名称 target')
|
| 55 |
+
if kind in ('open', 'close', 'take', 'press') and 'point' not in a:
|
| 56 |
+
raise ValueError('先点击当前图片选择物体')
|
| 57 |
+
if kind in ('read', 'unlock', 'use') and 'point' not in a and (not (a.get('target') or a.get('item'))):
|
| 58 |
+
raise ValueError('需要点击目标或填写手中物品')
|
| 59 |
+
if 'part' in a and (type(a['part']) is not int or not 1 <= a['part'] <= 30):
|
| 60 |
+
raise ValueError('part 为从1开始的层号')
|
| 61 |
+
drops = a.get('drop_notes', [])
|
| 62 |
+
if not isinstance(drops, list) or len(drops) > 20 or any((type(i) is not int or i < 1 for i in drops)):
|
| 63 |
+
raise ValueError('drop_notes 为笔记编号列表')
|
| 64 |
+
a.setdefault('thought', 'Human player choice.')
|
| 65 |
+
return a
|
| 66 |
+
|
| 67 |
+
class Catalog:
|
| 68 |
+
|
| 69 |
+
def __init__(self, support):
|
| 70 |
+
self.support = Path(support).resolve()
|
| 71 |
+
self.paths = {}
|
| 72 |
+
self.rows = []
|
| 73 |
+
manifest = read_json(self.support / 'manifest.json')
|
| 74 |
+
import hashlib, re
|
| 75 |
+
for name, digest in manifest['resource_hashes'].items():
|
| 76 |
+
if not name.startswith('catalog/') or not re.match('^(?:L[1-3]|H1)-\\d{2}_', Path(name).name):
|
| 77 |
+
continue
|
| 78 |
+
path = self.support / name
|
| 79 |
+
if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
|
| 80 |
+
raise ValueError('关卡快照校验失败')
|
| 81 |
+
cfg = read_json(path)
|
| 82 |
+
key = cfg['name'].split('_', 1)[0]
|
| 83 |
+
difficulty = key.split('-')[0]
|
| 84 |
+
cap = {'L1': 80, 'L2': 120, 'L3': 180, 'H1': 200}[difficulty]
|
| 85 |
+
if cfg['max_steps'] != cap or key in self.paths:
|
| 86 |
+
raise ValueError('关卡编号/预算不一致')
|
| 87 |
+
self.paths[key] = path
|
| 88 |
+
mode = '多房间' if difficulty == 'H1' else '单房间'
|
| 89 |
+
self.rows.append(dict(id=key, name=f'{key} · {mode}', difficulty=difficulty, steps=cap, config=key))
|
| 90 |
+
self.rows.sort(key=lambda r: (('L1', 'L2', 'L3', 'H1').index(r['difficulty']), r['id']))
|
| 91 |
+
if len(self.rows) != 145:
|
| 92 |
+
raise ValueError('有效关卡应为145关')
|
| 93 |
+
|
| 94 |
+
def public(self):
|
| 95 |
+
return {'levels': self.rows, 'action_schema': {'actions': list(ACTIONS), 'point_size': [640, 360], 'note_mode': 'attach_to_action', 'note_limit': 20, 'note_length': 200, 'recent_steps': 10, 'recall_separate': True, 'hint_once': True, 'no_early_stop': True}}
|
| 96 |
+
|
| 97 |
+
def assert_current_benchmark(settings, root):
|
| 98 |
+
import hashlib
|
| 99 |
+
config = read_json(settings['project_config'])
|
| 100 |
+
current = Path(config['host_settings']['local']['ESI_BUDGET_SUPPORT']).resolve()
|
| 101 |
+
if Path(settings['support']).resolve() != current:
|
| 102 |
+
raise ValueError('Game snapshot differs from current model snapshot; synchronize game first')
|
| 103 |
+
pins = settings['benchmark_sync']
|
| 104 |
+
entry = Path(config['worker_entry']['local'])
|
| 105 |
+
entry_bytes = entry.read_bytes()
|
| 106 |
+
digest = lambda value: hashlib.sha256(value).hexdigest()
|
| 107 |
+
if digest(entry_bytes) != config['worker_entry']['sha256'] or digest(entry_bytes) != pins['entry_sha256']:
|
| 108 |
+
raise ValueError('Game/model entry SHA mismatch')
|
| 109 |
+
if digest((current / 'manifest.json').read_bytes()) != pins['manifest_sha256']:
|
| 110 |
+
raise ValueError('Game/model manifest SHA mismatch')
|
| 111 |
+
manifest = read_json(current / 'manifest.json')
|
| 112 |
+
for group in ('hashes', 'resource_hashes'):
|
| 113 |
+
for name, expected in manifest.get(group, {}).items():
|
| 114 |
+
if digest((current / name).read_bytes()) != expected:
|
| 115 |
+
raise ValueError('Formal snapshot hash mismatch: ' + name)
|
| 116 |
+
source = entry_bytes.decode('utf-8')
|
| 117 |
+
needle = "sys.argv=[str(script)];globals()['__file__']=str(script)"
|
| 118 |
+
install = "from _human252 import install_human\ninstall_human(_escape,sys.modules['_escape_claw'],m,sys.modules['_escape_video163'])\n"
|
| 119 |
+
expected = source.replace(needle, install + needle).encode('utf-8')
|
| 120 |
+
actual = (Path(root) / 'human_entry.py').read_bytes()
|
| 121 |
+
if source.count(needle) != 1 or actual != expected or digest(actual) != settings['human_entry_sha256']:
|
| 122 |
+
raise ValueError('Human entry must be exact current model entry plus human-policy installation')
|
| 123 |
+
return config
|
runtime/h2_runtime/rack_press_quality.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
class RackGameMixin:
|
| 4 |
+
RACK_SOLVED_STAGE = 0
|
| 5 |
+
RACK_TARGET = (0, 1, 2, 3)
|
| 6 |
+
RACK_CHECK_ENABLED = True
|
| 7 |
+
|
| 8 |
+
def __init__(self):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.states[0].update(quality_check_presses=0, quality_reset_presses=0, quality_rack_released=False)
|
| 11 |
+
|
| 12 |
+
def _whole(self):
|
| 13 |
+
super()._whole()
|
| 14 |
+
if self.RACK_CHECK_ENABLED:
|
| 15 |
+
released = bool(self.states[0].get('quality_rack_released', False))
|
| 16 |
+
self.solved[self.RACK_SOLVED_STAGE] = released
|
| 17 |
+
self.reward_open[self.RACK_SOLVED_STAGE] = released
|
| 18 |
+
|
| 19 |
+
def act(self, a):
|
| 20 |
+
if a.get('_validated364') and a.get('action') == 'press':
|
| 21 |
+
key = a.get('_hit364')
|
| 22 |
+
if key == 's1_check' and self.RACK_CHECK_ENABLED:
|
| 23 |
+
state = self.states[0]
|
| 24 |
+
state['quality_check_presses'] += 1
|
| 25 |
+
if tuple((state['assignment'].get(i) for i in range(4))) == self.RACK_TARGET:
|
| 26 |
+
state['quality_rack_released'] = True
|
| 27 |
+
self._whole()
|
| 28 |
+
return {'ok': True, 'text': ''}
|
| 29 |
+
if key == 's1_reset':
|
| 30 |
+
self.states[0]['quality_reset_presses'] += 1
|
| 31 |
+
return super().act(a)
|
| 32 |
+
|
| 33 |
+
class RackSceneMixin:
|
| 34 |
+
RACK_CHECK_ENABLED = True
|
| 35 |
+
|
| 36 |
+
def controls_for(self, i, s, root):
|
| 37 |
+
super().controls_for(i, s, root)
|
| 38 |
+
if i != 0 or not self.RACK_CHECK_ENABLED:
|
| 39 |
+
return
|
| 40 |
+
self.label('quality_check_legend', 'CHECK', [0, -0.04, 0], 0.11, 0.028, parent=self.target_nodes['s1_check'])
|
| 41 |
+
self.label('quality_reset_legend', 'RESET', [0, -0.04, 0], 0.11, 0.028, parent=self.target_nodes['s1_reset'])
|
| 42 |
+
if self.spec['id'] == 'R23':
|
| 43 |
+
base = [0, -0.225, 1.205]
|
| 44 |
+
lock = self.group('quality_tool_lock_bar', base, root)
|
| 45 |
+
self.tube('tool_box_retaining_bar', [-0.72, 0, 0], [0.72, 0, 0], 0.012, 'steel', lock)
|
| 46 |
+
for x in (-0.75, 0.75):
|
| 47 |
+
self.box('grounded_bar_guide', [x, -0.16, 1.13625], [0.035, 0.075, 0.6875], 'iron', root)
|
| 48 |
+
self.box('bar_slide_foot', [x, -0.16, 0.8125], [0.12, 0.16, 0.04], 'steel', root)
|
| 49 |
+
self.tube('bar_sliding_shoe', [x, 0.065, -0.035], [x, 0, 0], 0.018, 'brass', lock)
|
| 50 |
+
self.custom['quality_lock_axis'] = 'z'
|
| 51 |
+
self.custom['quality_lock_travel'] = 0.25
|
| 52 |
+
self.tube('check_to_bar_vertical', [0.67, -0.17, 0.8], [0.67, -0.17, 1.185], 0.008, 'steel', root)
|
| 53 |
+
self.tube('sliding_check_link', [0.67, 0.055, -0.5], [0.67, 0.055, -0.02], 0.006, 'steel', lock)
|
| 54 |
+
self.tube('check_link_bar_elbow', [0.67, 0.055, -0.02], [0.67, 0, 0], 0.006, 'steel', lock)
|
| 55 |
+
else:
|
| 56 |
+
base = [0.54, -0.362, 0.59]
|
| 57 |
+
self.box('jug_bolt_side_support', [0.585, -0.27, 0.52], [0.055, 0.1, 0.44], 'iron', root)
|
| 58 |
+
self.box('jug_bolt_fixed_housing', [0.585, -0.33, 0.59], [0.07, 0.055, 0.065], 'iron', root)
|
| 59 |
+
lock = self.group('quality_jug_cabinet_bolt', base, root)
|
| 60 |
+
self.cylinder('solid_jug_slide_bolt', [0, 0, 0], 0.012, 0.15, 'steel', 'x', lock)
|
| 61 |
+
self.cylinder('jug_bolt_stop', [0.075, 0, 0], 0.02, 0.02, 'brass', 'x', lock)
|
| 62 |
+
self.custom['quality_lock_axis'] = 'x'
|
| 63 |
+
self.custom['quality_lock_travel'] = 0.13
|
| 64 |
+
self.tube('check_link_horizontal', [0.67, -0.17, 0.8], [0.6, -0.17, 0.8], 0.008, 'steel', root)
|
| 65 |
+
self.tube('check_link_elbow', [0.6, -0.17, 0.8], [0.6, -0.32, 0.8], 0.008, 'steel', root)
|
| 66 |
+
self.tube('check_link_to_jug_bolt', [0.6, -0.32, 0.8], [0.6, -0.32, 0.62], 0.008, 'steel', root)
|
| 67 |
+
self.custom['quality_rack_lock'] = lock
|
| 68 |
+
self.custom['quality_lock_base'] = base
|
| 69 |
+
|
| 70 |
+
def _quality_lock_pose(self, fraction):
|
| 71 |
+
if 'quality_rack_lock' not in self.custom:
|
| 72 |
+
return
|
| 73 |
+
position = list(self.custom['quality_lock_base'])
|
| 74 |
+
index = 2 if self.custom['quality_lock_axis'] == 'z' else 0
|
| 75 |
+
position[index] += self.custom['quality_lock_travel'] * fraction
|
| 76 |
+
self.transform(self.custom['quality_rack_lock'], position)
|
| 77 |
+
|
| 78 |
+
def sync(self, g):
|
| 79 |
+
super().sync(g)
|
| 80 |
+
if 'handle_s1_reset' in self.custom:
|
| 81 |
+
self.transform(self.custom['handle_s1_reset'], rpy=[0, -35, 0])
|
| 82 |
+
if self.RACK_CHECK_ENABLED:
|
| 83 |
+
released = bool(g.states[0].get('quality_rack_released'))
|
| 84 |
+
if 'handle_s1_check' in self.custom:
|
| 85 |
+
self.transform(self.custom['handle_s1_check'], rpy=[0, 35 if released else -35, 0])
|
| 86 |
+
self._quality_lock_pose(1 if released else 0)
|
| 87 |
+
for key in ('s1_check', 's1_reset'):
|
| 88 |
+
if key in self.target_nodes:
|
| 89 |
+
points = self.triangles(self.target_nodes[key]).reshape(-1, 3)
|
| 90 |
+
if points.size:
|
| 91 |
+
self.centres[key] = ((points.min(0) + points.max(0)) / 2).tolist()
|
| 92 |
+
|
| 93 |
+
def animate(self, d, before):
|
| 94 |
+
key = (d.current_hit or {}).get('key')
|
| 95 |
+
old, now = (before['states'][0], d.game.states[0])
|
| 96 |
+
reset = key == 's1_reset' and now['quality_reset_presses'] != old.get('quality_reset_presses', 0)
|
| 97 |
+
check = self.RACK_CHECK_ENABLED and key == 's1_check' and (now['quality_check_presses'] != old.get('quality_check_presses', 0))
|
| 98 |
+
if not reset and (not check):
|
| 99 |
+
return super().animate(d, before)
|
| 100 |
+
release_field = 'quality_rack_released' if self.RACK_CHECK_ENABLED else 'latch_released'
|
| 101 |
+
was = bool(old.get(release_field))
|
| 102 |
+
released = bool(now.get(release_field))
|
| 103 |
+
rows = []
|
| 104 |
+
for j, fraction in enumerate((0, 0.2, 0.4, 0.6, 0.8, 1)):
|
| 105 |
+
self.sync(d.game)
|
| 106 |
+
if reset:
|
| 107 |
+
angle = -35 + 70 * math.sin(math.pi * fraction)
|
| 108 |
+
self.transform(self.custom['handle_s1_reset'], rpy=[0, angle, 0])
|
| 109 |
+
for item in range(4):
|
| 110 |
+
k = 's1_item_' + str(item)
|
| 111 |
+
slot = next((z for z, value in old['assignment'].items() if value == item), None)
|
| 112 |
+
if slot is None or k not in self.props:
|
| 113 |
+
continue
|
| 114 |
+
start = self.custom['slot' + str(slot)]
|
| 115 |
+
rid = self.spec['id']
|
| 116 |
+
height = 0.91 if rid == 'R23' else 0.875 if rid == 'R24' else [0.885, 0.925, 0.895, 0.885][item]
|
| 117 |
+
finish = [(1.5 - item) * 0.37, -0.1, height]
|
| 118 |
+
self.transform(self.props[k], [a + (b - a) * fraction for a, b in zip(start, finish)])
|
| 119 |
+
lock_fraction = 1 if released else 0
|
| 120 |
+
else:
|
| 121 |
+
angle = 35 + 15 * math.sin(math.pi * fraction) if was else -35 + 70 * fraction if released else -35 + 50 * math.sin(math.pi * fraction)
|
| 122 |
+
lock_fraction = 1 if was else fraction if released else 0
|
| 123 |
+
self.transform(self.custom['handle_s1_check'], rpy=[0, angle, 0])
|
| 124 |
+
self._quality_lock_pose(lock_fraction)
|
| 125 |
+
d.frame(warm=4)
|
| 126 |
+
d.append('RESET returns rack pieces; acquired tools stay held' if reset else 'CHECK moves the actual retaining mechanism; only a complete correct rack releases it', 6)
|
| 127 |
+
if j in (2, 5):
|
| 128 |
+
d.capture_feedback_frame()
|
| 129 |
+
rows.append({'fraction': fraction, 'handle_angle_degrees': angle, 'lock_fraction': lock_fraction})
|
| 130 |
+
d.save('RACK_QUALITY_' + ('RESET' if reset else 'CHECK') + '.json', {'poses': rows, 'before_released': was, 'after_released': released, 'feedback_frames': 2, 'physical_action_only': True})
|
| 131 |
+
self.sync(d.game)
|
| 132 |
+
d.frame(warm=4)
|
| 133 |
+
|
| 134 |
+
def rack_feedback_standard(previous, check_enabled=True):
|
| 135 |
+
|
| 136 |
+
def standard(d):
|
| 137 |
+
if d.game.SPEC['id'] != 'R25':
|
| 138 |
+
return previous(d)
|
| 139 |
+
original = d.click
|
| 140 |
+
|
| 141 |
+
def click(key, kind='read', item=None, **fields):
|
| 142 |
+
if key == 's1_check' and kind == 'press':
|
| 143 |
+
d.aim(d.scene.world(0, [0.3, -0.28, 0.74]), 'Observe the CHECK handle and the actual jug-cabinet bolt together')
|
| 144 |
+
return original(key, kind, item=item, **fields)
|
| 145 |
+
d.click = click
|
| 146 |
+
try:
|
| 147 |
+
return previous(d)
|
| 148 |
+
finally:
|
| 149 |
+
d.click = original
|
| 150 |
+
return standard
|
| 151 |
+
|
| 152 |
+
class WheelFeedbackSceneMixin:
|
| 153 |
+
|
| 154 |
+
def button(self, key, parent, pos, symbol='circle', size=0.14):
|
| 155 |
+
if key != 's2_wheel_reverse':
|
| 156 |
+
return super().button(key, parent, pos, symbol, size)
|
| 157 |
+
from depth_four import DepthScene
|
| 158 |
+
old_target = self.target_nodes.get('s2_wheel')
|
| 159 |
+
old_handle = self.custom.get('handle_s2_wheel')
|
| 160 |
+
node = DepthScene.button(self, 's2_wheel', parent, pos, symbol, size)
|
| 161 |
+
reverse_handle = self.custom['handle_s2_wheel']
|
| 162 |
+
if old_target is None:
|
| 163 |
+
self.target_nodes.pop('s2_wheel', None)
|
| 164 |
+
else:
|
| 165 |
+
self.target_nodes['s2_wheel'] = old_target
|
| 166 |
+
if old_handle is None:
|
| 167 |
+
self.custom.pop('handle_s2_wheel', None)
|
| 168 |
+
else:
|
| 169 |
+
self.custom['handle_s2_wheel'] = old_handle
|
| 170 |
+
self.custom['handle_s2_wheel_reverse'] = reverse_handle
|
| 171 |
+
self.reg(key, node)
|
| 172 |
+
return node
|
| 173 |
+
|
| 174 |
+
def animate(self, d, before):
|
| 175 |
+
key = (d.current_hit or {}).get('key')
|
| 176 |
+
if key not in ('s2_wheel', 's2_wheel_reverse') or (d.current_action or {}).get('action') != 'press':
|
| 177 |
+
return super().animate(d, before)
|
| 178 |
+
state = d.game.states[1]
|
| 179 |
+
base = (45 if state.get('wheel_direction') == 1 else -35) if key.endswith('reverse') else 35 if state['slack'] else -35
|
| 180 |
+
direction = -1 if key.endswith('reverse') else 1
|
| 181 |
+
rows = []
|
| 182 |
+
for j, fraction in enumerate((0, 0.2, 0.4, 0.6, 0.8, 1)):
|
| 183 |
+
self.sync(d.game)
|
| 184 |
+
angle = base + direction * 360 * fraction
|
| 185 |
+
self.transform(self.custom['handle_' + key], rpy=[0, angle, 0])
|
| 186 |
+
d.frame(warm=4)
|
| 187 |
+
d.append('The wind/unwind crank turns; the rope responds only to its real support and routing', 6)
|
| 188 |
+
if j in (2, 5):
|
| 189 |
+
d.capture_feedback_frame()
|
| 190 |
+
rows.append({'fraction': fraction, 'angle_degrees': angle})
|
| 191 |
+
d.save('WHEEL_QUALITY_' + key + '.json', {'poses': rows, 'direction': direction, 'feedback_frames': 2, 'rule_state_unchanged_by_animation': True})
|
| 192 |
+
self.sync(d.game)
|
| 193 |
+
d.frame(warm=4)
|
| 194 |
+
|
| 195 |
+
class ReadingCabinetSceneMixin:
|
| 196 |
+
READING_RECORD_POS = (1.45, -0.32, 1.3)
|
| 197 |
+
READING_GATE_POS = (1.45, -0.36, 1.3)
|
| 198 |
+
|
| 199 |
+
def gate(self, key, parent, pos, w=0.6, h=0.5):
|
| 200 |
+
if key == 's3_open':
|
| 201 |
+
pos = list(self.READING_GATE_POS)
|
| 202 |
+
w, h = (0.82, 0.56)
|
| 203 |
+
return super().gate(key, parent, pos, w, h)
|
| 204 |
+
|
| 205 |
+
def core_card(self, i, root, reward):
|
| 206 |
+
super().core_card(i, root, reward)
|
| 207 |
+
if i != 2:
|
| 208 |
+
return
|
| 209 |
+
self.transform(self.custom['clue_B'], list(self.READING_RECORD_POS))
|
| 210 |
+
for node in root['meshes']:
|
| 211 |
+
if node.get('prim') and node['prim'].GetName().startswith('record_mount'):
|
| 212 |
+
self.visibility(node, False)
|
| 213 |
+
cabinet = self.group('quality_standing_reading_cabinet', [1.45, -0.15, 1.3], root)
|
| 214 |
+
self.box('reading_cabinet_back', [0, 0.12, 0], [0.82, 0.035, 0.56], 'wood', cabinet)
|
| 215 |
+
for x in (-0.4, 0.4):
|
| 216 |
+
self.box('reading_cabinet_side', [x, 0, 0], [0.025, 0.3, 0.56], 'paint', cabinet)
|
| 217 |
+
for z in (-0.28, 0.28):
|
| 218 |
+
self.box('reading_cabinet_shelf', [0, 0, z], [0.82, 0.3, 0.025], 'wood', cabinet)
|
| 219 |
+
for x in (1.1, 1.8):
|
| 220 |
+
self.box('grounded_reading_cabinet_leg', [x, -0.1, 0.50375], [0.055, 0.14, 1.0075], 'iron', root)
|
| 221 |
+
self.label('quality_reading_cabinet_identity', 'ROOM B / READING CABINET', [1.45, -0.305, 1.6], 0.8, 0.07, parent=root)
|
| 222 |
+
self.custom['quality_reading_cabinet'] = cabinet
|
| 223 |
+
points = self.triangles(cabinet).reshape(-1, 3)
|
| 224 |
+
lo, hi = (points.min(0), points.max(0))
|
| 225 |
+
self.add_obstacle(lo[0], lo[1] - 0.08, hi[0], hi[1])
|
| 226 |
+
|
| 227 |
+
def sync(self, g):
|
| 228 |
+
super().sync(g)
|
| 229 |
+
if 'clue_B' in self.custom:
|
| 230 |
+
self.transform(self.custom['clue_B'], list(self.READING_RECORD_POS))
|
| 231 |
+
for key in ('clue_B', 's3_open'):
|
| 232 |
+
if key in self.target_nodes:
|
| 233 |
+
points = self.triangles(self.target_nodes[key]).reshape(-1, 3)
|
| 234 |
+
if points.size:
|
| 235 |
+
self.centres[key] = ((points.min(0) + points.max(0)) / 2).tolist()
|
| 236 |
+
|
| 237 |
+
def reading_cabinet_standard(previous):
|
| 238 |
+
|
| 239 |
+
def standard(d):
|
| 240 |
+
original_click, original_route, original_aim = (d.click, d.route, d.aim)
|
| 241 |
+
|
| 242 |
+
def route(destination, *args, **kwargs):
|
| 243 |
+
if list(destination) == [6.25, 3.5] and d.game.states[2].get('open'):
|
| 244 |
+
destination = [7.75, 3.5]
|
| 245 |
+
return original_route(destination, *args, **kwargs)
|
| 246 |
+
|
| 247 |
+
def aim(target, *args, **kwargs):
|
| 248 |
+
legacy = d.scene.world(2, [0, -0.32, 0.51])
|
| 249 |
+
if len(target) == len(legacy) and all((abs(float(a) - float(b)) < 1e-05 for a, b in zip(target, legacy))):
|
| 250 |
+
target = d.scene.world(2, list(d.scene.READING_RECORD_POS))
|
| 251 |
+
return original_aim(target, *args, **kwargs)
|
| 252 |
+
|
| 253 |
+
def click(key, kind='read', item=None, **fields):
|
| 254 |
+
if key in ('s3_open', 'clue_B'):
|
| 255 |
+
original_route([7.75, 3.5])
|
| 256 |
+
original_aim(d.scene.centres[key])
|
| 257 |
+
return original_click(key, kind, item=item, **fields)
|
| 258 |
+
d.click, d.route, d.aim = (click, route, aim)
|
| 259 |
+
try:
|
| 260 |
+
return previous(d)
|
| 261 |
+
finally:
|
| 262 |
+
d.click, d.route, d.aim = (original_click, original_route, original_aim)
|
| 263 |
+
return standard
|
| 264 |
+
|
| 265 |
+
class R34RuleLegibilitySceneMixin:
|
| 266 |
+
PAWL_RULE_LINES = ('The pawl stays latched without power.', 'Support the FIXED post to unload its rope; then push the pawl.', 'A fixed support carries the load; a sliding guide follows it.', 'WIND tightens. UNWIND releases only a supported rope.')
|
| 267 |
+
|
| 268 |
+
def textboard(self, key, parent, pos, lines, w=1.65, h=0.34):
|
| 269 |
+
if key == 'rope_rule':
|
| 270 |
+
return self.custom['quality_s2_rule_board']
|
| 271 |
+
if key == 's2_note':
|
| 272 |
+
pos, lines, w, h = ([0, 0.1, 1.72], list(self.PAWL_RULE_LINES), 1.65, 0.4)
|
| 273 |
+
for x in (-0.79, 0.79):
|
| 274 |
+
self.box('quality_rule_grounded_foot', [x, 0.13, 0.8125], [0.08, 0.12, 0.04], 'iron', parent)
|
| 275 |
+
self.box('quality_rule_stanchion', [x, 0.13, 1.34625], [0.025, 0.04, 1.1075], 'iron', parent)
|
| 276 |
+
node = super().textboard(key, parent, pos, lines, w, h)
|
| 277 |
+
self.custom['quality_s2_rule_board'] = node
|
| 278 |
+
return node
|
| 279 |
+
return super().textboard(key, parent, pos, lines, w, h)
|
| 280 |
+
|
| 281 |
+
def label(self, key, text, center, width, height, right=(1, 0, 0), up=(0, 0, 1), parent=None):
|
| 282 |
+
center = list(center)
|
| 283 |
+
if key == 'wind_label':
|
| 284 |
+
center[2] = 0.835
|
| 285 |
+
self.box('quality_wind_tag_mount', [center[0], -0.18, 0.835], [0.045, 0.045, 0.055], 'iron', parent)
|
| 286 |
+
self.box('quality_wind_tag_back', [center[0], -0.192, 0.835], [width + 0.015, 0.016, height + 0.012], 'cream', parent)
|
| 287 |
+
center[1] = -0.202
|
| 288 |
+
elif key.startswith('guide_label') and key[-1:] in ('0', '1'):
|
| 289 |
+
guide = self.custom['rope_guide' + key[-1]]
|
| 290 |
+
self.tube('guide_tag_bracket', [0, 0.035, -0.06], [0, -0.035, -0.105], 0.008, 'iron', guide)
|
| 291 |
+
self.box('guide_tag_back', [0, -0.035, -0.105], [width + 0.015, 0.025, height + 0.012], 'cream', guide)
|
| 292 |
+
return super().label(key, text, [0, -0.05, -0.105], width, height, right, up, guide)
|
| 293 |
+
elif key.startswith('output_label') and key[-1:] in ('0', '1'):
|
| 294 |
+
center = [center[0], 0.017, 1.36]
|
| 295 |
+
self.box('output_tag_support', [center[0], 0.05, 1.39], [0.035, 0.035, 0.12], 'iron', parent)
|
| 296 |
+
self.box('output_tag_back', [center[0], 0.031, 1.36], [width + 0.015, 0.025, height + 0.012], 'cream', parent)
|
| 297 |
+
return super().label(key, text, center, width, height, right, up, parent)
|
| 298 |
+
|
| 299 |
+
def r34_rule_legibility_standard(previous):
|
| 300 |
+
|
| 301 |
+
def standard(d):
|
| 302 |
+
original = d.click
|
| 303 |
+
|
| 304 |
+
def click(key, kind='read', item=None, **fields):
|
| 305 |
+
if key == 's2_note' and kind == 'read':
|
| 306 |
+
d.route([1.5, 2.75])
|
| 307 |
+
d.aim(d.scene.centres[key], 'Read the single complete pawl/rope rule board')
|
| 308 |
+
return original(key, kind, item=item, **fields)
|
| 309 |
+
d.click = click
|
| 310 |
+
try:
|
| 311 |
+
return previous(d)
|
| 312 |
+
finally:
|
| 313 |
+
d.click = original
|
| 314 |
+
return standard
|
| 315 |
+
|
| 316 |
+
class ReadingReleaseSceneMixin:
|
| 317 |
+
RELEASE_PIN_BASE = (1.45, -0.383, 1.02)
|
| 318 |
+
RELEASE_PIN_TRAVEL = 0.1
|
| 319 |
+
|
| 320 |
+
def core_card(self, i, root, reward):
|
| 321 |
+
super().core_card(i, root, reward)
|
| 322 |
+
if i != 2 or 'quality_record_release_pin' in self.custom:
|
| 323 |
+
return
|
| 324 |
+
rid = self.spec['id']
|
| 325 |
+
socket = {'R24': [0.79, -0.025, 1.23], 'R25': [0.79, 0.02, 1.02], 'R34': [0.755, -0.155, 1.25]}[rid]
|
| 326 |
+
self.cylinder('output_release_socket', socket, 0.018, 0.04, 'brass', 'x', root)
|
| 327 |
+
start = [socket[0] + 0.02, socket[1], socket[2]]
|
| 328 |
+
path = [start, [1.025, socket[1], socket[2]], [1.025, -0.27, socket[2]], [1.025, -0.27, 1.0], [1.025, -0.335, 1.0], [1.45, -0.335, 1.0]]
|
| 329 |
+
cable = self.group('quality_reading_release_bowden', parent=root)
|
| 330 |
+
for a, b in zip(path, path[1:]):
|
| 331 |
+
if sum(((x - y) ** 2 for x, y in zip(a, b))) > 1e-12:
|
| 332 |
+
self.tube('fixed_edge_bowden_sheath', a, b, 0.008, 'rubber', cable)
|
| 333 |
+
self.box('release_source_cable_clip', [socket[0] - 0.012, socket[1], socket[2]], [0.025, 0.04, 0.04], 'steel', root)
|
| 334 |
+
self.box('release_left_stile_clip', [1.04, -0.27, socket[2]], [0.04, 0.045, 0.035], 'steel', root)
|
| 335 |
+
self.box('release_lower_corner_clip', [1.04, -0.315, 1.0], [0.045, 0.04, 0.03], 'steel', root)
|
| 336 |
+
self.box('release_bottom_rail_clip', [1.25, -0.315, 1.0], [0.035, 0.04, 0.03], 'steel', root)
|
| 337 |
+
housing = self.box('fixed_reading_latch_housing', [1.45, -0.345, 0.98], [0.1, 0.1, 0.07], 'iron', root)
|
| 338 |
+
points = self.triangles(housing).reshape(-1, 3)
|
| 339 |
+
lo, hi = (points.min(0), points.max(0))
|
| 340 |
+
self.add_obstacle(lo[0], lo[1], hi[0], hi[1])
|
| 341 |
+
self.cylinder('bowden_frame_socket', [1.415, -0.335, 0.995], 0.014, 0.045, 'brass', 'x', root)
|
| 342 |
+
pin = self.group('quality_record_release_pin', list(self.RELEASE_PIN_BASE), root)
|
| 343 |
+
self.cylinder('reading_frame_vertical_pin', [0, 0, 0], 0.009, 0.16, 'steel', 'z', pin)
|
| 344 |
+
self.cylinder('reading_pin_stop', [0, 0, -0.075], 0.014, 0.018, 'brass', 'z', pin)
|
| 345 |
+
self.custom['quality_record_release_pin'] = pin
|
| 346 |
+
self.custom['quality_record_release_path'] = path
|
| 347 |
+
self.custom['quality_record_release_cable'] = cable
|
| 348 |
+
self.custom['quality_record_release_source_socket'] = socket
|
| 349 |
+
|
| 350 |
+
def sync(self, g):
|
| 351 |
+
super().sync(g)
|
| 352 |
+
pin = self.custom.get('quality_record_release_pin')
|
| 353 |
+
if pin is not None:
|
| 354 |
+
withdrawn = bool(g.solved[2] or g.states[2].get('open', False))
|
| 355 |
+
pos = list(self.RELEASE_PIN_BASE)
|
| 356 |
+
if withdrawn:
|
| 357 |
+
pos[2] -= self.RELEASE_PIN_TRAVEL
|
| 358 |
+
self.transform(pin, pos)
|
runtime/h2_runtime/room_art364.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from native_primitives364 import Art
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 6 |
+
from font_utils import load_font
|
| 7 |
+
|
| 8 |
+
class RoomArt(Art):
|
| 9 |
+
|
| 10 |
+
def __init__(self, og, run):
|
| 11 |
+
super().__init__(og, run)
|
| 12 |
+
self.obstacles = []
|
| 13 |
+
self.target_nodes = {}
|
| 14 |
+
self.heroes = []
|
| 15 |
+
self.room_rectangles = []
|
| 16 |
+
|
| 17 |
+
def group(self, key, pos=(0, 0, 0), parent=None):
|
| 18 |
+
node = super().group(key, pos, parent)
|
| 19 |
+
if parent is not None:
|
| 20 |
+
parent['meshes'].append(node)
|
| 21 |
+
return node
|
| 22 |
+
|
| 23 |
+
def triangles(self, node):
|
| 24 |
+
cache = self.G.XformCache()
|
| 25 |
+
result = []
|
| 26 |
+
|
| 27 |
+
def visit(n):
|
| 28 |
+
if 'points' in n:
|
| 29 |
+
T = cache.GetLocalToWorldTransform(n['prim'])
|
| 30 |
+
p = np.array([list(T.Transform(self.F.Vec3d(*x))) for x in n['points']])
|
| 31 |
+
for f in n['faces']:
|
| 32 |
+
for i in range(1, len(f) - 1):
|
| 33 |
+
result.append(p[[f[0], f[i], f[i + 1]]])
|
| 34 |
+
else:
|
| 35 |
+
for child in n.get('meshes', []):
|
| 36 |
+
visit(child)
|
| 37 |
+
visit(node)
|
| 38 |
+
return np.asarray(result, dtype=float).reshape((-1, 3, 3))
|
| 39 |
+
|
| 40 |
+
def add_target(self, key, node):
|
| 41 |
+
self.target_nodes[key] = node
|
| 42 |
+
return node
|
| 43 |
+
|
| 44 |
+
def base_candidates(self, keys=None):
|
| 45 |
+
return [self.candidate(k, self.target_nodes[k]) for k in (self.target_nodes if keys is None else keys)]
|
| 46 |
+
|
| 47 |
+
def add_obstacle(self, x0, y0, x1, y1):
|
| 48 |
+
self.obstacles.append(tuple(map(float, (x0, y0, x1, y1))))
|
| 49 |
+
|
| 50 |
+
def static_blocked(self, x, y, radius=0.12):
|
| 51 |
+
return any((x0 - radius < x < x1 + radius and y0 - radius < y < y1 + radius for x0, y0, x1, y1 in self.obstacles))
|
| 52 |
+
|
| 53 |
+
def label_image(self, key, text, width=1000, height=200):
|
| 54 |
+
im = Image.new('RGB', (width, height), (216, 207, 179))
|
| 55 |
+
d = ImageDraw.Draw(im)
|
| 56 |
+
lines = str(text).split('\n')
|
| 57 |
+
size = int(height * 0.64 / max(1, len(lines)))
|
| 58 |
+
while size > 9:
|
| 59 |
+
f = load_font(size)
|
| 60 |
+
if max((d.textbbox((0, 0), line, font=f)[2] for line in lines)) < width * 0.92:
|
| 61 |
+
break
|
| 62 |
+
size -= 1
|
| 63 |
+
total = len(lines) * (size + max(3, int(size * 0.18)))
|
| 64 |
+
y = (height - total) / 2
|
| 65 |
+
for line in lines:
|
| 66 |
+
box = d.textbbox((0, 0), line, font=f)
|
| 67 |
+
d.text(((width - box[2]) / 2, y), line, font=f, fill=(32, 45, 47))
|
| 68 |
+
y += size + max(3, int(size * 0.18))
|
| 69 |
+
p = self.tex / (key + '.png')
|
| 70 |
+
im.save(p)
|
| 71 |
+
return p
|
| 72 |
+
|
| 73 |
+
def label(self, key, text, center, width, height, right=(1, 0, 0), up=(0, 0, 1), parent=None):
|
| 74 |
+
p = self.label_image(key, text, 1200, max(140, int(1200 * height / max(width, 0.01))))
|
| 75 |
+
mat = self.mat('label_' + key, texture=p, rough=1.0)
|
| 76 |
+
with self.og.sim.editing_usd():
|
| 77 |
+
s = self.S.Shader(self.stage.GetPrimAtPath(str(mat.GetPath()) + '/surface'))
|
| 78 |
+
s.CreateInput('useSpecularWorkflow', self.D.ValueTypeNames.Int).Set(1)
|
| 79 |
+
s.CreateInput('specularColor', self.D.ValueTypeNames.Color3f).Set(self.F.Vec3f(0, 0, 0))
|
| 80 |
+
return self.plane(key, center, width, height, right, up, None, parent, material=mat)
|
| 81 |
+
|
| 82 |
+
def table(self, key, center=(3, 3), size=(1.6, 0.7), height=0.9):
|
| 83 |
+
x, y = center
|
| 84 |
+
w, d = size
|
| 85 |
+
g = self.group(key)
|
| 86 |
+
self.box(key + '_top', [x, y, height], [w, d, 0.08], 'wood', g, bevel=0.015)
|
| 87 |
+
for xx in [-w / 2 + 0.1, w / 2 - 0.1]:
|
| 88 |
+
for yy in [-d / 2 + 0.1, d / 2 - 0.1]:
|
| 89 |
+
self.box(key + '_leg', [x + xx, y + yy, height / 2], [0.075, 0.075, height], 'iron', g)
|
| 90 |
+
self.box(key + '_shelf', [x, y, 0.28], [w - 0.15, d - 0.12, 0.045], 'wood', g)
|
| 91 |
+
self.add_obstacle(x - w / 2, y - d / 2, x + w / 2, y + d / 2)
|
| 92 |
+
return g
|
| 93 |
+
|
| 94 |
+
def ceiling_light(self, key, x, y, z=2.48, intensity=18000, color=(1.0, 0.92, 0.79)):
|
| 95 |
+
from pxr import UsdLux, UsdGeom, Gf
|
| 96 |
+
self.tube(key + '_cord', [x, y, z + 0.28], [x, y, z + 0.09], 0.009, 'iron')
|
| 97 |
+
self.cylinder(key + '_shade', [x, y, z + 0.055], 0.2, 0.09, 'paint')
|
| 98 |
+
self.cylinder(key + '_diffuser', [x, y, z], 0.17, 0.01, 'lamp')
|
| 99 |
+
with self.og.sim.editing_usd():
|
| 100 |
+
l = UsdLux.RectLight.Define(self.stage, '/World/redesign364/lights/' + key)
|
| 101 |
+
UsdGeom.Xformable(l.GetPrim()).AddTranslateOp().Set(Gf.Vec3d(x, y, z - 0.012))
|
| 102 |
+
l.CreateWidthAttr(0.24)
|
| 103 |
+
l.CreateHeightAttr(0.24)
|
| 104 |
+
l.CreateIntensityAttr(float(intensity))
|
| 105 |
+
l.CreateColorAttr(Gf.Vec3f(*color))
|
| 106 |
+
return l
|
| 107 |
+
|
| 108 |
+
def room_shell(self, name, origin=(0, 0), size=(6, 5), openings=None, height=2.8):
|
| 109 |
+
x0, y0 = origin
|
| 110 |
+
w, d = size
|
| 111 |
+
openings = openings or {}
|
| 112 |
+
self.room_rectangles.append((x0, y0, x0 + w, y0 + d))
|
| 113 |
+
count = max(1, int(round(w / 0.25)))
|
| 114 |
+
for i in range(count):
|
| 115 |
+
self.box(name + '_floor', [x0 + (i + 0.5) * w / count, y0 + d / 2, -0.025], [w / count - 0.003, d, 0.05], 'wood', bevel=0.002)
|
| 116 |
+
self.box(name + '_ceiling', [x0 + w / 2, y0 + d / 2, height + 0.035], [w + 0.12, d + 0.12, 0.07], 'plaster')
|
| 117 |
+
for side, length in [('south', w), ('north', w), ('west', d), ('east', d)]:
|
| 118 |
+
holes = sorted(openings.get(side, []))
|
| 119 |
+
segments = []
|
| 120 |
+
last = 0.0
|
| 121 |
+
for a, b in holes:
|
| 122 |
+
assert 0 <= a < b <= length, (side, a, b, length)
|
| 123 |
+
if a > last:
|
| 124 |
+
segments.append((last, a))
|
| 125 |
+
last = b
|
| 126 |
+
c = (a + b) / 2
|
| 127 |
+
if side in ['south', 'north']:
|
| 128 |
+
pos = [x0 + c, y0 if side == 'south' else y0 + d, 2.56]
|
| 129 |
+
sz = [b - a, 0.12, 0.48]
|
| 130 |
+
else:
|
| 131 |
+
pos = [x0 if side == 'west' else x0 + w, y0 + c, 2.56]
|
| 132 |
+
sz = [0.12, b - a, 0.48]
|
| 133 |
+
self.box(name + '_' + side + '_lintel', pos, sz, 'plaster')
|
| 134 |
+
if last < length:
|
| 135 |
+
segments.append((last, length))
|
| 136 |
+
for a, b in segments:
|
| 137 |
+
if side in ['south', 'north']:
|
| 138 |
+
x = x0 + (a + b) / 2
|
| 139 |
+
y = y0 if side == 'south' else y0 + d
|
| 140 |
+
c = [x, y, height / 2]
|
| 141 |
+
sz = [b - a, 0.12, height]
|
| 142 |
+
rect = (x0 + a, y - 0.06, x0 + b, y + 0.06)
|
| 143 |
+
lower = [x, y, 0.51]
|
| 144 |
+
lsz = [b - a, 0.135, 1.02]
|
| 145 |
+
rail = [x, y, 1.04]
|
| 146 |
+
rsz = [b - a, 0.15, 0.045]
|
| 147 |
+
else:
|
| 148 |
+
x = x0 if side == 'west' else x0 + w
|
| 149 |
+
y = y0 + (a + b) / 2
|
| 150 |
+
c = [x, y, height / 2]
|
| 151 |
+
sz = [0.12, b - a, height]
|
| 152 |
+
rect = (x - 0.06, y0 + a, x + 0.06, y0 + b)
|
| 153 |
+
lower = [x, y, 0.51]
|
| 154 |
+
lsz = [0.135, b - a, 1.02]
|
| 155 |
+
rail = [x, y, 1.04]
|
| 156 |
+
rsz = [0.15, b - a, 0.045]
|
| 157 |
+
self.box(name + '_' + side + '_wall', c, sz, 'plaster')
|
| 158 |
+
self.box(name + '_' + side + '_lower', lower, lsz, 'paint')
|
| 159 |
+
self.box(name + '_' + side + '_rail', rail, rsz, 'darkwood')
|
| 160 |
+
self.add_obstacle(*rect)
|
| 161 |
+
for frac in [0.18, 0.82]:
|
| 162 |
+
self.box(name + '_beam', [x0 + w * frac, y0 + d / 2, height - 0.1], [0.15, d, 0.18], 'darkwood')
|
| 163 |
+
self.ceiling_light(name + '_left_lamp', x0 + w * 0.3, y0 + d * 0.5, height - 0.34)
|
| 164 |
+
self.ceiling_light(name + '_right_lamp', x0 + w * 0.75, y0 + d * 0.72, height - 0.34)
|
| 165 |
+
|
| 166 |
+
def door(self, key, hinge=(2.45, 0.1, 0), width=1.1):
|
| 167 |
+
g = self.group(key, hinge)
|
| 168 |
+
self.box(key + '_leaf', [width / 2, 0, 1.12], [width, 0.09, 2.24], 'wood', g, bevel=0.025)
|
| 169 |
+
for z in [0.25, 1.98]:
|
| 170 |
+
self.box(key + '_band', [width / 2, 0.06, z], [width - 0.08, 0.03, 0.08], 'iron', g)
|
| 171 |
+
self.box(key + '_plate', [width - 0.13, 0.075, 1.05], [0.13, 0.03, 0.24], 'brass', g)
|
| 172 |
+
self.cylinder(key + '_knob', [width - 0.13, 0.11, 1.12], 0.037, 0.07, 'steel', 'y', g)
|
| 173 |
+
self.cylinder(key + '_keyhole', [width - 0.13, 0.095, 0.99], 0.018, 0.01, 'iron', 'y', g)
|
| 174 |
+
return g
|
runtime/h2_runtime/room_decor_quality.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
THEMES = {'R23': (('offcuts', 'cloth'), ('lined', 'conduit')), 'R24': (('lined', 'sleeves'), ('belts', 'spools')), 'R25': (('sacks', 'ceramics'), ('ceramics', 'cloth')), 'R26': (('rolls', 'folios'), ('folios', 'rolls')), 'R27': (('lined', 'cloth'), ('plates', 'cloth')), 'R28': (('paper', 'folios'), ('rolls', 'plates')), 'R29': (('lined', 'sleeves'), ('lined', 'hose')), 'R30': (('folios', 'rolls'), ('crate', 'folios')), 'R31': (('paper', 'rolls'), ('rolls', 'sleeves')), 'R32': (('folios', 'bags'), ('crate', 'rolls')), 'R33': (('ceramics', 'rolls'), ('lined', 'ceramics')), 'R34': (('plates', 'cloth'), ('belts', 'conduit')), 'R35': (('screens', 'rolls'), ('lined', 'screens')), 'R36': (('folios', 'bags'), ('lined', 'folios')), 'R37': (('rolls', 'plates'), ('ceramics', 'cloth')), 'R38': (('offcuts', 'cloth'), ('crate', 'rolls')), 'R39': (('paper', 'rolls'), ('rolls', 'plates')), 'R40': (('offcuts', 'cloth'), ('crate', 'rolls')), 'R41': (('ceramics', 'sleeves'), ('ceramics', 'cloth')), 'R42': (('folios', 'bags'), ('rolls', 'rolls')), 'R43': (('rolls', 'plates'), ('crate', 'cloth')), 'R44': (('lined', 'sleeves'), ('ceramics', 'rolls'))}
|
| 3 |
+
|
| 4 |
+
class _Fixture:
|
| 5 |
+
|
| 6 |
+
def __init__(self, scene, key, pos, angle=0):
|
| 7 |
+
self.s = scene
|
| 8 |
+
self.root = scene.group(key, pos)
|
| 9 |
+
if angle:
|
| 10 |
+
scene.transform(self.root, rpy=[0, 0, angle])
|
| 11 |
+
self.key = key
|
| 12 |
+
self.i = 0
|
| 13 |
+
|
| 14 |
+
def key_for(self, name):
|
| 15 |
+
self.i += 1
|
| 16 |
+
return self.key + '_' + str(self.i) + '_' + name
|
| 17 |
+
|
| 18 |
+
def box(self, name, pos, size, material='wood'):
|
| 19 |
+
return self.s.box(self.key_for(name), pos, size, material, self.root)
|
| 20 |
+
|
| 21 |
+
def cylinder(self, name, pos, radius, length, material='ivory', axis='z'):
|
| 22 |
+
return self.s.cylinder(self.key_for(name), pos, radius, length, material, axis, self.root, n=20)
|
| 23 |
+
|
| 24 |
+
def tube(self, name, a, b, radius=0.012, material='iron'):
|
| 25 |
+
return self.s.tube(self.key_for(name), a, b, radius, material, self.root)
|
| 26 |
+
|
| 27 |
+
def shelf(self, wall=False):
|
| 28 |
+
if wall:
|
| 29 |
+
self.box('wall_back', [0, 0.012, 1.38], [0.82, 0.045, 0.3], 'darkwood')
|
| 30 |
+
self.box('shelf', [0, -0.1, 1.36], [0.86, 0.22, 0.035])
|
| 31 |
+
for x in [-0.31, 0.31]:
|
| 32 |
+
self.box('bracket_upright', [x, -0.015, 1.285], [0.026, 0.05, 0.15], 'iron')
|
| 33 |
+
self.tube('bracket_diagonal', [x, -0.015, 1.22], [x, -0.135, 1.3425])
|
| 34 |
+
else:
|
| 35 |
+
self.box('base_shelf', [0, 0, 0.16], [0.82, 0.3, 0.035])
|
| 36 |
+
for x in [-0.37, 0.37]:
|
| 37 |
+
for y in [-0.115, 0.115]:
|
| 38 |
+
self.box('leg', [x, y, 0.35], [0.05, 0.05, 0.7], 'darkwood')
|
| 39 |
+
self.box('top_shelf', [0, 0, 0.7], [0.84, 0.31, 0.035])
|
| 40 |
+
self.box('rear_rail', [0, 0.1325, 0.47], [0.8, 0.025, 0.43], 'darkwood')
|
| 41 |
+
|
| 42 |
+
def folios(self, z, y=0):
|
| 43 |
+
for j in range(3):
|
| 44 |
+
x = -0.25 + j * 0.25
|
| 45 |
+
self.box('closed_folio_pages', [x, y, z + 0.095], [0.19, 0.19, 0.19], 'ivory')
|
| 46 |
+
for side in [-1, 1]:
|
| 47 |
+
self.box('cloth_binding', [x + side * 0.101, y, z + 0.095], [0.012, 0.215, 0.205], 'paint' if j % 2 else 'sample_blue')
|
| 48 |
+
self.box('plain_spine', [x, y - 0.103, z + 0.095], [0.21, 0.014, 0.205], 'paint')
|
| 49 |
+
|
| 50 |
+
def rolls(self, z, y=0, cloth=False, length=0.23):
|
| 51 |
+
for j in range(3):
|
| 52 |
+
self.cylinder('stored_roll', [-0.25 + j * 0.25, y, z + 0.065], 0.065, length, 'cloth' if cloth else 'ivory', 'y')
|
| 53 |
+
self.cylinder('roll_core', [-0.25 + j * 0.25, y - length / 2 - 0.006, z + 0.065], 0.018, 0.012, 'darkwood', 'y')
|
| 54 |
+
|
| 55 |
+
def ceramics(self, z, y=0):
|
| 56 |
+
for j, (height, radius) in enumerate([(0.17, 0.075), (0.115, 0.092), (0.22, 0.064)]):
|
| 57 |
+
x = -0.25 + j * 0.25
|
| 58 |
+
mat = ['paint', 'ivory', 'sample_blue'][j]
|
| 59 |
+
self.cylinder('pot_foot', [x, y, z + 0.012], radius * 0.7, 0.024, mat)
|
| 60 |
+
self.cylinder('pot_body', [x, y, z + height * 0.43], radius, height * 0.7, mat)
|
| 61 |
+
self.cylinder('pot_neck', [x, y, z + height * 0.83], radius * 0.65, height * 0.22, mat)
|
| 62 |
+
self.cylinder('dark_open_mouth', [x, y, z + height * 0.945], radius * 0.46, 0.003, 'darkwood')
|
| 63 |
+
|
| 64 |
+
def cloth(self, z, y=0):
|
| 65 |
+
for j in range(3):
|
| 66 |
+
self.box('folded_cloth', [-0.25 + j * 0.25, y, z + 0.025 + j * 0.003], [0.205, 0.15, 0.05 + j * 0.006], 'cloth' if j % 2 else 'ivory')
|
| 67 |
+
|
| 68 |
+
def plates(self, z, y=0, screen=False, depth=0.25):
|
| 69 |
+
self.box('sheet_rack_floor', [0, y, z + 0.0125], [0.77, depth, 0.025], 'darkwood')
|
| 70 |
+
for j in range(3):
|
| 71 |
+
x = -0.25 + j * 0.25
|
| 72 |
+
self.box('stock_sheet', [x, y, z + 0.15], [0.17, 0.028, 0.275], 'steel' if screen else 'wood')
|
| 73 |
+
self.box('front_slot', [x, y - 0.036, z + 0.035], [0.19, 0.025, 0.045], 'darkwood')
|
| 74 |
+
self.box('rear_slot', [x, y + 0.036, z + 0.035], [0.19, 0.025, 0.045], 'darkwood')
|
| 75 |
+
|
| 76 |
+
def coils(self, z, y=0, material='rubber'):
|
| 77 |
+
for j in range(2):
|
| 78 |
+
x = -0.21 + j * 0.42
|
| 79 |
+
for k in range(24):
|
| 80 |
+
a = 2 * np.pi * k / 24
|
| 81 |
+
b = 2 * np.pi * (k + 1) / 24
|
| 82 |
+
self.tube('bound_coil', [x + 0.11 * np.cos(a), y + 0.075 * np.sin(a), z + 0.016], [x + 0.11 * np.cos(b), y + 0.075 * np.sin(b), z + 0.016], 0.016, material)
|
| 83 |
+
for dx in [-0.12, 0.12]:
|
| 84 |
+
self.box('coil_stop', [x + dx, y, z + 0.027], [0.018, 0.12, 0.055], 'darkwood')
|
| 85 |
+
|
| 86 |
+
def low(self, kind):
|
| 87 |
+
if kind in ('crate', 'offcuts', 'lined', 'screens', 'plates', 'sacks'):
|
| 88 |
+
self.box('tray_floor', [0, 0, 0.14], [0.84, 0.3, 0.04])
|
| 89 |
+
for x in [-0.37, 0.37]:
|
| 90 |
+
for y in [-0.115, 0.115]:
|
| 91 |
+
self.box('foot', [x, y, 0.06], [0.065, 0.065, 0.12], 'darkwood')
|
| 92 |
+
for y in [-0.147, 0.147]:
|
| 93 |
+
for z in [0.205, 0.29]:
|
| 94 |
+
self.box('side_slat', [0, y, z], [0.84, 0.025, 0.055])
|
| 95 |
+
for x in [-0.41, 0.41]:
|
| 96 |
+
self.box('end', [x, 0, 0.25], [0.035, 0.3, 0.24])
|
| 97 |
+
if kind == 'lined':
|
| 98 |
+
self.box('padded_base', [0, 0, 0.185], [0.75, 0.24, 0.05], 'cloth')
|
| 99 |
+
for x in [-0.31, 0.31]:
|
| 100 |
+
self.box('padding_bolster', [x, 0, 0.235], [0.1, 0.23, 0.07], 'cloth')
|
| 101 |
+
elif kind in ('plates', 'screens'):
|
| 102 |
+
self.plates(0.16, screen=kind == 'screens')
|
| 103 |
+
elif kind == 'sacks':
|
| 104 |
+
for x in [-0.23, 0.23]:
|
| 105 |
+
self.cylinder('bulk_cloth_sack', [x, 0, 0.315], 0.105, 0.31, 'cloth')
|
| 106 |
+
self.cylinder('tied_neck', [x, 0, 0.4775], 0.035, 0.035, 'darkwood')
|
| 107 |
+
elif kind == 'offcuts':
|
| 108 |
+
for j in range(3):
|
| 109 |
+
self.box('timber_offcut', [-0.25 + j * 0.25, 0, 0.16 + (0.24 + j * 0.05) / 2], [0.15, 0.19, 0.24 + j * 0.05])
|
| 110 |
+
else:
|
| 111 |
+
for j in range(2):
|
| 112 |
+
self.box('packing_pad', [-0.2 + j * 0.4, 0, 0.1875], [0.32, 0.23, 0.055], 'cloth')
|
| 113 |
+
else:
|
| 114 |
+
self.shelf()
|
| 115 |
+
z = 0.7175
|
| 116 |
+
if kind == 'folios':
|
| 117 |
+
self.folios(z)
|
| 118 |
+
elif kind == 'ceramics':
|
| 119 |
+
self.ceramics(z)
|
| 120 |
+
elif kind == 'paper':
|
| 121 |
+
for j in range(3):
|
| 122 |
+
self.box('plain_paper_stack', [-0.26 + j * 0.26, 0, z + 0.045], [0.235, 0.23, 0.09], 'ivory')
|
| 123 |
+
elif kind == 'belts':
|
| 124 |
+
self.coils(z)
|
| 125 |
+
elif kind == 'rolls':
|
| 126 |
+
self.rolls(z, cloth=True)
|
| 127 |
+
self.box('spare_packing_cloth', [0.1, 0, 0.21], [0.45, 0.23, 0.065], 'cloth')
|
| 128 |
+
|
| 129 |
+
def wall(self, kind):
|
| 130 |
+
self.shelf(wall=True)
|
| 131 |
+
z = 1.3775
|
| 132 |
+
y = -0.1
|
| 133 |
+
if kind == 'ceramics':
|
| 134 |
+
self.ceramics(z, y)
|
| 135 |
+
elif kind == 'folios':
|
| 136 |
+
self.folios(z, y - 0.015)
|
| 137 |
+
elif kind in ('plates', 'screens'):
|
| 138 |
+
self.plates(z, y, screen=kind == 'screens', depth=0.18)
|
| 139 |
+
elif kind == 'rolls':
|
| 140 |
+
self.rolls(z, y, length=0.18)
|
| 141 |
+
elif kind == 'spools':
|
| 142 |
+
self.rolls(z, y, cloth=True, length=0.18)
|
| 143 |
+
elif kind in ('conduit', 'hose'):
|
| 144 |
+
self.coils(z, y, material='iron' if kind == 'conduit' else 'rubber')
|
| 145 |
+
elif kind in ('bags', 'sleeves'):
|
| 146 |
+
for j in range(3):
|
| 147 |
+
x = -0.25 + j * 0.25
|
| 148 |
+
self.box('cloth_storage_pouch', [x, y, z + 0.095], [0.19, 0.115, 0.19], 'cloth')
|
| 149 |
+
self.box('folded_pouch_top', [x, y - 0.01, z + 0.193], [0.19, 0.1, 0.016], 'ivory')
|
| 150 |
+
else:
|
| 151 |
+
self.cloth(z, y)
|
| 152 |
+
|
| 153 |
+
def populate_room_decor(scene, spec):
|
| 154 |
+
if getattr(scene, 'room_decor_receipt', None) is not None:
|
| 155 |
+
return scene.room_decor_receipt
|
| 156 |
+
rid = spec['id']
|
| 157 |
+
if rid not in THEMES:
|
| 158 |
+
return []
|
| 159 |
+
result = []
|
| 160 |
+
slots = {'A': (([3.35, 0.32, 0], 0), ([3.45, 4.94, 0], 0)), 'B': (([7.55, 0.32, 0], 0), ([4.865, 3.75, 0], 90))}
|
| 161 |
+
for room, kinds in zip(('A', 'B'), THEMES[rid]):
|
| 162 |
+
for index, ((pos, angle), kind) in enumerate(zip(slots[room], kinds)):
|
| 163 |
+
key = 'v5_decor_' + room + ('_low' if index == 0 else '_wall')
|
| 164 |
+
f = _Fixture(scene, key, pos, angle)
|
| 165 |
+
if index == 0:
|
| 166 |
+
f.low(kind)
|
| 167 |
+
else:
|
| 168 |
+
f.wall(kind)
|
| 169 |
+
points = scene.triangles(f.root).reshape(-1, 3)
|
| 170 |
+
lo = points.min(0)
|
| 171 |
+
hi = points.max(0)
|
| 172 |
+
scene.add_obstacle(float(lo[0]), float(lo[1]), float(hi[0]), float(hi[1]))
|
| 173 |
+
result.append({'room': room, 'theme': kind, 'group': key, 'root': f.root, 'aabb_min': lo.tolist(), 'aabb_max': hi.tolist(), 'fixed': True, 'interactive': False})
|
| 174 |
+
scene.room_decor_receipt = result
|
| 175 |
+
return result
|
runtime/h2_runtime/text_layout_quality.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import hashlib, math
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
from font_utils import load_font
|
| 5 |
+
|
| 6 |
+
def render_text_panel(text, w, h, pixel_width=1600, background=(220, 214, 192), ink=(28, 39, 40), align='left', return_layout=False):
|
| 7 |
+
if not math.isfinite(float(w)) or not math.isfinite(float(h)) or w <= 0 or (h <= 0):
|
| 8 |
+
raise ValueError('Positive finite text panel dimensions required')
|
| 9 |
+
source_lines = str(text).split('\n') if isinstance(text, str) else [str(v) for v in text]
|
| 10 |
+
width = max(16, int(round(pixel_width)))
|
| 11 |
+
height = max(1, int(round(width * float(h) / float(w))))
|
| 12 |
+
margin_x = max(2, min(int(width * 0.035), int(height * 0.12)))
|
| 13 |
+
margin_y = max(2, int(height * 0.075))
|
| 14 |
+
available_w = max(1, width - 2 * margin_x)
|
| 15 |
+
available_h = max(1, height - 2 * margin_y)
|
| 16 |
+
image = Image.new('RGB', (width, height), background)
|
| 17 |
+
draw = ImageDraw.Draw(image)
|
| 18 |
+
|
| 19 |
+
def bounds(value, font):
|
| 20 |
+
return draw.textbbox((0, 0), value, font=font)
|
| 21 |
+
|
| 22 |
+
def wrap(line, font):
|
| 23 |
+
if not line:
|
| 24 |
+
return ['']
|
| 25 |
+
result = []
|
| 26 |
+
remaining = line
|
| 27 |
+
while remaining:
|
| 28 |
+
if bounds(remaining, font)[2] - bounds(remaining, font)[0] <= available_w:
|
| 29 |
+
result.append(remaining)
|
| 30 |
+
break
|
| 31 |
+
n = 0
|
| 32 |
+
for j in range(1, len(remaining) + 1):
|
| 33 |
+
box = bounds(remaining[:j], font)
|
| 34 |
+
if box[2] - box[0] > available_w:
|
| 35 |
+
break
|
| 36 |
+
n = j
|
| 37 |
+
if n == 0:
|
| 38 |
+
return None
|
| 39 |
+
split = remaining.rfind(' ', 0, n + 1)
|
| 40 |
+
if split >= 0:
|
| 41 |
+
n = split + 1
|
| 42 |
+
result.append(remaining[:n])
|
| 43 |
+
remaining = remaining[n:]
|
| 44 |
+
return result
|
| 45 |
+
|
| 46 |
+
def layout(size):
|
| 47 |
+
font = load_font(size)
|
| 48 |
+
groups = []
|
| 49 |
+
for line in source_lines:
|
| 50 |
+
group = wrap(line, font)
|
| 51 |
+
if group is None:
|
| 52 |
+
return None
|
| 53 |
+
groups.append(group)
|
| 54 |
+
lines = [line for group in groups for line in group]
|
| 55 |
+
boxes = [bounds(line, font) for line in lines]
|
| 56 |
+
glyph_h = max([box[3] - box[1] for box in boxes] + [1])
|
| 57 |
+
gap = max(2, int(size * 0.17))
|
| 58 |
+
total = glyph_h * len(lines) + gap * max(0, len(lines) - 1)
|
| 59 |
+
return (font, groups, lines, boxes, glyph_h, gap, total)
|
| 60 |
+
low, high, best = (9, max(9, int(height * 1.5)), None)
|
| 61 |
+
while low <= high:
|
| 62 |
+
size = (low + high) // 2
|
| 63 |
+
value = layout(size)
|
| 64 |
+
if value is not None and value[-1] <= available_h:
|
| 65 |
+
best = (size, value)
|
| 66 |
+
low = size + 1
|
| 67 |
+
else:
|
| 68 |
+
high = size - 1
|
| 69 |
+
if best is None:
|
| 70 |
+
raise ValueError('Text cannot fit panel at the bundled font minimum; increase isotropic texture resolution')
|
| 71 |
+
size, (font, groups, lines, boxes, glyph_h, gap, total) = best
|
| 72 |
+
y = (height - total) / 2
|
| 73 |
+
placements = []
|
| 74 |
+
for line, box in zip(lines, boxes):
|
| 75 |
+
actual_w = box[2] - box[0]
|
| 76 |
+
x = (width - actual_w) / 2 if align == 'center' else margin_x
|
| 77 |
+
position = (x - box[0], y - box[1])
|
| 78 |
+
draw.text(position, line, font=font, fill=ink)
|
| 79 |
+
placements.append({'text': line, 'ink_bbox': [x, y, x + actual_w, y + box[3] - box[1]], 'draw_xy': list(position)})
|
| 80 |
+
y += glyph_h + gap
|
| 81 |
+
assert all((''.join(group) == source for group, source in zip(groups, source_lines)))
|
| 82 |
+
metadata = {'source_lines': source_lines, 'source_text': '\n'.join(source_lines), 'wrapped_groups': groups, 'canvas': [width, height], 'world': [float(w), float(h)], 'font_size': size, 'font': 'bundled DejaVuSansMono', 'placements': placements, 'glyph_resize_applied': False, 'pixel_to_world_anisotropy': float(w) / width / (float(h) / height), 'background': list(background), 'ink': list(ink), 'align': align}
|
| 83 |
+
image.info['text_layout_quality'] = metadata
|
| 84 |
+
return (image, metadata) if return_layout else image
|
| 85 |
+
|
| 86 |
+
def save_text_image(directory, image):
|
| 87 |
+
digest = hashlib.sha256(repr((image.mode, image.size)).encode() + b'\x00' + image.tobytes()).hexdigest()
|
| 88 |
+
path = Path(directory) / ('t_' + digest[:32] + '.png')
|
| 89 |
+
if not path.exists():
|
| 90 |
+
image.save(path)
|
| 91 |
+
return path
|
| 92 |
+
|
| 93 |
+
def reflow_text_image(image, w, h):
|
| 94 |
+
meta = image.info.get('text_layout_quality')
|
| 95 |
+
if meta is None:
|
| 96 |
+
return image
|
| 97 |
+
return render_text_panel(meta['source_lines'], w, h, background=tuple(meta['background']), ink=tuple(meta['ink']), align=meta['align'])
|
runtime/legacy_entry.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import argparse, importlib.util, importlib.abc, json, os, sys, runpy, hashlib
|
| 3 |
+
from read_content_policy import install_image_tracking as _install_read_metadata
|
| 4 |
+
_install_read_metadata()
|
| 5 |
+
ROOT = Path(__file__).resolve().parent
|
| 6 |
+
SUPPORT = ROOT / 'legacy_source/formal_render283/support'
|
| 7 |
+
PATCH = ROOT / 'legacy_source/cabinet_joint345'
|
| 8 |
+
|
| 9 |
+
def load(name, path):
|
| 10 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 11 |
+
m = importlib.util.module_from_spec(spec)
|
| 12 |
+
sys.modules[name] = m
|
| 13 |
+
spec.loader.exec_module(m)
|
| 14 |
+
return m
|
| 15 |
+
|
| 16 |
+
def install_stack():
|
| 17 |
+
from read_content_policy import install_image_tracking
|
| 18 |
+
install_image_tracking()
|
| 19 |
+
os.environ['ESI_ESCAPE_REFS'] = 'claw'
|
| 20 |
+
import unified_protocol as P
|
| 21 |
+
sys.path.insert(0, str(SUPPORT))
|
| 22 |
+
S = load('_escape_stagnation', SUPPORT / '_escape_stagnation.py')
|
| 23 |
+
E = load('_escape', SUPPORT / '_escape_bind_ownedvisual1010.py')
|
| 24 |
+
C = load('_escape_claw', SUPPORT / '_escape_claw_nativefresh1009.py')
|
| 25 |
+
for alias, file in [('_escape_keypad_visual', '_escape_keypad_visual_devices1008.py'), ('_escape_use_visual', '_escape_use_assetkey1010.py'), ('_native_scene77', 'native_scene77.py'), ('_escape_devices_visual', '_escape_devices_legacykeys1010.py')]:
|
| 26 |
+
load(alias, SUPPORT / file)
|
| 27 |
+
load('_revision17_native', SUPPORT / 'revision17_native1010.py').install(E, C)
|
| 28 |
+
load('_escape_video163', SUPPORT / 'escape_video163.py').install(E, C)
|
| 29 |
+
load('_unified_camera332', PATCH / 'camera_follow332.py').install(sys.modules['_escape_video163'])
|
| 30 |
+
load('_unified_key328', PATCH / 'key_sync328.py').install(E)
|
| 31 |
+
load('_unified_door337', PATCH / 'door_joint337.py').install(E)
|
| 32 |
+
load('_unified_cab345', PATCH / 'cabinet_joint345.py').install(E)
|
| 33 |
+
stage = load('_unified_stage159', SUPPORT / '_escape_stage_hints159.py')
|
| 34 |
+
S._stage_module159 = lambda: stage
|
| 35 |
+
P.install(E, C, S, stage)
|
| 36 |
+
sys.path.insert(0, str(ROOT / 'native_runtime'))
|
| 37 |
+
from legacy_rooms_bridge import install_mechanism_hooks
|
| 38 |
+
install_mechanism_hooks(E)
|
| 39 |
+
from read_content_policy import install_executor
|
| 40 |
+
install_executor(E)
|
| 41 |
+
return (E, C, S)
|
| 42 |
+
|
| 43 |
+
class ToolsLoader(importlib.abc.Loader):
|
| 44 |
+
|
| 45 |
+
def create_module(self, spec):
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
def exec_module(self, module):
|
| 49 |
+
source = (PATCH / 'thin_tools333.py').read_text(encoding='utf-8')
|
| 50 |
+
module.__file__ = str(Path(os.environ['ESI_UNIFIED_REPO']) / 'run/_tools.py')
|
| 51 |
+
exec(compile(source, module.__file__, 'exec'), module.__dict__)
|
| 52 |
+
|
| 53 |
+
class ToolsFinder(importlib.abc.MetaPathFinder):
|
| 54 |
+
|
| 55 |
+
def find_spec(self, fullname, path=None, target=None):
|
| 56 |
+
if fullname == '_tools':
|
| 57 |
+
return importlib.util.spec_from_loader(fullname, ToolsLoader())
|
| 58 |
+
|
runtime/legacy_metrics/checkpoint_bank268_v2.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
runtime/legacy_metrics/frozen_default.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"host_settings": {
|
| 3 |
+
"local": {
|
| 4 |
+
"ESI_BUDGET_SUPPORT": "support"
|
| 5 |
+
}
|
| 6 |
+
}
|
| 7 |
+
}
|
runtime/legacy_metrics/milestone_checkpoints268.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import hashlib, json, re
|
| 4 |
+
from milestone_filter268 import config_for, normalized
|
| 5 |
+
POLICY = 'per_level_fixed_evidence_checkpoints268_v2'
|
| 6 |
+
ROOT = Path(__file__).resolve().parent
|
| 7 |
+
BANK_FILE = 'checkpoint_bank268_v2.json'
|
| 8 |
+
METRIC_KEYS = {'milestones', 'milestone_total', 'milestone_completed', 'milestone_completion_rate', 'first_milestone_step', 'last_milestone_step', 'next_progress_after_tip_step', 'actions_until_progress_after_tip', 'milestone_policy', 'milestone_exclusions', 'milestone_evidence', 'milestone_labels', 'milestone_definition_sha256', 'milestone_definition_count', 'milestone_unverifiable', 'milestone_basis'}
|
| 9 |
+
|
| 10 |
+
def read(path):
|
| 11 |
+
return json.loads(Path(path).read_text('utf8'))
|
| 12 |
+
|
| 13 |
+
def step(value):
|
| 14 |
+
if value is None or isinstance(value, bool):
|
| 15 |
+
return None
|
| 16 |
+
m = re.match('^(\\d+)', str(value))
|
| 17 |
+
return int(m[1]) if m else None
|
| 18 |
+
|
| 19 |
+
def photo(value):
|
| 20 |
+
name = str(value).replace('\\', '/').rsplit('/', 1)[-1]
|
| 21 |
+
return name.replace('_small.png', '.png').replace('_clean.png', '.png')
|
| 22 |
+
|
| 23 |
+
@lru_cache(maxsize=1)
|
| 24 |
+
def bank():
|
| 25 |
+
raw = (ROOT / BANK_FILE).read_bytes()
|
| 26 |
+
data = json.loads(raw)
|
| 27 |
+
assert data['policy'] == POLICY and len(data['levels']) == 50
|
| 28 |
+
return (data, hashlib.sha256(raw).hexdigest())
|
| 29 |
+
|
| 30 |
+
def definition(cfg):
|
| 31 |
+
data, digest = bank()
|
| 32 |
+
name = cfg['name']
|
| 33 |
+
row = data['levels'][name]
|
| 34 |
+
assert row['config_file'] == name + '.json'
|
| 35 |
+
original = config_for({'name': name, 'config_sha256': row['config_sha256']})
|
| 36 |
+
assert original['name'] == cfg['name']
|
| 37 |
+
return (row, digest)
|
| 38 |
+
|
| 39 |
+
class Evidence:
|
| 40 |
+
|
| 41 |
+
def __init__(self, summary, cfg, turns, objects):
|
| 42 |
+
self.summary = summary
|
| 43 |
+
self.cfg = cfg
|
| 44 |
+
self.turns = list(turns or [])
|
| 45 |
+
self.objects = objects or {}
|
| 46 |
+
self.items = {x['id']: x for x in cfg.get('items', [])}
|
| 47 |
+
self.byname = {x['name']: x['id'] for x in cfg.get('items', [])}
|
| 48 |
+
self.marks = summary.get('milestones') or {}
|
| 49 |
+
self.deliveries = {}
|
| 50 |
+
self.boxes = {}
|
| 51 |
+
self._groups = {}
|
| 52 |
+
for index, r in enumerate(self.turns):
|
| 53 |
+
for image in r.get('model_input_contents', []):
|
| 54 |
+
if image.get('type') == 'image':
|
| 55 |
+
p = photo(image.get('path', image.get('name', '')))
|
| 56 |
+
self.deliveries.setdefault(p, dict(record=index, turn=r.get('turn')))
|
| 57 |
+
for path, rows in (r.get('photo_boxes') or {}).items():
|
| 58 |
+
ids = set()
|
| 59 |
+
for x in rows:
|
| 60 |
+
if isinstance(x, (list, tuple)) and x:
|
| 61 |
+
ids.add(str(x[0]))
|
| 62 |
+
self.boxes[photo(path)] = ids
|
| 63 |
+
|
| 64 |
+
def sim(self, value):
|
| 65 |
+
if value is None:
|
| 66 |
+
return None
|
| 67 |
+
obj = self.objects.get(str(value), self.objects.get(value, {}))
|
| 68 |
+
if isinstance(obj, dict) and obj.get('sim'):
|
| 69 |
+
return obj['sim']
|
| 70 |
+
if str(value) in self.byname:
|
| 71 |
+
return str(value)
|
| 72 |
+
if str(value) in self.items:
|
| 73 |
+
return self.items[str(value)]['name']
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
def target(self, r, key='target'):
|
| 77 |
+
ids = r.get('action_ids') or (r.get('result') or {}).get('action_ids') or {}
|
| 78 |
+
value = ids.get(key, ids.get('object') if key == 'target' else None)
|
| 79 |
+
return self.sim(value)
|
| 80 |
+
|
| 81 |
+
def delivered(self, r, index):
|
| 82 |
+
result = r.get('result') or {}
|
| 83 |
+
for value in list(result.get('images') or []) + list(result.get('images_boxed') or []):
|
| 84 |
+
key = photo(value)
|
| 85 |
+
receipt = self.deliveries.get(key)
|
| 86 |
+
if receipt and receipt['record'] > index:
|
| 87 |
+
return (key, receipt)
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
def visible(self, r, index, names):
|
| 91 |
+
names = set(names)
|
| 92 |
+
ids = {str(k) for k, v in self.objects.items() if isinstance(v, dict) and v.get('sim') in names}
|
| 93 |
+
result = r.get('result') or {}
|
| 94 |
+
for value in list(result.get('images') or []) + list(result.get('images_boxed') or []):
|
| 95 |
+
key = photo(value)
|
| 96 |
+
receipt = self.deliveries.get(key)
|
| 97 |
+
if receipt and receipt['record'] > index and ids.intersection(self.boxes.get(key, set())):
|
| 98 |
+
return (key, receipt)
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def raw(self, aliases):
|
| 102 |
+
values = [(step(self.marks.get(k)), k) for k in aliases if step(self.marks.get(k)) is not None]
|
| 103 |
+
if not values:
|
| 104 |
+
return None
|
| 105 |
+
n, k = min(values)
|
| 106 |
+
return dict(step=n, source='native_mark', mark=k)
|
| 107 |
+
|
| 108 |
+
def event(self, node):
|
| 109 |
+
kind = node['kind']
|
| 110 |
+
item = node.get('item')
|
| 111 |
+
name = self.items.get(item, {}).get('name')
|
| 112 |
+
raw = self.raw(node.get('aliases', []))
|
| 113 |
+
if node['key'] == 'exited':
|
| 114 |
+
if not raw or self.summary.get('success') is not True:
|
| 115 |
+
return None
|
| 116 |
+
terminal = [r for r in self.turns if r.get('counted') is True]
|
| 117 |
+
if not terminal:
|
| 118 |
+
return None
|
| 119 |
+
last = terminal[-1]
|
| 120 |
+
exits = {d['name'] for d in self.cfg.get('doors', []) if d.get('exit')}
|
| 121 |
+
if (last.get('action') or {}).get('action') != 'open' or not (last.get('result') or {}).get('ok') or self.target(last) not in exits:
|
| 122 |
+
return None
|
| 123 |
+
return dict(raw, source='native_terminal_mark_and_actual_exit_open')
|
| 124 |
+
if raw:
|
| 125 |
+
return raw
|
| 126 |
+
for index, r in enumerate(self.turns):
|
| 127 |
+
result = r.get('result') or {}
|
| 128 |
+
action = r.get('action') or {}
|
| 129 |
+
n = step(r.get('turn'))
|
| 130 |
+
if n is None or not result.get('ok'):
|
| 131 |
+
continue
|
| 132 |
+
pe = r.get('_progress_evidence150') or {}
|
| 133 |
+
before = pe.get('before') or {}
|
| 134 |
+
after = pe.get('after') or {}
|
| 135 |
+
image = self.delivered(r, index)
|
| 136 |
+
proof = dict(step=n, source='logged_state_or_action', record=index)
|
| 137 |
+
if kind == 'take':
|
| 138 |
+
state = (after.get('items') or {}).get(name, {})
|
| 139 |
+
if state.get('taken') is True and name in (after.get('holding') or []) and (not ((before.get('items') or {}).get(name, {}) or {}).get('taken')):
|
| 140 |
+
return dict(proof, item=item, field='items.taken + holding')
|
| 141 |
+
elif kind == 'exposed':
|
| 142 |
+
state = (after.get('items') or {}).get(name, {})
|
| 143 |
+
if state.get('exposed') is True or state.get('revealed') is True:
|
| 144 |
+
return dict(proof, item=item, field='items.exposed/revealed')
|
| 145 |
+
elif kind == 'measure':
|
| 146 |
+
if action.get('action') == 'use' and self.target(r, 'item') == name and (node['target'] in (result.get('measured') or {})) and image:
|
| 147 |
+
return dict(proof, target=node['target'], measurement=result['measured'][node['target']], image=image[0], delivered_at=image[1]['turn'])
|
| 148 |
+
elif kind == 'uv':
|
| 149 |
+
uv = result.get('uv') or {}
|
| 150 |
+
if action.get('action') == 'use' and self.target(r, 'item') == name and (uv.get('lit') is True) and (uv.get('blocked') is False) and image:
|
| 151 |
+
return dict(proof, item=item, field='uv.lit=true, blocked=false', image=image[0], delivered_at=image[1]['turn'])
|
| 152 |
+
elif kind == 'zoom':
|
| 153 |
+
zoom = result.get('zoom') or {}
|
| 154 |
+
view = self.visible(r, index, node['targets'])
|
| 155 |
+
if action.get('action') == 'use' and self.target(r, 'item') == name and (float(zoom.get('times', 0)) > 1) and view:
|
| 156 |
+
return dict(proof, item=item, field='zoom + target present in delivered photo', image=view[0], delivered_at=view[1]['turn'])
|
| 157 |
+
elif kind == 'stool':
|
| 158 |
+
st = after.get('stool') or {}
|
| 159 |
+
if st.get('on') is True and st.get('name') == name and (st.get('furn') in node['targets']):
|
| 160 |
+
return dict(proof, item=item, field='stool.on and configured furniture')
|
| 161 |
+
elif kind == 'printed':
|
| 162 |
+
paper = str((result.get('keypad') or {}).get('paper') or '')
|
| 163 |
+
if action.get('action') == 'press' and image and (len(paper) >= int(node['length'])):
|
| 164 |
+
ids = r.get('action_ids') or {}
|
| 165 |
+
if node['target'] == self.target(r) or ids.get('keypad_key') or (result.get('keypad') or {}).get('typed'):
|
| 166 |
+
if any((paper.endswith(text) for text in node['accepted_outputs'])):
|
| 167 |
+
return dict(proof, target=node['target'], field='complete accepted printed source group', image=image[0], delivered_at=image[1]['turn'])
|
| 168 |
+
elif kind == 'water_ready':
|
| 169 |
+
amounts = []
|
| 170 |
+
for state in (before, after):
|
| 171 |
+
amounts.append(state.get('jugs') or {})
|
| 172 |
+
amounts.append(result.get('jug') or {})
|
| 173 |
+
if any((any((v == node['amount'] for k, v in a.items() if k in node['items'])) for a in amounts)):
|
| 174 |
+
return dict(proof, field='actual jug amount', amount=node['amount'])
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
def group_progress(self, group):
|
| 178 |
+
if group in self._groups:
|
| 179 |
+
return self._groups[group]
|
| 180 |
+
spec = self.cfg['slot_groups'][group]
|
| 181 |
+
kind = spec['kind']
|
| 182 |
+
gadgets = {g['name']: g for g in self.cfg.get('gadgets', []) if g.get('group') == group}
|
| 183 |
+
allitems = list(spec.get('items') or [])
|
| 184 |
+
events = []
|
| 185 |
+
for index, r in enumerate(self.turns):
|
| 186 |
+
result = r.get('result') or {}
|
| 187 |
+
n = step(r.get('turn'))
|
| 188 |
+
act = (r.get('action') or {}).get('action')
|
| 189 |
+
if n is None or not result.get('ok') or act not in ('use', 'press', 'take'):
|
| 190 |
+
continue
|
| 191 |
+
after = (r.get('_progress_evidence150') or {}).get('after') or {}
|
| 192 |
+
gs = after.get('gadgets') or {}
|
| 193 |
+
count = 0
|
| 194 |
+
held = {slot: gs.get(slot, {}).get('holding') for slot, g in gadgets.items() if g.get('type') == 'slot'}
|
| 195 |
+
occ = {slot for slot, value in held.items() if value}
|
| 196 |
+
ids = {slot: self.byname.get(value, value) for slot, value in held.items() if value}
|
| 197 |
+
if kind == 'pattern':
|
| 198 |
+
options = spec.get('targets_any') or [spec.get('targets') or []]
|
| 199 |
+
count = max([len(occ) for target in options if occ <= set(target)] + [0])
|
| 200 |
+
elif kind == 'assign':
|
| 201 |
+
options = spec.get('answers') or [spec.get('answer') or {}]
|
| 202 |
+
count = max([len(ids) for answer in options if all((answer.get(slot) == item for slot, item in ids.items()))] + [0])
|
| 203 |
+
elif kind == 'rotate' and (not spec.get('connectivity')):
|
| 204 |
+
need = {name: g for name, g in gadgets.items() if int(g.get('target', 0)) % int(g.get('period', 4)) != int(g.get('turns', 0)) % int(g.get('period', 4))}
|
| 205 |
+
count = sum((gs.get(name, {}).get('turns') is not None and int(gs[name]['turns']) % int(g.get('period', 4)) == int(g.get('target', 0)) % int(g.get('period', 4)) for name, g in need.items()))
|
| 206 |
+
events.append((n, count, index))
|
| 207 |
+
self._groups[group] = events
|
| 208 |
+
return events
|
| 209 |
+
|
| 210 |
+
def group_node(self, node):
|
| 211 |
+
kind = node['kind']
|
| 212 |
+
group = node['group']
|
| 213 |
+
nmax = node.get('total', 1)
|
| 214 |
+
if kind == 'paint':
|
| 215 |
+
for index, r in enumerate(self.turns):
|
| 216 |
+
res = r.get('result') or {}
|
| 217 |
+
n = step(r.get('turn'))
|
| 218 |
+
if n is not None and res.get('ok') and ((res.get('paint') or {}).get(node['target']) == node['colour']):
|
| 219 |
+
return dict(step=n, source='logged_paint_state', target=node['target'], colour=node['colour'], record=index)
|
| 220 |
+
else:
|
| 221 |
+
for n, count, index in self.group_progress(group):
|
| 222 |
+
if count >= node['rank']:
|
| 223 |
+
return dict(step=n, source='legal_partial_group_state', group=group, rank=node['rank'], record=index)
|
| 224 |
+
solved = self.raw(['solved ' + group])
|
| 225 |
+
if solved:
|
| 226 |
+
return dict(solved, source='native_solved_group_entails_goal_state', group=group)
|
| 227 |
+
return None
|
| 228 |
+
|
| 229 |
+
def evaluate(summary, cfg, turns=(), objects=None):
|
| 230 |
+
row, digest = definition(cfg)
|
| 231 |
+
e = Evidence(summary, cfg, turns, objects)
|
| 232 |
+
kept = {}
|
| 233 |
+
proof = {}
|
| 234 |
+
labels = {}
|
| 235 |
+
owned_aliases = {}
|
| 236 |
+
for node in row['nodes']:
|
| 237 |
+
key = node['key']
|
| 238 |
+
assert key not in kept
|
| 239 |
+
result = e.group_node(node) if node['kind'] in ('group_rank', 'paint') else e.event(node)
|
| 240 |
+
kept[key] = result['step'] if result else None
|
| 241 |
+
if result:
|
| 242 |
+
proof[key] = result
|
| 243 |
+
labels[key] = node['label_zh']
|
| 244 |
+
for alias in node.get('aliases', []):
|
| 245 |
+
owned_aliases.setdefault(alias, key)
|
| 246 |
+
removed = {}
|
| 247 |
+
for key, value in (summary.get('milestones') or {}).items():
|
| 248 |
+
if key in kept:
|
| 249 |
+
continue
|
| 250 |
+
removed[key] = dict(step=value, reason=row['removed'].get(key, 'merged_equivalent_event' if key in owned_aliases else 'not_a_required_checkpoint'), merged_into=owned_aliases.get(key))
|
| 251 |
+
return dict(milestones=kept, milestone_policy=POLICY, milestone_exclusions=removed, milestone_evidence=proof, milestone_labels=labels, milestone_definition_sha256=digest, milestone_definition_count=len(kept), milestone_unverifiable=[], milestone_basis='frozen per-level definitions; first actual state/event only; all configured legal methods; no thought/oracle inference')
|
| 252 |
+
|
| 253 |
+
def milestone_items(summary, cfg, turns=(), objects=None):
|
| 254 |
+
value = evaluate(summary, cfg, turns, objects)
|
| 255 |
+
return (value['milestones'], value['milestone_exclusions'])
|
| 256 |
+
|
| 257 |
+
def corrected_metrics(record, cfg, summary=None, turns=(), objects=None):
|
| 258 |
+
s = summary or record.get('raw_summary') or dict(milestones=record.get('milestones', {}))
|
| 259 |
+
value = evaluate(s, cfg, turns, objects)
|
| 260 |
+
marks = value['milestones']
|
| 261 |
+
achieved = {k: v for k, v in marks.items() if v is not None}
|
| 262 |
+
progress = sorted(set(achieved.values()))
|
| 263 |
+
trigger = record.get('hint_trigger_step')
|
| 264 |
+
nxt = min((n for n in progress if trigger is not None and n > trigger), default=None)
|
| 265 |
+
out = dict(record)
|
| 266 |
+
out.update(value)
|
| 267 |
+
out.update(milestone_total=len(marks), milestone_completed=len(achieved), milestone_completion_rate=len(achieved) / len(marks) if marks else None, first_milestone_step=min(progress, default=None), last_milestone_step=max(progress, default=None), next_progress_after_tip_step=nxt, actions_until_progress_after_tip=nxt - trigger if nxt is not None else None)
|
| 268 |
+
return out
|
| 269 |
+
|
| 270 |
+
def checkpoint_html(value):
|
| 271 |
+
import html
|
| 272 |
+
esc = lambda x: html.escape(str(x))
|
| 273 |
+
body = '<h2 id="milestones">进度节点</h2><div class="box" data-checkpoint-policy="' + POLICY + '">逐关固定检查点;必要线索和道具保留,干扰项与同义事件不重复计分。仅按实际记录计首次达成,不要求标准解顺序。<br>这是进度覆盖率,通关仍以成功open真实出口为准;未发生的read/take不因通关而补造。</div>'
|
| 274 |
+
body += '<table><tr><th>检查点</th><th>首次达成</th><th>原日志依据</th></tr>'
|
| 275 |
+
for key, n in value['milestones'].items():
|
| 276 |
+
evidence = value.get('milestone_evidence', {}).get(key)
|
| 277 |
+
proof = '<details><summary>依据</summary><pre>' + esc(json.dumps(evidence, ensure_ascii=False, indent=2)) + '</pre></details>' if evidence else '尚无达成证据'
|
| 278 |
+
body += '<tr><td>' + esc(value.get('milestone_labels', {}).get(key, key)) + '<br><code>' + esc(key) + '</code></td><td>' + ('第 ' + str(n) + ' 步' if n is not None else '尚未达成') + '</td><td>' + proof + '</td></tr>'
|
| 279 |
+
return body + '</table>'
|
runtime/legacy_metrics/milestone_filter268.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
import hashlib, json, re
|
| 4 |
+
ROOT = Path(__file__).resolve().parent
|
| 5 |
+
POLICY = 'required_marks_exclude_decoys_rest_and_traps268_v1'
|
| 6 |
+
METRIC_KEYS = {'milestones', 'milestone_total', 'milestone_completed', 'milestone_completion_rate', 'first_milestone_step', 'last_milestone_step', 'next_progress_after_tip_step', 'actions_until_progress_after_tip', 'milestone_policy', 'milestone_exclusions'}
|
| 7 |
+
|
| 8 |
+
def read(p):
|
| 9 |
+
return json.loads(Path(p).read_text('utf8'))
|
| 10 |
+
|
| 11 |
+
def normalized(value):
|
| 12 |
+
return ' '.join(str(value).strip().casefold().split())
|
| 13 |
+
|
| 14 |
+
@lru_cache(maxsize=1)
|
| 15 |
+
def catalog():
|
| 16 |
+
default = read(ROOT / 'frozen_default.json')
|
| 17 |
+
for host in ('local', 'server'):
|
| 18 |
+
support = Path(default['host_settings'][host]['ESI_BUDGET_SUPPORT'])
|
| 19 |
+
if (support / 'manifest.json').is_file():
|
| 20 |
+
return (support, read(support / 'manifest.json'), read(support / 'level_aliases157.json'))
|
| 21 |
+
raise RuntimeError('Frozen catalog missing; do not infer milestone roles from names')
|
| 22 |
+
|
| 23 |
+
def config_for(value):
|
| 24 |
+
support, manifest, aliases = catalog()
|
| 25 |
+
name = value.get('config_file') or value.get('config') or value.get('name')
|
| 26 |
+
key = str(name).replace('\\', '/').rsplit('/', 1)[-1].removesuffix('.json')
|
| 27 |
+
name = next((aliases[k][key] for k in ('by_new_name', 'by_new_id', 'by_legacy_name', 'by_legacy_id') if key in aliases.get(k, {})), None)
|
| 28 |
+
if name is None:
|
| 29 |
+
raise ValueError('Unknown level config: ' + key)
|
| 30 |
+
p = support / 'catalog' / (name + '.json')
|
| 31 |
+
digest = hashlib.sha256(p.read_bytes()).hexdigest()
|
| 32 |
+
assert manifest['resource_hashes']['catalog/' + p.name] == digest, 'Frozen catalog hash mismatch'
|
| 33 |
+
if value.get('config_sha256'):
|
| 34 |
+
assert value['config_sha256'] == digest
|
| 35 |
+
return read(p)
|
| 36 |
+
|
| 37 |
+
def exclusions_for(summary, cfg):
|
| 38 |
+
excluded = {}
|
| 39 |
+
|
| 40 |
+
def add(obj, reason):
|
| 41 |
+
for k in ('id', 'name', 'display'):
|
| 42 |
+
if obj.get(k) is not None:
|
| 43 |
+
excluded[normalized(obj[k])] = reason
|
| 44 |
+
collections = [cfg.get(k, []) for k in ('items', 'scene_add', 'gadgets', 'doors')]
|
| 45 |
+
collections.append((summary.get('scoring_only') or {}).get('items', []))
|
| 46 |
+
for objects in collections:
|
| 47 |
+
for obj in objects:
|
| 48 |
+
if normalized(obj.get('role', '')) in ('decoy', 'distractor') or normalized(obj.get('kind', '')) in ('decoy', 'distractor') or obj.get('decoy') is True or (obj.get('distractor') is True):
|
| 49 |
+
add(obj, 'explicit_distractor')
|
| 50 |
+
rest = {group for group, info in cfg.get('slot_groups', {}).items() if info.get('kind') == 'rest'}
|
| 51 |
+
for group in rest:
|
| 52 |
+
excluded[normalized(group)] = 'optional_rest_slot'
|
| 53 |
+
for gadget in cfg.get('gadgets', []):
|
| 54 |
+
if gadget.get('type') == 'slot' and gadget.get('group') in rest:
|
| 55 |
+
for key in ('id', 'name'):
|
| 56 |
+
if gadget.get(key) is not None:
|
| 57 |
+
excluded[normalized(gadget[key])] = 'optional_rest_slot'
|
| 58 |
+
trap_locks = {(str(name), int(part)) for trap in cfg.get('traps', []) for name, part in trap.get('locks', [])}
|
| 59 |
+
for lock in cfg.get('part_locks', []):
|
| 60 |
+
if lock.get('latent') is True and (str(lock.get('container')), int(lock.get('part', 1))) in trap_locks:
|
| 61 |
+
add(lock, 'trap_only_latent_lock')
|
| 62 |
+
return excluded
|
| 63 |
+
|
| 64 |
+
def milestone_items(summary, cfg):
|
| 65 |
+
excluded = exclusions_for(summary, cfg)
|
| 66 |
+
kept = {}
|
| 67 |
+
removed = {}
|
| 68 |
+
for key, value in (summary.get('milestones') or {}).items():
|
| 69 |
+
pieces = str(key).split(maxsplit=1)
|
| 70 |
+
verb = normalized(pieces[0]) if pieces else ''
|
| 71 |
+
target = normalized(pieces[1]) if len(pieces) > 1 else ''
|
| 72 |
+
reason = 'negative_trap_event' if verb == 'trap' else excluded.get(target)
|
| 73 |
+
if reason is None and ':' in target:
|
| 74 |
+
reason = excluded.get(target.split(':', 1)[0])
|
| 75 |
+
if reason:
|
| 76 |
+
removed[key] = dict(reason=reason, step=value)
|
| 77 |
+
else:
|
| 78 |
+
kept[key] = value
|
| 79 |
+
return (kept, removed)
|
| 80 |
+
|
| 81 |
+
def corrected_metrics(record, cfg, summary=None):
|
| 82 |
+
from metrics268 import step
|
| 83 |
+
s = summary or record.get('raw_summary') or dict(milestones=record.get('milestones', {}))
|
| 84 |
+
kept, removed = milestone_items(s, cfg)
|
| 85 |
+
achieved = {k: v for k, v in kept.items() if v is not None}
|
| 86 |
+
progress = sorted({step(v) for v in achieved.values() if step(v) is not None})
|
| 87 |
+
trigger = record.get('hint_trigger_step')
|
| 88 |
+
nxt = min((x for x in progress if trigger is not None and x > trigger), default=None)
|
| 89 |
+
out = dict(record)
|
| 90 |
+
out.update(milestones=kept, milestone_total=len(kept), milestone_completed=len(achieved), milestone_completion_rate=len(achieved) / len(kept) if kept else None, first_milestone_step=min(progress, default=None), last_milestone_step=max(progress, default=None), next_progress_after_tip_step=nxt, actions_until_progress_after_tip=nxt - trigger if nxt is not None else None, milestone_policy=POLICY, milestone_exclusions=removed)
|
| 91 |
+
return out
|
runtime/legacy_resume.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json, copy, hashlib, os, shutil, time
|
| 3 |
+
from episode_plan import save, SYSTEM_INSTRUCTION
|
| 4 |
+
from native_model_episode import restore_client_calls, paid_record_fingerprint
|
| 5 |
+
CONTEXT = None
|
| 6 |
+
|
| 7 |
+
def prepare(plan, level, out, client):
|
| 8 |
+
global CONTEXT
|
| 9 |
+
out = Path(out)
|
| 10 |
+
cp = out / 'native/checkpoints/latest/escape_ckpt.json'
|
| 11 |
+
log = out / 'native/escape_log.json'
|
| 12 |
+
if not cp.exists() or not log.exists():
|
| 13 |
+
raise ValueError('No complete original legacy checkpoint; never restart an existing case from0')
|
| 14 |
+
ck = json.loads(cp.read_text('utf8'))
|
| 15 |
+
raw = json.loads(log.read_text('utf8'))
|
| 16 |
+
counted = [t['turn'] for t in raw['turns'] if t.get('counted') and isinstance(t.get('turn'), int)]
|
| 17 |
+
last = max(counted, default=0)
|
| 18 |
+
if last != int(ck['t']):
|
| 19 |
+
raise ValueError('Latest action log and physical checkpoint differ; explicit recovery review required, no replay')
|
| 20 |
+
prefix = raw['turns']
|
| 21 |
+
if ck['turns'] != prefix[:len(ck['turns'])]:
|
| 22 |
+
raise ValueError('Original checkpoint history prefix differs')
|
| 23 |
+
ck['turns'] = copy.deepcopy(prefix)
|
| 24 |
+
ck['recalls'] = int(raw['summary'].get('recalls', ck['recalls']))
|
| 25 |
+
consumed = sum((bool((x.get('model') or {}).get('raw')) for x in prefix))
|
| 26 |
+
calls = restore_client_calls(client, out)
|
| 27 |
+
if len(calls) < consumed or len(calls) > consumed + 1:
|
| 28 |
+
raise ValueError('Recorded model responses do not align with executed legacy history')
|
| 29 |
+
next_decision = consumed + 1
|
| 30 |
+
pending = out / 'api' / ('decision_%04d_input.json' % next_decision)
|
| 31 |
+
if not pending.exists():
|
| 32 |
+
seq = max([int(x.get('api_sequence', 0)) for x in calls[:consumed]] + [consumed]) + 1
|
| 33 |
+
pending = out / 'api' / ('%04d_request.json' % seq)
|
| 34 |
+
frozen = json.loads(pending.read_text('utf8')) if pending.exists() else None
|
| 35 |
+
if frozen is None:
|
| 36 |
+
raise ValueError('Original pending input unavailable; no regenerated paid input allowed')
|
| 37 |
+
for x in frozen['contents']:
|
| 38 |
+
if x['type'] == 'image' and hashlib.sha256(Path(x['path']).read_bytes()).hexdigest() != x['sha256']:
|
| 39 |
+
raise ValueError('Saved legacy input image changed')
|
| 40 |
+
if frozen['system_instruction'] != SYSTEM_INSTRUCTION:
|
| 41 |
+
raise ValueError('Original system instruction changed')
|
| 42 |
+
folder = out / ('resume_input_' + str(time.time_ns()))
|
| 43 |
+
folder.mkdir()
|
| 44 |
+
save(folder / 'escape_ckpt.json', ck)
|
| 45 |
+
shutil.copy2(cp.with_name('map.json'), folder / 'map.json')
|
| 46 |
+
os.environ['ESI_ESCAPE_RESUME'] = str(folder)
|
| 47 |
+
os.environ['ESI_ESCAPE_RESUME_FULL'] = '1'
|
| 48 |
+
CONTEXT = {'checkpoint': ck, 'prefix': prefix, 'calls': calls, 'consumed': consumed, 'frozen': frozen, 'used': False, 'level': level, 'out': out}
|
| 49 |
+
from models import qwen as q
|
| 50 |
+
original = q.QwenModel.generate_json
|
| 51 |
+
|
| 52 |
+
def generate(self, contents, system_instruction, **kwargs):
|
| 53 |
+
if not CONTEXT['used']:
|
| 54 |
+
CONTEXT['used'] = True
|
| 55 |
+
actual = [Path(x['path']) if x['type'] == 'image' else x['text'] for x in frozen['contents']]
|
| 56 |
+
if len(calls) > consumed:
|
| 57 |
+
from native_model_episode import explicit_contents, replay_saved_action
|
| 58 |
+
packet = {'model_input_contents': frozen['contents']}
|
| 59 |
+
_, digest = explicit_contents(packet)
|
| 60 |
+
record = calls[consumed]
|
| 61 |
+
if paid_record_fingerprint(record) != digest:
|
| 62 |
+
raise ValueError('Saved paid legacy response belongs to a different input')
|
| 63 |
+
q.THINKING.append(copy.deepcopy(record))
|
| 64 |
+
return (replay_saved_action(record), record['content'], record.get('finish_reason', 'stop'))
|
| 65 |
+
return original(self, actual, system_instruction, **kwargs)
|
| 66 |
+
return original(self, contents, system_instruction, **kwargs)
|
| 67 |
+
q.QwenModel.generate_json = generate
|
| 68 |
+
save(out / 'RESUME_PREPARED.json', {'passed': True, 'from_action': last, 'recalls': ck['recalls'], 'executed_model_decisions': consumed, 'recorded_model_calls': len(calls), 'same_pending_contents': True, 'new_model_calls': 0})
|
| 69 |
+
return CONTEXT
|
| 70 |
+
|
| 71 |
+
def install_prompt(E):
|
| 72 |
+
if CONTEXT is None:
|
| 73 |
+
return
|
| 74 |
+
old = E.Escape.prompt
|
| 75 |
+
|
| 76 |
+
def prompt(esc, *args, **kwargs):
|
| 77 |
+
result = old(esc, *args, **kwargs)
|
| 78 |
+
if not CONTEXT['used']:
|
| 79 |
+
ck = CONTEXT['checkpoint']
|
| 80 |
+
if not esc.resumed or esc.turns != CONTEXT['prefix'] or int(esc.recalls) != int(ck['recalls']):
|
| 81 |
+
raise ValueError('Restored legacy state/history not verified')
|
| 82 |
+
frozen = CONTEXT['frozen']
|
| 83 |
+
esc._claw_contents = [Path(x['path']) if x['type'] == 'image' else x['text'] for x in frozen['contents']]
|
| 84 |
+
result = ''.join(('[photo: ' + x.name + ']' if isinstance(x, Path) else str(x) for x in esc._claw_contents))
|
| 85 |
+
save(CONTEXT['out'] / 'RESUME_VERIFICATION.json', {'passed': True, 'from_action': ck['t'], 'recalls_retained': esc.recalls, 'history_retained': True, 'frozen_pending_image_and_text_bytes': True, 'model_decisions_replayed': 0})
|
| 86 |
+
return result
|
| 87 |
+
E.Escape.prompt = prompt
|
runtime/legacy_scene_bootstrap.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys, json, importlib.util, types, math
|
| 3 |
+
ROOT = Path(__file__).resolve().parent
|
| 4 |
+
|
| 5 |
+
def install_driver(driver, public_id):
|
| 6 |
+
import unified_protocol as P
|
| 7 |
+
row = P.resolve(public_id)
|
| 8 |
+
if row['kind'] != 'native_room':
|
| 9 |
+
raise ValueError('Common native binding is for a new native room')
|
| 10 |
+
runtime = Path(driver.level.__file__).parent
|
| 11 |
+
root_runtime = ROOT / 'native_runtime'
|
| 12 |
+
sys.path.insert(0, str(root_runtime))
|
| 13 |
+
sys.path.insert(0, str(runtime))
|
| 14 |
+
from legacy_entry import install_stack
|
| 15 |
+
E, C, _ = install_stack()
|
| 16 |
+
owner_path = ROOT / 'OWNER_PART_MAP.json'
|
| 17 |
+
motion_path = ROOT / 'MOTION_BINDINGS.json'
|
| 18 |
+
owners = json.loads(owner_path.read_text('utf8'))
|
| 19 |
+
motions = json.loads(motion_path.read_text('utf8'))
|
| 20 |
+
level = row['source_id']
|
| 21 |
+
if row.get('room_family') == 'medium_v6':
|
| 22 |
+
from legacy_h2_bridge import attach
|
| 23 |
+
session = attach(driver, driver.run / 'common_executor', working=ROOT, E=E, C=C)
|
| 24 |
+
elif level == 'R01':
|
| 25 |
+
from legacy_r01_pilot import attach
|
| 26 |
+
session = attach(driver, driver.run / 'common_executor', working=ROOT, E=E, C=C)
|
| 27 |
+
elif level == 'R02':
|
| 28 |
+
from legacy_r02_bridge import attach
|
| 29 |
+
session = attach(driver, driver.run / 'common_executor', working=ROOT, owner_map=owner_path, motion_map=motion_path, E=E, C=C)
|
| 30 |
+
else:
|
| 31 |
+
from legacy_rooms_bridge import attach
|
| 32 |
+
predicates = {}
|
| 33 |
+
if level == 'R14':
|
| 34 |
+
fn = getattr(driver.level, 'bolt_path_clear', None)
|
| 35 |
+
if not callable(fn):
|
| 36 |
+
raise RuntimeError('Real R14 geometry predicate is missing')
|
| 37 |
+
predicates['R14.bolt_path_clear'] = fn
|
| 38 |
+
session = attach(driver, driver.run / 'common_executor', working=ROOT, owner_map=owner_path, motion_map=motion_path, predicates=predicates, E=E, C=C)
|
| 39 |
+
e = session.esc
|
| 40 |
+
e.cfg.update(protocol='unified_v2', public_id=public_id, max_steps=row['action_cap'], recall_budget=row['recall_cap'], tip_window=row['tip_window'])
|
| 41 |
+
if row.get('room_family') == 'medium_v6':
|
| 42 |
+
e.cam_z = float(driver.pos[2]) - float(e.floor)
|
| 43 |
+
e._cam_z0 = e.cam_z
|
| 44 |
+
for key, sim in getattr(session.backend, 'key_to_sim', {}).items():
|
| 45 |
+
e._display[sim] = driver.label(key)
|
| 46 |
+
live_owners = getattr(session.backend, 'owner_map', None) or owners['levels'].get(level, {})
|
| 47 |
+
for owner in live_owners.get('owners', []):
|
| 48 |
+
if owner['owner_id'] in session.backend.objects:
|
| 49 |
+
e._display[owner['owner_id']] = str(owner.get('public_label') or owner['owner_id'].replace('_', ' '))
|
| 50 |
+
if hasattr(session.backend, 'exit_name'):
|
| 51 |
+
e._display[session.backend.exit_name] = 'exit door'
|
| 52 |
+
if hasattr(session, 'observe'):
|
| 53 |
+
session.observe(driver.pos, driver.yaw, math.degrees(driver.pitch))
|
| 54 |
+
else:
|
| 55 |
+
e.pos = driver.pos.copy()
|
| 56 |
+
e.yaw = float(driver.yaw)
|
| 57 |
+
e._claw_pitch = math.degrees(driver.pitch)
|
| 58 |
+
boxed, _ = C.shoot(e, 'initial')
|
| 59 |
+
e._claw_photos = [boxed]
|
| 60 |
+
from observation_group import attach as attach_observation_group
|
| 61 |
+
attach_observation_group(driver, session)
|
| 62 |
+
from legacy_driver_transport import attach as attach_transport
|
| 63 |
+
attach_transport(driver, session)
|
| 64 |
+
old_click = driver.click
|
| 65 |
+
aliases = live_owners.get('alias_to_owner_part', {})
|
| 66 |
+
if not aliases:
|
| 67 |
+
aliases = {key: {'owner_id': value[0], 'part': value[1]} for key, value in getattr(session.backend, 'part_aliases', {}).items()}
|
| 68 |
+
|
| 69 |
+
def click(d, key, kind='read', item=None, purpose='', **fields):
|
| 70 |
+
if kind in ('open', 'close', 'unlock') and key in aliases:
|
| 71 |
+
fields.setdefault('part', int(aliases[key]['part']))
|
| 72 |
+
if item is not None:
|
| 73 |
+
selected = []
|
| 74 |
+
for oid in e.holding:
|
| 75 |
+
sim = e.objs[oid]['sim']
|
| 76 |
+
meta = getattr(session.backend, 'item_metadata', {}).get(sim, {})
|
| 77 |
+
if meta.get('item_key', getattr(session.backend, 'sim_to_key', {}).get(sim)) == item:
|
| 78 |
+
selected.append(oid)
|
| 79 |
+
if len(selected) == 1:
|
| 80 |
+
oid = selected[0]
|
| 81 |
+
category = str(e.objs[oid]['cat'])
|
| 82 |
+
peers = C._held(e, category)
|
| 83 |
+
if oid in peers:
|
| 84 |
+
if len(peers) == 1:
|
| 85 |
+
item = category
|
| 86 |
+
else:
|
| 87 |
+
rank = peers.index(oid) + 1
|
| 88 |
+
words = list(E.ORD_WORDS)
|
| 89 |
+
candidates = ([words[rank - 1] + ' ' + category] if rank <= len(words) else []) + [str(rank) + ' ' + category, '#' + str(rank) + ' ' + category]
|
| 90 |
+
matches = [word for word in candidates if C._held(e, word) == [oid]]
|
| 91 |
+
if not matches:
|
| 92 |
+
raise RuntimeError('Authored helper cannot express the selected inventory instance through the public old ordinal syntax')
|
| 93 |
+
item = matches[0]
|
| 94 |
+
return old_click(key, kind, item, purpose, **fields)
|
| 95 |
+
driver.click = types.MethodType(click, driver)
|
| 96 |
+
driver.save('COMMON_EXECUTOR.json', {'public_id': public_id, 'source_id': level, 'executor_file': str(Path(E.__file__).resolve()), 'dispatcher_file': str(Path(C.__file__).resolve()), 'point_method_file': C._at_point.__code__.co_filename, 'movement_method_file': C._move.__code__.co_filename, 'part_map': str(owner_path), 'motion_map': str(motion_path), 'new_driver_action_fallback': False, 'model_calls': 0})
|
| 97 |
+
return session
|
runtime/legacy_source/cabinet_joint345/MODIFIED_FILE.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, math, os, time
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
class Recorder:
|
| 5 |
+
|
| 6 |
+
def __init__(self, esc, third_only=False, *, cpu_mock_fov_h=None, reference_eye_height=None):
|
| 7 |
+
import numpy as np
|
| 8 |
+
import imageio.v2 as imageio
|
| 9 |
+
import omnigibson as og
|
| 10 |
+
self.e, self.og, self.np = (esc, og, np)
|
| 11 |
+
self.cpu_mock_fov_h = cpu_mock_fov_h
|
| 12 |
+
if third_only:
|
| 13 |
+
raise ValueError('Live164 prohibits post-run spectator recovery')
|
| 14 |
+
self.third_only = False
|
| 15 |
+
from video_inventory164 import Inventory
|
| 16 |
+
self.inventory = Inventory(esc)
|
| 17 |
+
from video_pacing165 import validate
|
| 18 |
+
self.pacing = validate(json.loads(os.environ.get('ESI_ESCAPE_VIDEO_PACING', '{}')))
|
| 19 |
+
self._still165 = None
|
| 20 |
+
self._world_revision228 = 0
|
| 21 |
+
self._photo_revision228 = 0
|
| 22 |
+
self._capture_revision228 = 0
|
| 23 |
+
self._pair_confirmed228 = False
|
| 24 |
+
self._world_edit228 = False
|
| 25 |
+
self._tp_last168 = None
|
| 26 |
+
import sys
|
| 27 |
+
avatar_root = Path(__file__).with_name('avatar3d168')
|
| 28 |
+
sys.path.insert(0, str(avatar_root))
|
| 29 |
+
from video_robot_gl168 import LiveRobot
|
| 30 |
+
self.robot168 = LiveRobot(avatar_root, reference_eye_height=float(reference_eye_height) if reference_eye_height is not None else float(getattr(esc, '_cam_z0', None) or esc.cam_z) - float(esc.floor))
|
| 31 |
+
from video_action164 import VideoAction
|
| 32 |
+
self.display = VideoAction(esc)
|
| 33 |
+
self.root = Path(os.environ.get('ESI_ESCAPE_VIDEO_DIR') or esc.out / 'video')
|
| 34 |
+
self.root.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
self.fps = int(os.environ.get('ESI_ESCAPE_VIDEO_FPS', '12'))
|
| 36 |
+
if not 4 <= self.fps <= 30:
|
| 37 |
+
raise ValueError('Video FPS must be 4..30')
|
| 38 |
+
self.paths = [self.root / 'first_person.mp4', self.root / 'third_person.mp4']
|
| 39 |
+
if any((p.exists() for p in self.paths)) or (self.root / 'combined.mp4').exists():
|
| 40 |
+
if not getattr(esc, 'resumed', False):
|
| 41 |
+
raise FileExistsError('Do not overwrite a fresh episode video')
|
| 42 |
+
base = self.root
|
| 43 |
+
number = 2
|
| 44 |
+
while (base / f'segment_{number:03d}').exists():
|
| 45 |
+
number += 1
|
| 46 |
+
self.root = base / f'segment_{number:03d}'
|
| 47 |
+
self.root.mkdir()
|
| 48 |
+
self.paths = [self.root / 'first_person.mp4', self.root / 'third_person.mp4']
|
| 49 |
+
from video_pair_writer230 import make_writers
|
| 50 |
+
self._paired230 = make_writers(self.root, self.fps, legacy_dual=os.environ.get('ESI_ESCAPE_VIDEO_LEGACY_DUAL', '0') == '1')
|
| 51 |
+
self.writers = self._paired230.writers
|
| 52 |
+
self.paths = list(self._paired230.paths)
|
| 53 |
+
self.log = (self.root / 'frames.jsonl').open('w', encoding='utf-8')
|
| 54 |
+
self.count, self.busy, self.closed, self.tick = (0, False, False, 0)
|
| 55 |
+
self.label = {'turn': 0, 'action': 'start'}
|
| 56 |
+
self.last = self.current()
|
| 57 |
+
self.render = og.sim.render
|
| 58 |
+
self.settle_frames = max(8, int(os.environ.get('ESI_ESCAPE_VIDEO_SETTLE_FRAMES', '8')))
|
| 59 |
+
from omnigibson.sensors import VisionSensor
|
| 60 |
+
before_tick = int(og.sim.current_time_step_index)
|
| 61 |
+
self.tp_camera227 = VisionSensor(relative_prim_path='/videoLive227/thirdCamera', name='video_third227', modalities=['rgb', 'depth_linear'], image_width=1280, image_height=720, focal_length=12.0, horizontal_aperture=float(og.sim.viewer_camera.horizontal_aperture), clipping_range=tuple(map(float, og.sim.viewer_camera.clipping_range)))
|
| 62 |
+
self.tp_camera227.load(esc.env.scene)
|
| 63 |
+
self.tp_camera227.initialize()
|
| 64 |
+
if int(og.sim.current_time_step_index) != before_tick:
|
| 65 |
+
raise RuntimeError('Video camera creation advanced physics')
|
| 66 |
+
self.metadata = dict(version=221, fps=self.fps, size=[640, 424], combined_size=[1280, 424], combined_pair='same arrays/same world tick; video only', camera_source='accepted formal178 original angle; no new camera design', scene_size=[640, 360], inventory_hud='video only; actual holding; not model input', third_only_recovery=False, capture_mode='live paired views before world advances', shared_refresh227=True, native_camera_video227='model viewer FP unchanged optics + dedicated1280x720 TP downsampled640x360, one8-render pass', post_run_rerender=False, resume_segment=bool(getattr(esc, 'resumed', False)), resume_action=getattr(esc, 't', 0), model_input_changed=False, spectator_sent_to_model=False, action_overlay='first person video only; actual ok and original failure feedback', point_overlay='submitted clicked-photo pixels; camera motion uses observation inset', video_source='native renderer; not step-image slideshow', third_person_camera='smooth angled follower; max55mm camera motion per frame; no cuts', third_person_marker='2D RGB position/heading with projected robot display; no USD/world geometry', third_person_avatar='actual R1 mesh, isolated live OpenGL render+world-depth occlusion; no OG geometry', marker_scene_geometry=False, marker_projection='actual TP camera quaternion; fov_h radians at focal12', marker_cpu_mock_fov_h=cpu_mock_fov_h, timeline='live action timeline plus explicit video-only human-viewing holds; no program sleeps', presentation_pacing=self.pacing, cached_holds_extra_physics_steps=0, walk='validated 5cm engine waypoints', turns='native camera interpolation between committed views', extra_physics_steps=0, paths=[str(p.resolve()) for p in self.paths], frames=0)
|
| 67 |
+
self.save()
|
| 68 |
+
|
| 69 |
+
def current(self):
|
| 70 |
+
return [float(self.e.pos[0]), float(self.e.pos[1]), float(self.e.cam_z), float(self.e.yaw), float(getattr(self.e, '_claw_pitch', 0.0))]
|
| 71 |
+
|
| 72 |
+
def visible(self, yes):
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
@staticmethod
|
| 76 |
+
def project_pixel(point, camera_position, camera_quaternion, fov_h, width=640, height=360):
|
| 77 |
+
import numpy as np
|
| 78 |
+
|
| 79 |
+
def array(value):
|
| 80 |
+
if hasattr(value, 'detach'):
|
| 81 |
+
value = value.detach()
|
| 82 |
+
if hasattr(value, 'cpu'):
|
| 83 |
+
value = value.cpu()
|
| 84 |
+
return np.asarray(value, dtype=float)
|
| 85 |
+
p = array(point)
|
| 86 |
+
c = array(camera_position)
|
| 87 |
+
q = array(camera_quaternion)
|
| 88 |
+
if p.shape != (3,) or c.shape != (3,) or q.shape != (4,):
|
| 89 |
+
raise ValueError('Invalid camera/point shape')
|
| 90 |
+
if not np.isfinite(p).all() or not np.isfinite(c).all() or (not np.isfinite(q).all()):
|
| 91 |
+
raise ValueError('Non-finite projection input')
|
| 92 |
+
norm = float(np.linalg.norm(q))
|
| 93 |
+
if norm <= 1e-12 or not math.isfinite(fov_h) or (not 0 < fov_h < math.pi):
|
| 94 |
+
raise ValueError('Invalid quaternion/HFOV radians')
|
| 95 |
+
x, y, z, w = q / norm
|
| 96 |
+
R = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
|
| 97 |
+
local = R.T @ (p - c)
|
| 98 |
+
depth = -float(local[2])
|
| 99 |
+
if depth <= 1e-06:
|
| 100 |
+
return None
|
| 101 |
+
fx = width / 2.0 / math.tan(fov_h / 2.0)
|
| 102 |
+
return (width / 2.0 + fx * float(local[0]) / depth, height / 2.0 - fx * float(local[1]) / depth, depth)
|
| 103 |
+
|
| 104 |
+
def tp_marker_rgb(self, rgb, pose, camera227=None):
|
| 105 |
+
from PIL import Image, ImageDraw
|
| 106 |
+
result = rgb.copy()
|
| 107 |
+
info = dict(drawn=False, mode='RGB_ONLY', scene_geometry=False)
|
| 108 |
+
try:
|
| 109 |
+
cam = camera227 or self.og.sim.viewer_camera
|
| 110 |
+
info['focal_length'] = float(cam.focal_length)
|
| 111 |
+
try:
|
| 112 |
+
fov = 2 * math.atan(float(cam.horizontal_aperture) / (2 * float(cam.focal_length))) if camera227 is not None else float(self.e.c['fov_h']())
|
| 113 |
+
aperture = float(cam.horizontal_aperture)
|
| 114 |
+
focal = float(cam.focal_length)
|
| 115 |
+
if not math.isfinite(aperture) or not math.isfinite(focal) or aperture <= 0 or (focal <= 0):
|
| 116 |
+
raise ValueError('Invalid real TP optical calibration')
|
| 117 |
+
optical_fov = 2 * math.atan(aperture / (2 * focal))
|
| 118 |
+
if not math.isclose(fov, optical_fov, rel_tol=1e-07, abs_tol=1e-09):
|
| 119 |
+
raise ValueError('HFOV callback differs from real TP optics; implicit fallback rejected')
|
| 120 |
+
info['horizontal_aperture'] = aperture
|
| 121 |
+
info['projection_source'] = 'dedicated TP native camera optical calibration' if camera227 is not None else 'e.c[fov_h] radians verified against current TP optics'
|
| 122 |
+
except Exception as ex:
|
| 123 |
+
if self.cpu_mock_fov_h is None:
|
| 124 |
+
info.update(reason='real_fov_unavailable; marker skipped', error=type(ex).__name__ + ': ' + str(ex))
|
| 125 |
+
return (result, info)
|
| 126 |
+
fov = float(self.cpu_mock_fov_h)
|
| 127 |
+
info['projection_source'] = 'CPU_MOCK_EXPLICIT_FOV_RADIANS'
|
| 128 |
+
cp, cq = cam.get_position_orientation()
|
| 129 |
+
height, width = rgb.shape[:2]
|
| 130 |
+
center = self.project_pixel(pose[:3], cp, cq, fov, width, height)
|
| 131 |
+
tip_world = [pose[0] + math.cos(pose[3]) * 0.3, pose[1] + math.sin(pose[3]) * 0.3, pose[2]]
|
| 132 |
+
tip = self.project_pixel(tip_world, cp, cq, fov, width, height)
|
| 133 |
+
info.update(fov_h_radians=fov, position_pixel=None if center is None else list(center[:2]), heading_pixel=None if tip is None else list(tip[:2]), world_camera_position=list(map(float, pose[:3])), world_heading_tip=tip_world)
|
| 134 |
+
if center is None or not (0 <= center[0] < width and 0 <= center[1] < height):
|
| 135 |
+
info['reason'] = 'camera-position projection outside TP frame or behind camera'
|
| 136 |
+
return (result, info)
|
| 137 |
+
from video_robot_gl168 import array as avatar_array
|
| 138 |
+
for warm_attempt in range(4):
|
| 139 |
+
obs = cam.get_obs()[0]
|
| 140 |
+
depth = obs.get('depth_linear')
|
| 141 |
+
valid = False
|
| 142 |
+
if depth is not None:
|
| 143 |
+
d = avatar_array(depth)
|
| 144 |
+
valid = bool(self.np.any(self.np.isfinite(d) & (d > 0)))
|
| 145 |
+
if valid:
|
| 146 |
+
break
|
| 147 |
+
if warm_attempt < 3:
|
| 148 |
+
self.settle()
|
| 149 |
+
else:
|
| 150 |
+
raise RuntimeError('Same-view TP depth remained invalid after render-only warmup')
|
| 151 |
+
if warm_attempt:
|
| 152 |
+
result = self.rgb(camera227=cam).copy()
|
| 153 |
+
info['depth_warmup_render_retries'] = warm_attempt
|
| 154 |
+
shown, avatar = self.robot168.compose(result, avatar_array(depth), pose, cp, cq, fov, float(self.e.floor))
|
| 155 |
+
info['avatar'] = avatar
|
| 156 |
+
info['drawn'] = avatar['visible_pixels'] > 0
|
| 157 |
+
return (shown, info)
|
| 158 |
+
except Exception as ex:
|
| 159 |
+
info.update(reason='projection unavailable; marker skipped', error=type(ex).__name__ + ': ' + str(ex))
|
| 160 |
+
return (result, info)
|
| 161 |
+
|
| 162 |
+
def save(self):
|
| 163 |
+
self.metadata.update(frames=self.count, duration_seconds=self.count / self.fps, closed=self.closed, wall_time=time.time())
|
| 164 |
+
p = self.root / 'recording.json'
|
| 165 |
+
t = p.with_suffix('.tmp')
|
| 166 |
+
t.write_text(json.dumps(self.metadata, ensure_ascii=False, indent=2), encoding='utf-8')
|
| 167 |
+
os.replace(t, p)
|
| 168 |
+
|
| 169 |
+
def rgb(self, camera227=None):
|
| 170 |
+
from PIL import Image
|
| 171 |
+
cam = camera227 or self.og.sim.viewer_camera
|
| 172 |
+
|
| 173 |
+
def values(x):
|
| 174 |
+
if hasattr(x, 'detach'):
|
| 175 |
+
x = x.detach()
|
| 176 |
+
if hasattr(x, 'cpu'):
|
| 177 |
+
x = x.cpu().numpy()
|
| 178 |
+
return tuple(self.np.asarray(x).reshape(-1).tolist())
|
| 179 |
+
|
| 180 |
+
def capture_state():
|
| 181 |
+
cp, cq = cam.get_position_orientation()
|
| 182 |
+
return (int(self.og.sim.current_time_step_index), tuple(self.current()), values(cp), values(cq), float(cam.focal_length), tuple(getattr(self.e, 'holding', []) or []), tuple(map(str, getattr(self.e, '_claw_photos', []) or [])))
|
| 183 |
+
before = capture_state()
|
| 184 |
+
invalid = []
|
| 185 |
+
for attempt in range(4):
|
| 186 |
+
if capture_state() != before:
|
| 187 |
+
raise RuntimeError('Render-only RGB retry changed capture state')
|
| 188 |
+
raw = cam.get_obs()[0].get('rgb')
|
| 189 |
+
if raw is not None:
|
| 190 |
+
if hasattr(raw, 'cpu'):
|
| 191 |
+
raw = raw.cpu().numpy()
|
| 192 |
+
raw = self.np.asarray(raw)
|
| 193 |
+
valid = raw is not None and raw.ndim == 3 and (raw.shape[2] >= 3) and (raw.size > 0) and self.np.isfinite(raw[:, :, :3]).all() and self.np.any(raw[:, :, :3] != 0)
|
| 194 |
+
if capture_state() != before:
|
| 195 |
+
raise RuntimeError('Native RGB read changed capture state')
|
| 196 |
+
if valid:
|
| 197 |
+
x = raw[:, :, :3].astype('uint8')
|
| 198 |
+
if attempt:
|
| 199 |
+
self.metadata.setdefault('rgb_render_only_retries', []).append(dict(capture_frame=self.count, turn=self.label.get('turn'), retries=attempt, fresh_native_reads=attempt + 1, render_ticks=attempt * self.settle_frames, world_tick=before[0], invalid_outputs=invalid, physics_steps_added=0, neighbour_frame_substitution=False))
|
| 200 |
+
return self.np.asarray(Image.fromarray(x).resize((640, 360), Image.Resampling.LANCZOS))
|
| 201 |
+
invalid.append('missing' if raw is None else 'empty' if raw.size == 0 else 'invalid_shape' if raw.ndim != 3 or raw.shape[2] < 3 else 'nonfinite' if not self.np.isfinite(raw[:, :, :3]).all() else 'all_zero_rgb')
|
| 202 |
+
if attempt < 3:
|
| 203 |
+
for _ in range(self.settle_frames):
|
| 204 |
+
self.render()
|
| 205 |
+
if capture_state() != before:
|
| 206 |
+
raise RuntimeError('Render-only RGB retry changed capture state')
|
| 207 |
+
raise RuntimeError('Native renderer returned invalid RGB after 4 fresh reads / 3 render-only retries: ' + ','.join(invalid))
|
| 208 |
+
|
| 209 |
+
def settle(self):
|
| 210 |
+
for _ in range(self.settle_frames):
|
| 211 |
+
self.render()
|
| 212 |
+
|
| 213 |
+
def _original_tp_position178(self, p):
|
| 214 |
+
floor = float(self.e.floor)
|
| 215 |
+
sp = self.np.array([p[0], p[1], floor + 2.35])
|
| 216 |
+
room = self.e.room_name(p[0], p[1])
|
| 217 |
+
region = self.e.region_of(p[0], p[1])
|
| 218 |
+
for back in (0.7, 0.55, 0.4, 0.25, 0.1):
|
| 219 |
+
xy = self.np.array([p[0] - math.cos(p[3]) * back, p[1] - math.sin(p[3]) * back])
|
| 220 |
+
if self.e.room_name(*xy) == room and self.e.region_of(*xy) == region and self.e._wall_free_segment(self.np.array(p[:2]), xy) and (not self.e._cell_blocked(*xy, 0.08)):
|
| 221 |
+
sp[:2] = xy
|
| 222 |
+
break
|
| 223 |
+
last = getattr(self, '_tp_last168', None)
|
| 224 |
+
if last is not None:
|
| 225 |
+
delta = sp - last
|
| 226 |
+
distance = float(self.np.linalg.norm(delta))
|
| 227 |
+
candidate = last + delta * min(1.0, 0.055 / max(distance, 1e-12))
|
| 228 |
+
if distance <= 1.0 and self.e._wall_free_segment(last[:2], candidate[:2]) and (not self.e._cell_blocked(*candidate[:2], 0.08)):
|
| 229 |
+
sp = candidate
|
| 230 |
+
self._tp_last168 = sp.copy()
|
| 231 |
+
return sp
|
| 232 |
+
|
| 233 |
+
def frame(self, pose=None, source='physics_tick'):
|
| 234 |
+
if self.busy or self.closed or getattr(self, 'capture_failed', False):
|
| 235 |
+
return
|
| 236 |
+
p = list(pose or self.current())
|
| 237 |
+
self.busy = True
|
| 238 |
+
physics_before = int(self.og.sim.current_time_step_index)
|
| 239 |
+
cam = self.og.sim.viewer_camera
|
| 240 |
+
oldp, oldq = cam.get_position_orientation()
|
| 241 |
+
oldf = float(cam.focal_length)
|
| 242 |
+
try:
|
| 243 |
+
if not self.third_only:
|
| 244 |
+
cam.set_position_orientation(position=self.np.array(p[:3]), orientation=self.e.E.quat_from(p[3], p[4]))
|
| 245 |
+
floor = float(self.e.floor)
|
| 246 |
+
sp = self._original_tp_position178(p)
|
| 247 |
+
aim = self.np.array([p[0] + math.cos(p[3]) * 0.2, p[1] + math.sin(p[3]) * 0.2, floor + 0.85])
|
| 248 |
+
d = aim - sp
|
| 249 |
+
yaw = math.atan2(d[1], d[0])
|
| 250 |
+
pitch = math.degrees(math.atan2(d[2], math.hypot(d[0], d[1])))
|
| 251 |
+
tp = self.tp_camera227
|
| 252 |
+
tp.set_position_orientation(position=sp, orientation=self.e.E.quat_from(yaw, pitch))
|
| 253 |
+
self.settle()
|
| 254 |
+
first = self.rgb().copy()
|
| 255 |
+
third = self.rgb(camera227=tp).copy()
|
| 256 |
+
third, tp_marker = self.tp_marker_rgb(third, p, camera227=tp)
|
| 257 |
+
still_first, still_third = (first.copy(), third.copy())
|
| 258 |
+
first, inventory = self.inventory.compose(first)
|
| 259 |
+
first = self.display.compose(first, pose=p, force_inset=bool(self.inventory.reading))
|
| 260 |
+
third, _ = self.inventory.compose(third, reading=False)
|
| 261 |
+
if self.writers[0]:
|
| 262 |
+
self.writers[0].append_data(first)
|
| 263 |
+
self.writers[1].append_data(third)
|
| 264 |
+
physics_after = int(self.og.sim.current_time_step_index)
|
| 265 |
+
if physics_after != physics_before:
|
| 266 |
+
raise RuntimeError('World advanced between paired video views')
|
| 267 |
+
row = dict(frame=self.count, time=self.count / self.fps, **self.label, source=source, pose=p, spectator_position=sp.tolist(), physics_tick_before=physics_before, physics_tick_after=physics_after, live_pair=True, inventory=inventory, display_action=self.display.state(), tp_marker=tp_marker)
|
| 268 |
+
self.log.write(json.dumps(row, ensure_ascii=False) + '\n')
|
| 269 |
+
self._still165 = {'first': still_first, 'third': still_third, 'pose': p, 'row': dict(row)}
|
| 270 |
+
self.count += 1
|
| 271 |
+
self.last = p
|
| 272 |
+
self._capture_revision228 += 1
|
| 273 |
+
self._pair_confirmed228 = True
|
| 274 |
+
if self.count % 48 == 0:
|
| 275 |
+
self.log.flush()
|
| 276 |
+
self.save()
|
| 277 |
+
finally:
|
| 278 |
+
cam.focal_length = oldf
|
| 279 |
+
cam.set_position_orientation(position=oldp, orientation=oldq)
|
| 280 |
+
if source in ('episode_start', 'final_hold'):
|
| 281 |
+
self.settle()
|
| 282 |
+
self.busy = False
|
| 283 |
+
|
| 284 |
+
def hold(self, seconds, source='presentation_hold'):
|
| 285 |
+
if self.closed or getattr(self, 'capture_failed', False):
|
| 286 |
+
return
|
| 287 |
+
cached = getattr(self, '_still165', None)
|
| 288 |
+
if cached is None:
|
| 289 |
+
raise RuntimeError('No live pair available for video-only hold')
|
| 290 |
+
tick = int(self.og.sim.current_time_step_index)
|
| 291 |
+
if tick != cached['row']['physics_tick_after']:
|
| 292 |
+
raise RuntimeError('Cannot display a stale world state as a live hold')
|
| 293 |
+
from video_pacing165 import frames_for
|
| 294 |
+
repeats = frames_for(seconds, self.fps)
|
| 295 |
+
first, inventory = self.inventory.compose(cached['first'].copy())
|
| 296 |
+
first = self.display.compose(first, pose=cached['pose'], force_inset=bool(self.inventory.reading))
|
| 297 |
+
third, _ = self.inventory.compose(cached['third'].copy(), reading=False)
|
| 298 |
+
for _ in range(repeats):
|
| 299 |
+
if self.writers[0]:
|
| 300 |
+
self.writers[0].append_data(first)
|
| 301 |
+
self.writers[1].append_data(third)
|
| 302 |
+
row = dict(cached['row'])
|
| 303 |
+
row.update(frame=self.count, time=self.count / self.fps, **self.label, source=source, inventory=inventory, display_action=self.display.state(), scene_capture_frame=cached['row']['frame'], presentation_only_repeat=True, physics_tick_before=tick, physics_tick_after=tick)
|
| 304 |
+
self.log.write(json.dumps(row, ensure_ascii=False) + '\n')
|
| 305 |
+
self.count += 1
|
| 306 |
+
self.log.flush()
|
| 307 |
+
self.save()
|
| 308 |
+
|
| 309 |
+
def _finish_walk225(self):
|
| 310 |
+
walk = getattr(self, '_walk225', None)
|
| 311 |
+
if walk is None:
|
| 312 |
+
return
|
| 313 |
+
if int(self.og.sim.current_time_step_index) != walk['tick']:
|
| 314 |
+
raise RuntimeError('World advanced before the final validated walk frame')
|
| 315 |
+
self._walk225 = None
|
| 316 |
+
if self.last != walk['pose']:
|
| 317 |
+
self.frame(walk['pose'], 'validated_walk_waypoint')
|
| 318 |
+
|
| 319 |
+
def _sample_walk225(self, p):
|
| 320 |
+
walk = getattr(self, '_walk225', None)
|
| 321 |
+
start = list(walk['pose'] if walk is not None else self.last)
|
| 322 |
+
if p[2:] != start[2:]:
|
| 323 |
+
return False
|
| 324 |
+
tick = int(self.og.sim.current_time_step_index)
|
| 325 |
+
if walk is None:
|
| 326 |
+
walk = self._walk225 = dict(pose=start, seconds=0.0, samples=0, tick=tick)
|
| 327 |
+
elif tick != walk['tick']:
|
| 328 |
+
raise RuntimeError('World advanced during validated walk sampling')
|
| 329 |
+
secs = math.hypot(p[0] - start[0], p[1] - start[1]) / 0.55
|
| 330 |
+
elapsed = walk['seconds']
|
| 331 |
+
end = elapsed + secs
|
| 332 |
+
if secs > 0:
|
| 333 |
+
while (walk['samples'] + 1) / self.fps <= end + 1e-12:
|
| 334 |
+
sample = (walk['samples'] + 1) / self.fps
|
| 335 |
+
a = max(0.0, min(1.0, (sample - elapsed) / secs))
|
| 336 |
+
q = list(p) if a == 1.0 else [start[j] + (p[j] - start[j]) * a for j in range(5)]
|
| 337 |
+
self.frame(q, 'validated_walk_waypoint')
|
| 338 |
+
walk['samples'] += 1
|
| 339 |
+
walk['pose'] = list(p)
|
| 340 |
+
walk['seconds'] = end
|
| 341 |
+
return True
|
| 342 |
+
|
| 343 |
+
def transition(self, p, source='camera_motion'):
|
| 344 |
+
if self.busy:
|
| 345 |
+
return
|
| 346 |
+
p = list(p)
|
| 347 |
+
if source == 'validated_walk_waypoint' and self._sample_walk225(p):
|
| 348 |
+
return
|
| 349 |
+
self._finish_walk225()
|
| 350 |
+
start = list(self.last)
|
| 351 |
+
delta = (p[3] - start[3] + math.pi) % (2 * math.pi) - math.pi
|
| 352 |
+
action = getattr(getattr(self, 'display', None), 'action', None) or {}
|
| 353 |
+
if source == 'native_physics_tick' and action.get('action') == 'turn' and (action.get('direction') in ('left', 'right')):
|
| 354 |
+
delta = p[3] - start[3]
|
| 355 |
+
length = math.hypot(p[0] - start[0], p[1] - start[1])
|
| 356 |
+
secs = max(length / 0.55, abs(delta) / math.radians(75), abs(p[4] - start[4]) / 75)
|
| 357 |
+
n = max(1, min(48, int(math.ceil(secs * self.fps))))
|
| 358 |
+
for i in range(1, n + 1):
|
| 359 |
+
a = i / n
|
| 360 |
+
q = [start[j] + (p[j] - start[j]) * a for j in range(5)]
|
| 361 |
+
q[3] = start[3] + delta * a
|
| 362 |
+
self.frame(q, source)
|
| 363 |
+
|
| 364 |
+
def close(self, error=None, hold_frames=None):
|
| 365 |
+
if self.closed:
|
| 366 |
+
return
|
| 367 |
+
if error is None and getattr(self, 'capture_errors', []):
|
| 368 |
+
error = 'VIDEO_CAPTURE_ERROR: ' + self.capture_errors[0]['error']
|
| 369 |
+
try:
|
| 370 |
+
if error is None:
|
| 371 |
+
self._finish_walk225()
|
| 372 |
+
for _ in range(self.fps if hold_frames is None else int(hold_frames)):
|
| 373 |
+
self.frame(source='final_hold')
|
| 374 |
+
finally:
|
| 375 |
+
self.closed = True
|
| 376 |
+
for w in self.writers:
|
| 377 |
+
if w:
|
| 378 |
+
w.close()
|
| 379 |
+
self.log.flush()
|
| 380 |
+
self.log.close()
|
| 381 |
+
if getattr(self, 'robot168', None):
|
| 382 |
+
self.robot168.close()
|
| 383 |
+
if getattr(self, 'tp_camera227', None):
|
| 384 |
+
self.tp_camera227.remove()
|
| 385 |
+
self.metadata.update(success=bool(self.e.success), turns=self.e.t, error=error)
|
| 386 |
+
try:
|
| 387 |
+
from video_pair221 import finalize_pair
|
| 388 |
+
self._paired230.finalize(self.metadata, legacy_finalize=finalize_pair, expected_frames=self.count)
|
| 389 |
+
except Exception as ex:
|
| 390 |
+
issue = type(ex).__name__ + ': ' + str(ex)
|
| 391 |
+
self.metadata['pairing_error'] = issue
|
| 392 |
+
previous = self.metadata.get('error')
|
| 393 |
+
self.metadata['error'] = (str(previous) + '; ' if previous else '') + 'VIDEO_PAIRING_ERROR221: ' + issue
|
| 394 |
+
self.metadata['video_valid'] = False
|
| 395 |
+
print('VIDEO_PAIRING_ERROR221 ' + issue, flush=True)
|
| 396 |
+
self.save()
|
| 397 |
+
print('DUAL_VIDEO163_CLOSED', json.dumps(self.metadata, ensure_ascii=False), flush=True)
|
| 398 |
+
|
| 399 |
+
def _proof228(rec):
|
| 400 |
+
|
| 401 |
+
def values(value):
|
| 402 |
+
if hasattr(value, 'detach'):
|
| 403 |
+
value = value.detach()
|
| 404 |
+
if hasattr(value, 'cpu'):
|
| 405 |
+
value = value.cpu()
|
| 406 |
+
if hasattr(value, 'tolist'):
|
| 407 |
+
value = value.tolist()
|
| 408 |
+
return list(map(float, value))
|
| 409 |
+
|
| 410 |
+
def camera(cam):
|
| 411 |
+
cp, cq = cam.get_position_orientation()
|
| 412 |
+
return dict(position=values(cp), orientation=values(cq), focal_length=float(cam.focal_length), horizontal_aperture=float(cam.horizontal_aperture), resolution=[int(cam.image_width), int(cam.image_height)])
|
| 413 |
+
return dict(world_revision=rec._world_revision228, physics_revision=int(rec.og.sim.current_time_step_index), sdk_photo_revision=rec._photo_revision228, capture_revision=rec._capture_revision228, scene_static=not rec._world_edit228, pair_confirmed=rec._pair_confirmed228, fp_camera=camera(rec.og.sim.viewer_camera), tp_camera=camera(rec.tp_camera227))
|
| 414 |
+
from video_frame_cache227 import install as _install_static_cache228
|
| 415 |
+
_install_static_cache228(Recorder, proof=_proof228)
|
| 416 |
+
|
| 417 |
+
def install(E, C):
|
| 418 |
+
if os.environ.get('ESI_ESCAPE_VIDEO', '0') != '1':
|
| 419 |
+
return False
|
| 420 |
+
if getattr(E.Escape, '_video163_installed', False):
|
| 421 |
+
return True
|
| 422 |
+
setup, run, act, joint = (E.Escape.setup, E.Escape.run, C.act, E.Escape.set_joint)
|
| 423 |
+
|
| 424 |
+
def video_guard(esc, fn, *args, **kwargs):
|
| 425 |
+
rec = getattr(esc, '_video163', None)
|
| 426 |
+
cleanup = getattr(fn, '__name__', '') in ('close', 'save')
|
| 427 |
+
if rec and getattr(rec, 'capture_failed', False) and (not cleanup):
|
| 428 |
+
return None
|
| 429 |
+
try:
|
| 430 |
+
return fn(*args, **kwargs)
|
| 431 |
+
except Exception as ex:
|
| 432 |
+
import traceback
|
| 433 |
+
issue = {'callback': getattr(fn, '__qualname__', str(fn)), 'error': type(ex).__name__ + ': ' + str(ex), 'traceback': traceback.format_exc(), 'turn': getattr(esc, 't', None)}
|
| 434 |
+
if rec:
|
| 435 |
+
rec.capture_failed = True
|
| 436 |
+
rec.capture_errors = getattr(rec, 'capture_errors', []) + [issue]
|
| 437 |
+
rec.metadata['capture_errors'] = rec.capture_errors
|
| 438 |
+
rec.metadata['video_valid'] = False
|
| 439 |
+
rec.metadata['error'] = 'VIDEO_CAPTURE_ERROR: ' + issue['error']
|
| 440 |
+
try:
|
| 441 |
+
rec.save()
|
| 442 |
+
except Exception:
|
| 443 |
+
pass
|
| 444 |
+
else:
|
| 445 |
+
esc._video164_setup_errors = getattr(esc, '_video164_setup_errors', []) + [issue]
|
| 446 |
+
try:
|
| 447 |
+
path = Path(os.environ.get('ESI_ESCAPE_VIDEO_DIR') or esc.out / 'video')
|
| 448 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 449 |
+
(path / 'video_setup_error164.json').write_text(json.dumps(issue, ensure_ascii=False, indent=2), encoding='utf8')
|
| 450 |
+
except Exception:
|
| 451 |
+
pass
|
| 452 |
+
try:
|
| 453 |
+
print('VIDEO_CAPTURE_ERROR164 ' + json.dumps(issue, ensure_ascii=False), flush=True)
|
| 454 |
+
except Exception:
|
| 455 |
+
pass
|
| 456 |
+
return None
|
| 457 |
+
|
| 458 |
+
def video_setup(esc, *args, **kwargs):
|
| 459 |
+
result = setup(esc, *args, **kwargs)
|
| 460 |
+
if getattr(esc, '_video163_run_active', False) and (not hasattr(esc, '_video163')):
|
| 461 |
+
|
| 462 |
+
def attach():
|
| 463 |
+
rec = esc._video163 = Recorder(esc, reference_eye_height=float(E.CAM_H))
|
| 464 |
+
native_transition = rec.transition
|
| 465 |
+
|
| 466 |
+
def guarded_transition(*args, **kwargs):
|
| 467 |
+
return video_guard(esc, native_transition, *args, **kwargs)
|
| 468 |
+
rec.transition = guarded_transition
|
| 469 |
+
shot, step = (esc.c['shot'], esc.c['step_sim'])
|
| 470 |
+
|
| 471 |
+
def record_shot(path, pos, quat):
|
| 472 |
+
rec._photo_revision228 += 1
|
| 473 |
+
rec._pair_confirmed228 = False
|
| 474 |
+
if not str(path).endswith('_flush_view.png'):
|
| 475 |
+
|
| 476 |
+
def camera_motion():
|
| 477 |
+
y, p = esc.E.yaw_pitch_of(quat)
|
| 478 |
+
rec.transition([*map(float, pos), float(y), float(p)], 'camera_motion')
|
| 479 |
+
video_guard(esc, camera_motion)
|
| 480 |
+
result = shot(path, pos, quat)
|
| 481 |
+
rec._photo_revision228 += 1
|
| 482 |
+
rec._pair_confirmed228 = False
|
| 483 |
+
rec._frame_cache227_entry = None
|
| 484 |
+
rec._still165 = None
|
| 485 |
+
if not str(path).endswith('_flush_view.png'):
|
| 486 |
+
|
| 487 |
+
def committed_observation():
|
| 488 |
+
from video_pacing165 import stage_seconds
|
| 489 |
+
delay = stage_seconds(path, rec.pacing)
|
| 490 |
+
stem281 = Path(path).stem.lower()
|
| 491 |
+
optical281 = next((name for name in ('uv_off', 'zoom_restored', 'uv', 'zoom') if stem281.endswith('_' + name + '_clean')), None)
|
| 492 |
+
if optical281 in ('uv', 'zoom'):
|
| 493 |
+
delay = max(delay, float(rec.pacing.get('transient_observation_seconds', 2.0)))
|
| 494 |
+
if delay or 'keypad' in Path(path).stem.lower() or optical281:
|
| 495 |
+
y, p = esc.E.yaw_pitch_of(quat)
|
| 496 |
+
rec.frame([*map(float, pos), float(y), float(p)], source='native_optical_committed281' if optical281 else 'native_observation_committed274')
|
| 497 |
+
if delay and rec.label.get('action') == 'use':
|
| 498 |
+
rec.hold(delay, source='native_effect_hold')
|
| 499 |
+
video_guard(esc, committed_observation)
|
| 500 |
+
return result
|
| 501 |
+
|
| 502 |
+
def record_steps(n=10):
|
| 503 |
+
for i in range(int(n)):
|
| 504 |
+
if i == 0:
|
| 505 |
+
video_guard(esc, rec._finish_walk225)
|
| 506 |
+
step(1)
|
| 507 |
+
rec.tick += 1
|
| 508 |
+
if rec.tick % 3 == 0:
|
| 509 |
+
video_guard(esc, rec.transition, rec.current(), 'native_physics_tick')
|
| 510 |
+
esc.c['shot'] = record_shot
|
| 511 |
+
esc.c['step_sim'] = record_steps
|
| 512 |
+
video_guard(esc, rec.frame, source='episode_start')
|
| 513 |
+
video_guard(esc, attach)
|
| 514 |
+
return result
|
| 515 |
+
|
| 516 |
+
def video_act(esc, a):
|
| 517 |
+
rec = getattr(esc, '_video163', None)
|
| 518 |
+
if rec:
|
| 519 |
+
|
| 520 |
+
def before():
|
| 521 |
+
rec.inventory.cache_visible()
|
| 522 |
+
rec.display.begin(__import__('copy').deepcopy(a), rec.current())
|
| 523 |
+
rec.label = {'turn': esc.t, 'action': str(a.get('action', ''))}
|
| 524 |
+
rec.transition(rec.current(), 'action_begin')
|
| 525 |
+
video_guard(esc, before)
|
| 526 |
+
if rec:
|
| 527 |
+
rec._world_revision228 += 1
|
| 528 |
+
rec._world_edit228 = True
|
| 529 |
+
rec._pair_confirmed228 = False
|
| 530 |
+
try:
|
| 531 |
+
r = act(esc, a)
|
| 532 |
+
finally:
|
| 533 |
+
if rec:
|
| 534 |
+
rec._world_edit228 = False
|
| 535 |
+
if rec:
|
| 536 |
+
|
| 537 |
+
def after():
|
| 538 |
+
snapshot = __import__('copy').deepcopy({'turn': esc.t, 'action': a, 'result': r})
|
| 539 |
+
feedback = ''.join(C._model_feedback(snapshot))
|
| 540 |
+
rec.display.finish(__import__('copy').deepcopy(r), feedback)
|
| 541 |
+
rec.inventory.reading = feedback if a.get('action') == 'read' and r.get('ok') else None
|
| 542 |
+
rec.transition(rec.current(), 'action_end')
|
| 543 |
+
action_pages, status_pages = rec.display.pages()
|
| 544 |
+
read_pages = rec.inventory.read_pages() if rec.inventory.reading else [None]
|
| 545 |
+
for page in range(max(len(action_pages), len(status_pages), len(read_pages))):
|
| 546 |
+
rec.display.page = page
|
| 547 |
+
rec.inventory.read_page = min(page, len(read_pages) - 1)
|
| 548 |
+
from video_pacing165 import seconds_for
|
| 549 |
+
page_text = read_pages[min(page, len(read_pages) - 1)] if rec.inventory.reading else feedback
|
| 550 |
+
rec.hold(seconds_for(str(a.get('action', '')), bool(r.get('ok')), page_text, rec.pacing), source='action_hold')
|
| 551 |
+
rec.inventory.reading = None
|
| 552 |
+
rec.settle()
|
| 553 |
+
video_guard(esc, after)
|
| 554 |
+
return r
|
| 555 |
+
|
| 556 |
+
def video_joint(esc, so, jn, opened):
|
| 557 |
+
return joint(esc, so, jn, opened)
|
| 558 |
+
|
| 559 |
+
def video_run(esc, *args, **kwargs):
|
| 560 |
+
error = None
|
| 561 |
+
esc._video163_run_active = True
|
| 562 |
+
try:
|
| 563 |
+
return run(esc, *args, **kwargs)
|
| 564 |
+
except BaseException as ex:
|
| 565 |
+
error = type(ex).__name__ + ': ' + str(ex)
|
| 566 |
+
raise
|
| 567 |
+
finally:
|
| 568 |
+
rec = getattr(esc, '_video163', None)
|
| 569 |
+
if rec:
|
| 570 |
+
video_guard(esc, rec.close, error)
|
| 571 |
+
esc._video163_run_active = False
|
| 572 |
+
import sys
|
| 573 |
+
stag = sys.modules.get('_escape_stagnation')
|
| 574 |
+
if stag is not None and (not getattr(stag, '_video164_feedback_wrapped', False)):
|
| 575 |
+
original_update = stag.update
|
| 576 |
+
|
| 577 |
+
def video_feedback_update(esc, record):
|
| 578 |
+
result = original_update(esc, record)
|
| 579 |
+
rec = getattr(esc, '_video163', None)
|
| 580 |
+
|
| 581 |
+
def render_recorded_feedback():
|
| 582 |
+
if rec and (not rec.closed) and (rec.display.action is not None) and (record.get('turn') == rec.label.get('turn')) and ('model_feedback' in record):
|
| 583 |
+
feedback = str(record['model_feedback'] or '')
|
| 584 |
+
if feedback != rec.display.feedback:
|
| 585 |
+
previous = rec.display.feedback
|
| 586 |
+
appended = bool(previous and feedback.startswith(previous))
|
| 587 |
+
shown = feedback[len(previous):].strip() if appended else feedback
|
| 588 |
+
try:
|
| 589 |
+
rec.display.finish(__import__('copy').deepcopy(record.get('result') or {}), shown)
|
| 590 |
+
action_pages, status_pages = rec.display.pages()
|
| 591 |
+
for page in range(max(len(action_pages), len(status_pages))):
|
| 592 |
+
rec.display.page = page
|
| 593 |
+
from video_pacing165 import seconds_for
|
| 594 |
+
page_text = ' '.join(status_pages[min(page, len(status_pages) - 1)]) if appended else feedback
|
| 595 |
+
kind = 'read' if appended else str((record.get('action') or {}).get('action', ''))
|
| 596 |
+
rec.hold(seconds_for(kind, True if appended else bool((record.get('result') or {}).get('ok')), page_text, rec.pacing), source='recorded_feedback_hold')
|
| 597 |
+
finally:
|
| 598 |
+
rec.display.finish(__import__('copy').deepcopy(record.get('result') or {}), feedback)
|
| 599 |
+
rec.display.page = 0
|
| 600 |
+
rec.settle()
|
| 601 |
+
video_guard(esc, render_recorded_feedback)
|
| 602 |
+
return result
|
| 603 |
+
stag.update = video_feedback_update
|
| 604 |
+
stag._video164_feedback_wrapped = True
|
| 605 |
+
E.Escape.setup = video_setup
|
| 606 |
+
E.Escape.run = video_run
|
| 607 |
+
E.Escape.set_joint = video_joint
|
| 608 |
+
C.act = video_act
|
| 609 |
+
E.Escape._video163_installed = True
|
| 610 |
+
return True
|