"""Mission identity, edit acknowledgement and ground-constrained viewport picking.""" import importlib.util import json from pathlib import Path import numpy as np import pytest from pydantic import ValidationError from test_ai_polygon_realtime import realtime as _realtime from test_ai_polygon_realtime import snapshot from k1link.simulation.ai_polygon.contracts import PlanningCommand, PlanSave, RunCreate realtime = _realtime def point(identity, x, y=0, z=0): return {"id": identity * 16, "position": [x, y, z]} def test_plan_requires_worker_ack_and_is_immutable(realtime): store, hello, row = realtime row["request"]["purpose"] = "planning" store._save(row) key = row["run_id"] with pytest.raises(RuntimeError, match="планирование"): store.control(key, "play") command = PlanningCommand(request_id="e" * 32, action="add") assert store.planning_command(key, command)["planning_sequence"] == 1 assert store.planning_command(key, command)["planning_sequence"] == 1 with pytest.raises(RuntimeError, match="подтверждения"): store.save_plan(key, PlanSave(name="Trail", sequence=1)) points = [point("a", 1, 2, 0.3), point("b", 1, 4, 0.5)] store.snapshot( key, hello.instance_id, snapshot( planning={ "sequence": 1, "view_revision": 0, "points": points, "can_undo": True, } ), ) plan = store.save_plan(key, PlanSave(name="Trail", sequence=1)) assert plan["settings"]["spawn_xy"] == [1, 2] assert plan["settings"]["route_xy"] == [[1, 4]] assert plan["settings"]["heading_degrees"] == 90 assert store.plans.get(plan["plan_id"]) == plan assert store.worlds.get(row["world"]["world_id"])["settings"] == row["world"]["settings"] store.control(key, "stop") with pytest.raises(RuntimeError, match="завершается"): store.save_plan(key, PlanSave(name="Trail", sequence=1)) altered = {**plan, "name": "tampered"} (store.plans.root / (plan["plan_id"] + ".json")).write_text(json.dumps(altered)) with pytest.raises(ValueError, match="повреждено"): store.plans.get(plan["plan_id"]) def test_plan_identity_and_no_edits_during_evaluation(realtime): store, _, row = realtime with pytest.raises(RuntimeError, match="планирования"): store.planning_command(row["run_id"], PlanningCommand(request_id="f" * 32, action="clear")) plan = store.plans.create(row, "Task", [point("a", 0), point("b", 1)], 0) row["state"] = "stopped" store._save(row) store.active = None store.queue.release_simulation(row["run_id"]) request = RunCreate( world_id=row["world"]["world_id"], clock="realtime", start_paused=True, plan_id=plan["plan_id"], ) updated = store.worlds.get(row["world"]["world_id"]) updated["sha256"] = "f" * 64 from k1link.simulation.ai_polygon.worlds import write_json write_json(store.worlds.directory(updated["world_id"]) / "world.json", updated) with pytest.raises(ValueError, match="не соответствует"): store.start(request, "wrong-scene-plan") def test_snapshot_route_is_bounded(): with pytest.raises(ValidationError): snapshot( planning={ "sequence": 0, "view_revision": 0, "can_undo": False, "points": [point("a", 0)] * 34, } ) with pytest.raises(ValidationError): snapshot( planning={ "sequence": 0, "view_revision": 0, "can_undo": False, "points": [point("a", float("nan"))], } ) class TerrainQuery: def raycast_all(self, origin, direction, distance, collect, bothSides): if direction[2] >= 0: return # Synthetic sloping ground z = 0.1 x. A foreign collider cannot be picked. t = (origin[2] - 0.1 * origin[0]) / (0.1 * direction[0] - direction[2]) p = np.asarray(origin) + t * np.asarray(direction) collect({"collision": "/World/Rover", "normal": [0, 0, 1], "position": [0, 0, 2]}) if 0 <= t <= distance: collect({"collision": "/World/Terrain", "normal": [-0.1, 0, 0.995], "position": p}) def test_projection_edit_axes_undo_and_stale_view(): source = Path(__file__).parents[1] / "simulation/ai-polygon/route_view.py" spec = importlib.util.spec_from_file_location("route_view_test", source) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) view = module.RouteView( { "request": {"purpose": "planning"}, "world": { "settings": { "spawn_xy": [0, 0], "ground_z": 0, "heading_degrees": 0, "route_xy": [[100, 100]], } }, }, TerrainQuery(), ) assert len(view.points) == 1 # No hidden legacy mission imported into a new plan. view.matrix[3, 2] = -10 p = module.project_point([2, 3, 0], view.matrix, view.focal, view.aperture) origin, direction = view.ray(*p) assert np.allclose(origin + direction * (-origin[2] / direction[2]), [2, 3, 0]) identity = view.points[0]["id"] command = PlanningCommand( request_id="a" * 32, action="move", point_id=identity, x=0.6, y=0.6, axis="x" ).model_dump() view.apply([{**command, "sequence": 1}]) moved = view.points[0]["position"] assert moved[0] > 1 and moved[1] == 0 and moved[2] == pytest.approx(0.1 * moved[0]) view.apply([{**command, "sequence": 2, "action": "undo"}]) assert view.points[0]["position"] == [0, 0, 0] view.apply([{**command, "sequence": 3, "view_revision": 99}]) assert "Обзор изменился" in view.error assert view.points[0]["position"] == [0, 0, 0] view.apply([{**command, "sequence": 4, "action": "zoom", "amount": 1000}]) assert np.linalg.norm(view.desired_eye - view.eye) == pytest.approx(3) # Free-look keeps position; flight follows gaze, Q/E follows world vertical. view.apply([{**command, "sequence": 5, "action": "home"}]) home = view.desired_eye.copy() view.apply([{**command, "sequence": 6, "action": "orbit", "x": 0.4, "y": -1}]) assert np.allclose(view.desired_eye, home) assert view.desired_angles[1] > 0 # Looking above the horizon is allowed. forward, right, up = view.camera_axes(view.desired_angles) assert abs(np.dot(forward, right)) < 1e-8 and np.linalg.norm(up) == pytest.approx(1) view.apply([{**command, "sequence": 7, "action": "fly", "x": 0, "y": 0.5, "amount": 0}]) assert np.allclose(view.desired_eye - home, forward * 0.5) flown = view.desired_eye.copy() view.apply([{**command, "sequence": 8, "action": "fly", "x": 0, "y": 0, "amount": -1}]) assert np.allclose(view.desired_eye - flown, [0, 0, -1]) assert view.camera_moving for _ in range(180): view.advance_camera(1 / 30) assert not view.camera_moving # No latched key or simulation time is needed to stop. assert view.points[0]["position"] == [0, 0, 0] view.apply([{**command, "sequence": 9, "action": "clip", "amount": 0, "enabled": True}]) assert view.clip_height == 0 # Zero/negative world heights are real clipping planes. view.apply([{**command, "sequence": 10, "action": "clip", "amount": -2, "enabled": True}]) assert view.clip_height == -2 view.apply([{**command, "sequence": 11, "action": "clip", "enabled": False}]) assert view.clip_height is None