#5001 Mission Timeline Driven Sim App

#5001 Mission Timeline Driven Sim App

#5001 Using the following definitions: """#

SIMULATION.txt rows: title, description, environment_url, [assets_url], [resources_url], [mission_url], notes

#

ENVIRONMENT.txt rows: description, background_image_source, scale_X, scale_Y

#

ASSETS.csv columns: id, name, source, shape, pos_X, pos_Y, center, radius, length, width, color, heading, speed

#

RESOURCES.csv columns: id, name, units, quanity

#

MISSION.txt data:

SEQUENCE, id, description

EVENT, time_start, time_end, description

ASSET, asset_id, start_point, end_point, speed, description

#""", provide simulation data for a lunar surface operations mission  

Below is a complete, internally consistent dataset for a lunar south pole surface operations mission (Artemis Shackleton Ridge EVA-04), formatted strictly to match your five schema definitions.

Coordinate frames are aligned across ENVIRONMENT.txt, ASSETS.csv, and MISSION.txt in meters relative to a 1000m x 1000m local topocentric grid (0,0 at bottom-left, Lander positioned at 200, 200).

SIMULATION.txt

title: Artemis Shackleton Ridge EVA-04
description: Dual-astronaut and Lunar Terrain Vehicle (LTV) traverse from the HLS Lander to Shackleton Crater Rim Station Alpha for core sampling, seismometer deployment, and ISRU regolith collection.
environment_url: ./ENVIRONMENT.txt
assets_url: ./ASSETS.csv
resources_url: ./RESOURCES.csv
mission_url: ./MISSION.txt
notes: Coordinates in meters (topocentric local frame). Time in mission elapsed seconds (0 to 14400s / 4.0 hrs). Speed in m/s. Note: RESOURCES.csv intentionally retains the schema spelling 'quanity'.

ENVIRONMENT.txt

description: Lunar South Pole - Shackleton Crater Connecting Ridge (Low-angle solar illumination at 3.2 deg elevation, high-contrast PSR boundary along Y > 750)
background_image_source: ./maps/shackleton_ridge_dem_hillshade_1km.png
scale_X: 1000.0
scale_Y: 1000.0

ASSETS.csv

id,name,source,shape,pos_X,pos_Y,center,radius,length,width,color,heading,speed
AST-01,HLS Starship Lander,./models/hls_lander.glb,circle,200.0,200.0,"200.0,200.0",12.0,24.0,24.0,#E0E4E8,0.0,0.0
AST-02,Lunar Terrain Vehicle (LTV-1),./models/ltv_rover.glb,rectangle,225.0,210.0,"225.0,210.0",0.0,4.2,2.4,#F4A261,45.0,0.0
AST-03,Astronaut EV-1 (Commander),./models/axemu_suit_red.glb,circle,212.0,205.0,"212.0,205.0",0.6,1.2,1.2,#E63946,45.0,0.0
AST-04,Astronaut EV-2 (Mission Specialist),./models/axemu_suit_blue.glb,circle,214.0,202.0,"214.0,202.0",0.6,1.2,1.2,#457B9D,45.0,0.0
AST-05,Portable Solar Array (VSAT-1),./models/deployable_solar.glb,rectangle,185.0,230.0,"185.0,230.0",0.0,6.0,1.8,#1D3557,90.0,0.0
AST-06,Lunar Surface Seismometer (LSS-1),./models/seismometer_pkg.glb,rectangle,224.0,209.5,"224.0,209.5",0.0,0.8,0.8,#2A9D8F,0.0,0.0
AST-07,ISRU Regolith Sample Box,./models/sample_cache.glb,rectangle,223.5,210.5,"223.5,210.5",0.0,0.9,0.6,#E9C46A,0.0,0.0
AST-08,PSR Permanently Shadowed Zone,./overlays/psr_zone_alpha.png,polygon,780.0,850.0,"780.0,850.0",85.0,170.0,140.0,#2B2D42,0.0,0.0

RESOURCES.csv

id,name,units,quantity
RES-01,EV-1 AxEMU Oxygen (Primary + Secondary),kg,1.45
RES-02,EV-2 AxEMU Oxygen (Primary + Secondary),kg,1.45
RES-03,EV-1 PLSS Sublimator Feedwater,kg,4.80
RES-04,EV-2 PLSS Sublimator Feedwater,kg,4.80
RES-05,EV-1 Suit Battery Charge,kWh,1.80
RES-06,EV-2 Suit Battery Charge,kWh,1.80
RES-07,LTV-1 Main Traction Battery,kWh,18.50
RES-08,Core Drill Sample Tubes (Sealed),count,6
RES-09,Regolith Scoop Canisters,count,4
RES-10,Kapton Thermal Insulation Blankets,count,2

MISSION.txt

SEQUENCE, SEQ-01, Egress, Pre-Traverse Checkouts, and Payload Loading
  EVENT, 0, 900, Crew egresses HLS airlock and translates to LTV-1 parking pad
    ASSET, AST-03, "212.0,205.0", "223.0,211.0", 0.8, EV-1 walks from HLS base to LTV-1 driver station
    ASSET, AST-04, "214.0,202.0", "226.0,208.0", 0.8, EV-2 walks from HLS base to LTV-1 payload rack
  EVENT, 900, 1800, LTV-1 avionics wake-up and payload verification
    ASSET, AST-02, "225.0,210.0", "225.0,210.0", 0.0, LTV-1 runs wheel steering, comms, and LiDAR self-test
    ASSET, AST-06, "224.0,209.5", "224.0,209.5", 0.0, Seismometer LSS-1 confirmed locked in rear cargo bay
    ASSET, AST-07, "223.5,210.5", "223.5,210.5", 0.0, ISRU sample box confirmed latched on LTV-1 deck

SEQUENCE, SEQ-02, Outbound Traverse to Shackleton Rim Station Alpha
  EVENT, 1800, 3600, Leg 1 traverse across sunlit regolith plain to Waypoint WP-1 (Boulder Field)
    ASSET, AST-02, "225.0,210.0", "510.0,495.0", 2.2, LTV-1 drives northeast along ridge crest avoiding crater ejecta
    ASSET, AST-03, "223.0,211.0", "508.0,496.0", 2.2, EV-1 seated in LTV-1 port seat
    ASSET, AST-04, "226.0,208.0", "511.0,493.0", 2.2, EV-2 seated in LTV-1 starboard seat
    ASSET, AST-06, "224.0,209.5", "509.0,494.5", 2.2, LSS-1 carried aboard LTV-1
    ASSET, AST-07, "223.5,210.5", "508.5,495.5", 2.2, Sample cache carried aboard LTV-1
  EVENT, 3600, 5100, Leg 2 traverse from Waypoint WP-1 to Station Alpha near PSR boundary
    ASSET, AST-02, "510.0,495.0", "740.0,765.0", 1.8, LTV-1 approaches Station Alpha at reduced speed near shadow line
    ASSET, AST-03, "508.0,496.0", "738.0,766.0", 1.8, EV-1 monitors LiDAR hazard map along PSR margin
    ASSET, AST-04, "511.0,493.0", "741.0,763.0", 1.8, EV-2 logs visual geology waypoints
    ASSET, AST-06, "509.0,494.5", "739.0,764.5", 1.8, LSS-1 carried aboard LTV-1
    ASSET, AST-07, "508.5,495.5", "738.5,765.5", 1.8, Sample cache carried aboard LTV-1

SEQUENCE, SEQ-03, Station Alpha Science Operations & PSR Edge Sampling
  EVENT, 5100, 7200, Seismometer offloading and leveling at Station Alpha
    ASSET, AST-03, "738.0,766.0", "755.0,780.0", 0.6, EV-1 unloads LSS-1 and carries it to bedrock outcrop
    ASSET, AST-06, "739.0,764.5", "755.0,780.0", 0.6, LSS-1 deployed and leveled on regolith anchor plate
    ASSET, AST-04, "741.0,763.0", "756.0,778.0", 0.5, EV-2 connects seismic data transceiver and verifies telemetry
  EVENT, 7200, 9600, PSR boundary core drilling and volatile-bearing regolith collection
    ASSET, AST-04, "756.0,778.0", "768.0,812.0", 0.5, EV-2 enters shallow PSR margin (AST-08) with rover floodlights
    ASSET, AST-03, "755.0,780.0", "762.0,795.0", 0.5, EV-1 maintains visual safety tether watch from sunlit rim
    ASSET, AST-07, "738.5,765.5", "765.0,805.0", 0.5, Sample cache moved to edge of PSR for cold-chain sealing
  EVENT, 9600, 10500, Stowage of sealed sample cache back onto LTV-1
    ASSET, AST-07, "765.0,805.0", "738.5,765.5", 0.6, Sealed sample cache loaded into LTV-1 thermal bay
    ASSET, AST-03, "762.0,795.0", "738.0,766.0", 0.7, EV-1 boards LTV-1 and verifies cargo lock
    ASSET, AST-04, "768.0,812.0", "741.0,763.0", 0.7, EV-2 boards LTV-1 and completes dust brush-off

SEQUENCE, SEQ-04, Return Traverse and HLS Lander Post-EVA Closeout
  EVENT, 10500, 13200, Direct return traverse from Station Alpha to HLS Landing Pad
    ASSET, AST-02, "740.0,765.0", "225.0,210.0", 2.5, LTV-1 returns along cleared outbound wheel tracks
    ASSET, AST-03, "738.0,766.0", "223.0,211.0", 2.5, EV-1 pilots return leg
    ASSET, AST-04, "741.0,763.0", "226.0,208.0", 2.5, EV-2 monitors PLSS consumables and sample bay temps
    ASSET, AST-07, "738.5,765.5", "223.5,210.5", 2.5, Sealed sample cache transported back to base
  EVENT, 13200, 14400, Sample transfer, LTV umbilical hookup, and crew ingress
    ASSET, AST-02, "225.0,210.0", "195.0,225.0", 0.5, LTV-1 repositions adjacent to Portable Solar Array VSAT-1 for charging
    ASSET, AST-04, "226.0,208.0", "210.0,203.0", 0.7, EV-2 carries ISRU sample box to HLS sample airlock lift
    ASSET, AST-07, "223.5,210.5", "210.0,203.0", 0.7, Sample cache transferred into HLS cold stowage
    ASSET, AST-03, "223.0,211.0", "208.0,204.0", 0.7, EV-1 connects LTV charging umbilical and enters HLS airlock


Write a Python validator and parser that loads SIMULATION.txt, ENVIRONMENT.txt, ASSETS.csv, RESOURCES.csv, and MISSION.txt, checks coordinate bounds and asset ID references, and interpolates asset positions at any timestamp.

Below is a complete, zero-dependency Python 3.10+ module (lunar_sim_parser.py) that parses all five files, enforces referential integrity, validates spatial bounds and physical travel speeds, and interpolates asset positions and headings at any mission elapsed timestamp.

lunar_sim_parser.py

from __future__ import annotations

import csv
import math
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple


class SimulationValidationError(Exception):
    """Raised when structural, referential, or physical validation fails."""


@dataclass
class SimulationManifest:
    title: str
    description: str
    environment_url: str
    assets_url: Optional[str] = None
    resources_url: Optional[str] = None
    mission_url: Optional[str] = None
    notes: str = ""


@dataclass
class Environment:
    description: str
    background_image_source: str
    scale_X: float
    scale_Y: float


@dataclass
class Asset:
    id: str
    name: str
    source: str
    shape: str
    pos_X: float
    pos_Y: float
    center: Tuple[float, float]
    radius: float
    length: float
    width: float
    color: str
    heading: float
    speed: float


@dataclass
class Resource:
    id: str
    name: str
    units: str
    quanity: float  # Matches schema spelling


@dataclass
class AssetAction:
    asset_id: str
    start_point: Tuple[float, float]
    end_point: Tuple[float, float]
    speed: float
    description: str


@dataclass
class MissionEvent:
    time_start: float
    time_end: float
    description: str
    assets: List[AssetAction] = field(default_factory=list)


@dataclass
class MissionSequence:
    id: str
    description: str
    events: List[MissionEvent] = field(default_factory=list)


@dataclass
class AssetState:
    asset_id: str
    name: str
    x: float
    y: float
    heading: float
    speed: float
    active_sequence: Optional[str]
    active_task: str


@dataclass
class SimulationPackage:
    manifest: SimulationManifest
    environment: Environment
    assets: Dict[str, Asset]
    resources: Dict[str, Resource]
    sequences: List[MissionSequence]

    @property
    def max_time(self) -> float:
        return max(
            (ev.time_end for seq in self.sequences for ev in seq.events),
            default=0.0,
        )

    def get_state_at(self, t: float) -> Dict[str, AssetState]:
        """
        Returns interpolated (x, y, heading, speed, active_task) for every asset
        at timestamp `t` (in mission elapsed seconds).
        """
        states: Dict[str, AssetState] = {}

        for asset_id, asset in self.assets.items():
            # Default to initial state from ASSETS.csv
            curr_x, curr_y = asset.pos_X, asset.pos_Y
            curr_heading = asset.heading
            curr_speed = 0.0
            active_seq = None
            active_task = "Idle at initial deployment"

            # Walk chronologically through sequences and events
            for seq in self.sequences:
                for ev in seq.events:
                    action = next(
                        (a for a in ev.assets if a.asset_id == asset_id), None
                    )
                    if action is None:
                        continue

                    if t < ev.time_start:
                        # Future event; stop scanning if earlier events already placed asset
                        continue

                    dx = action.end_point[0] - action.start_point[0]
                    dy = action.end_point[1] - action.start_point[1]
                    dist = math.hypot(dx, dy)

                    if dist > 1e-6:
                        # Convert math atan2 (0=East, CCW) to compass heading (0=North, CW)
                        curr_heading = (math.degrees(math.atan2(dx, dy)) + 360.0) % 360.0

                    if ev.time_start <= t <= ev.time_end:
                        duration = ev.time_end - ev.time_start
                        alpha = (t - ev.time_start) / duration if duration > 0 else 1.0
                        curr_x = action.start_point[0] + alpha * dx
                        curr_y = action.start_point[1] + alpha * dy
                        curr_speed = action.speed if dist > 1e-6 else 0.0
                        active_seq = seq.id
                        active_task = action.description
                    elif t > ev.time_end:
                        # Event completed; asset holds at end_point until next event
                        curr_x, curr_y = action.end_point
                        curr_speed = 0.0
                        active_seq = None
                        active_task = f"Completed: {action.description}"

            states[asset_id] = AssetState(
                asset_id=asset_id,
                name=asset.name,
                x=round(curr_x, 3),
                y=round(curr_y, 3),
                heading=round(curr_heading, 2),
                speed=round(curr_speed, 3),
                active_sequence=active_seq,
                active_task=active_task,
            )

        return states


# ---------------------------------------------------------------------------
# Parsing Helpers
# ---------------------------------------------------------------------------

def _parse_kv_file(path: Path) -> Dict[str, str]:
    if not path.exists():
        raise SimulationValidationError(f"Missing required file: {path}")
    data: Dict[str, str] = {}
    for line_no, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if ":" not in line:
            raise SimulationValidationError(
                f"{path.name}:{line_no} invalid key-value format: {raw_line!r}"
            )
        key, val = line.split(":", 1)
        data[key.strip()] = val.strip()
    return data


def _parse_coord_pair(raw: str, context: str) -> Tuple[float, float]:
    cleaned = raw.strip().strip('"').strip("'")
    parts = [p.strip() for p in cleaned.split(",")]
    if len(parts) != 2:
        raise SimulationValidationError(
            f"{context}: expected 'X,Y' coordinate pair, got {raw!r}"
        )
    try:
        return float(parts[0]), float(parts[1])
    except ValueError as exc:
        raise SimulationValidationError(
            f"{context}: non-numeric coordinate in {raw!r}"
        ) from exc


def _split_csv_line(line: str) -> List[str]:
    """Splits a single MISSION.txt line respecting quoted 'X,Y' pairs."""
    return next(csv.reader([line], skipinitialspace=True))


# ---------------------------------------------------------------------------
# File Loaders
# ---------------------------------------------------------------------------

def load_simulation_manifest(sim_path: Path) -> SimulationManifest:
    kv = _parse_kv_file(sim_path)
    required = ["title", "description", "environment_url"]
    for req in required:
        if req not in kv:
            raise SimulationValidationError(f"SIMULATION.txt missing required row: '{req}'")
    return SimulationManifest(
        title=kv["title"],
        description=kv["description"],
        environment_url=kv["environment_url"],
        assets_url=kv.get("assets_url"),
        resources_url=kv.get("resources_url"),
        mission_url=kv.get("mission_url"),
        notes=kv.get("notes", ""),
    )


def load_environment(env_path: Path) -> Environment:
    kv = _parse_kv_file(env_path)
    required = ["description", "background_image_source", "scale_X", "scale_Y"]
    for req in required:
        if req not in kv:
            raise SimulationValidationError(f"ENVIRONMENT.txt missing required row: '{req}'")
    try:
        scale_x = float(kv["scale_X"])
        scale_y = float(kv["scale_Y"])
    except ValueError as exc:
        raise SimulationValidationError("ENVIRONMENT.txt scale_X and scale_Y must be floats") from exc

    if scale_x <= 0 or scale_y <= 0:
        raise SimulationValidationError("ENVIRONMENT.txt scale_X and scale_Y must be > 0")

    return Environment(
        description=kv["description"],
        background_image_source=kv["background_image_source"],
        scale_X=scale_x,
        scale_Y=scale_y,
    )


def load_assets(assets_path: Path) -> Dict[str, Asset]:
    if not assets_path.exists():
        raise SimulationValidationError(f"Missing ASSETS file: {assets_path}")

    expected_cols = [
        "id", "name", "source", "shape", "pos_X", "pos_Y",
        "center", "radius", "length", "width", "color", "heading", "speed"
    ]
    assets: Dict[str, Asset] = {}

    with assets_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != expected_cols:
            raise SimulationValidationError(
                f"ASSETS.csv header mismatch.\nExpected: {expected_cols}\nGot:      {reader.fieldnames}"
            )
        for row_num, row in enumerate(reader, 2):
            aid = row["id"].strip()
            if aid in assets:
                raise SimulationValidationError(f"ASSETS.csv:{row_num} duplicate asset id '{aid}'")
            try:
                assets[aid] = Asset(
                    id=aid,
                    name=row["name"].strip(),
                    source=row["source"].strip(),
                    shape=row["shape"].strip(),
                    pos_X=float(row["pos_X"]),
                    pos_Y=float(row["pos_Y"]),
                    center=_parse_coord_pair(row["center"], f"ASSETS.csv:{row_num} center"),
                    radius=float(row["radius"]),
                    length=float(row["length"]),
                    width=float(row["width"]),
                    color=row["color"].strip(),
                    heading=float(row["heading"]),
                    speed=float(row["speed"]),
                )
            except ValueError as exc:
                raise SimulationValidationError(
                    f"ASSETS.csv:{row_num} numeric parse error on asset '{aid}'"
                ) from exc

    return assets


def load_resources(res_path: Path) -> Dict[str, Resource]:
    if not res_path.exists():
        raise SimulationValidationError(f"Missing RESOURCES file: {res_path}")

    expected_cols = ["id", "name", "units", "quanity"]
    resources: Dict[str, Resource] = {}

    with res_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != expected_cols:
            raise SimulationValidationError(
                f"RESOURCES.csv header mismatch.\nExpected: {expected_cols}\nGot:      {reader.fieldnames}"
            )
        for row_num, row in enumerate(reader, 2):
            rid = row["id"].strip()
            if rid in resources:
                raise SimulationValidationError(f"RESOURCES.csv:{row_num} duplicate resource id '{rid}'")
            try:
                qty = float(row["quanity"])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"RESOURCES.csv:{row_num} invalid numeric quanity for '{rid}'"
                ) from exc
            resources[rid] = Resource(
                id=rid,
                name=row["name"].strip(),
                units=row["units"].strip(),
                quanity=qty,
            )

    return resources


def load_mission(mission_path: Path) -> List[MissionSequence]:
    if not mission_path.exists():
        raise SimulationValidationError(f"Missing MISSION file: {mission_path}")

    sequences: List[MissionSequence] = []
    current_seq: Optional[MissionSequence] = None
    current_event: Optional[MissionEvent] = None

    for line_no, raw_line in enumerate(mission_path.read_text(encoding="utf-8").splitlines(), 1):
        stripped = raw_line.strip()
        if not stripped or stripped.startswith("#"):
            continue

        tokens = _split_csv_line(stripped)
        tag = tokens[0].upper()

        if tag == "SEQUENCE":
            if len(tokens) < 3:
                raise SimulationValidationError(f"MISSION.txt:{line_no} SEQUENCE requires id, description")
            current_seq = MissionSequence(id=tokens[1], description=",".join(tokens[2:]).strip())
            sequences.append(current_seq)
            current_event = None

        elif tag == "EVENT":
            if current_seq is None:
                raise SimulationValidationError(f"MISSION.txt:{line_no} EVENT declared outside a SEQUENCE")
            if len(tokens) < 4:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT requires time_start, time_end, description"
                )
            try:
                t_start = float(tokens[1])
                t_end = float(tokens[2])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT timestamps must be numeric"
                ) from exc
            if t_end < t_start:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT time_end ({t_end}) < time_start ({t_start})"
                )
            current_event = MissionEvent(
                time_start=t_start,
                time_end=t_end,
                description=",".join(tokens[3:]).strip(),
            )
            current_seq.events.append(current_event)

        elif tag == "ASSET":
            if current_event is None:
                raise SimulationValidationError(f"MISSION.txt:{line_no} ASSET declared outside an EVENT")
            if len(tokens) < 6:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} ASSET requires asset_id, start_point, end_point, speed, description"
                )
            start_pt = _parse_coord_pair(tokens[2], f"MISSION.txt:{line_no} start_point")
            end_pt = _parse_coord_pair(tokens[3], f"MISSION.txt:{line_no} end_point")
            try:
                spd = float(tokens[4])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} ASSET speed must be numeric"
                ) from exc

            current_event.assets.append(
                AssetAction(
                    asset_id=tokens[1],
                    start_point=start_pt,
                    end_point=end_pt,
                    speed=spd,
                    description=",".join(tokens[5:]).strip(),
                )
            )
        else:
            raise SimulationValidationError(f"MISSION.txt:{line_no} unknown record type: {tag!r}")

    return sequences


# ---------------------------------------------------------------------------
# Cross-File Validator & Loader Entrypoint
# ---------------------------------------------------------------------------

def load_and_validate_simulation(sim_file: str | Path) -> Tuple[SimulationPackage, List[str]]:
    """
    Loads all referenced simulation files relative to `sim_file`, runs hard
    integrity checks (raising SimulationValidationError on failure), and returns
    (SimulationPackage, warnings_list).
    """
    sim_path = Path(sim_file).resolve()
    base_dir = sim_path.parent
    warnings: List[str] = []

    manifest = load_simulation_manifest(sim_path)
    env = load_environment((base_dir / manifest.environment_url).resolve())

    assets: Dict[str, Asset] = {}
    if manifest.assets_url:
        assets = load_assets((base_dir / manifest.assets_url).resolve())

    resources: Dict[str, Resource] = {}
    if manifest.resources_url:
        resources = load_resources((base_dir / manifest.resources_url).resolve())

    sequences: List[MissionSequence] = []
    if manifest.mission_url:
        sequences = load_mission((base_dir / manifest.mission_url).resolve())

    def check_bounds(x: float, y: float, label: str) -> None:
        if not (0.0 <= x <= env.scale_X and 0.0 <= y <= env.scale_Y):
            raise SimulationValidationError(
                f"Out-of-bounds coordinate in {label}: ({x}, {y}) outside "
                f"[0..{env.scale_X}, 0..{env.scale_Y}]"
            )

    # 1. Validate initial asset bounds & center consistency
    for aid, asset in assets.items():
        check_bounds(asset.pos_X, asset.pos_Y, f"ASSETS.csv ({aid} pos_X/pos_Y)")
        check_bounds(asset.center[0], asset.center[1], f"ASSETS.csv ({aid} center)")

    # 2. Validate mission references, coordinate bounds, continuity, and speed
    last_known_pos: Dict[str, Tuple[float, float]] = {
        aid: (a.pos_X, a.pos_Y) for aid, a in assets.items()
    }
    last_end_time: Dict[str, float] = {aid: 0.0 for aid in assets}

    for seq in sequences:
        for ev in seq.events:
            duration = ev.time_end - ev.time_start
            seen_in_event = set()

            for act in ev.assets:
                if act.asset_id not in assets:
                    raise SimulationValidationError(
                        f"{seq.id} [{ev.time_start}-{ev.time_end}s]: unknown asset_id '{act.asset_id}'"
                    )
                if act.asset_id in seen_in_event:
                    raise SimulationValidationError(
                        f"{seq.id} [{ev.time_start}-{ev.time_end}s]: duplicate asset '{act.asset_id}' in same event"
                    )
                seen_in_event.add(act.asset_id)

                # Temporal overlap check per asset
                if ev.time_start < last_end_time[act.asset_id]:
                    raise SimulationValidationError(
                        f"{seq.id}: overlapping timeline for '{act.asset_id}' at t={ev.time_start}s"
                    )

                # Coordinate bounds check
                check_bounds(act.start_point[0], act.start_point[1], f"{seq.id} {act.asset_id} start_point")
                check_bounds(act.end_point[0], act.end_point[1], f"{seq.id} {act.asset_id} end_point")

                # Spatial continuity warning (teleportation check)
                prev_x, prev_y = last_known_pos[act.asset_id]
                gap = math.hypot(act.start_point[0] - prev_x, act.start_point[1] - prev_y)
                if gap > 0.01:
                    warnings.append(
                        f"[Continuity] {seq.id} ({ev.time_start}s): {act.asset_id} starts at "
                        f"{act.start_point}, {gap:.2f}m away from prior position ({prev_x}, {prev_y})."
                    )

                # Kinematic speed consistency check
                dist = math.hypot(
                    act.end_point[0] - act.start_point[0],
                    act.end_point[1] - act.start_point[1],
                )
                if duration > 0 and dist > 0:
                    implied_speed = dist / duration
                    if act.speed > 0 and implied_speed > act.speed * 1.05:
                        warnings.append(
                            f"[Kinematics] {seq.id} ({ev.time_start}-{ev.time_end}s): {act.asset_id} "
                            f"travels {dist:.1f}m in {duration:.0f}s ({implied_speed:.2f} m/s), "
                            f"exceeding declared speed {act.speed:.2f} m/s."
                        )

                last_known_pos[act.asset_id] = act.end_point
                last_end_time[act.asset_id] = ev.time_end

    pkg = SimulationPackage(
        manifest=manifest,
        environment=env,
        assets=assets,
        resources=resources,
        sequences=sequences,
    )
    return pkg, warnings


# ---------------------------------------------------------------------------
# CLI Usage & Interpolation Demo
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    package, warn_list = load_and_validate_simulation("SIMULATION.txt")

    print(f"Loaded: {package.manifest.title}")
    print(f"Bounds: {package.environment.scale_X}m x {package.environment.scale_Y}m")
    print(f"Assets: {len(package.assets)} | Resources: {len(package.resources)} | Duration: {package.max_time:.0f}s")

    if warn_list:
        print("\nWarnings:")
        for w in warn_list:
            print(f"  - {w}")

    # Query interpolated state mid-traverse (t = 2700s) and during PSR sampling (t = 8400s)
    for query_t in (2700.0, 8400.0):
        print(f"\n--- Telemetry Snapshot at T+{query_t:.0f}s ---")
        snapshot = package.get_state_at(query_t)
        for aid in ("AST-02", "AST-03", "AST-04", "AST-07"):
            st = snapshot[aid]
            print(
                f"  {st.asset_id} ({st.name:<30}) | "
                f"Pos: ({st.x:6.1f}, {st.y:6.1f}) | "
                f"Hdg: {st.heading:5.1f}° | Spd: {st.speed:4.2f} m/s | {st.active_task}"
            )

What This Enforces & Computes

  1. Strict Schema Enforcement:

    • Verifies required rows in SIMULATION.txt and ENVIRONMENT.txt, exact CSV headers in ASSETS.csv and RESOURCES.csv (including the quanity column spelling), and valid SEQUENCE --> EVENT --> ASSET hierarchy in MISSION.txt.

  2. Spatial, Referential, and Temporal Validation:

    • Confirms every asset_id in MISSION.txt exists in ASSETS.csv, prevents overlapping events for the same asset, and ensures all initial, start, and end coordinates lie within [0..scale_X, 0..scale_Y].

    • Emits non-fatal warnings if an asset teleports between consecutive events or if segment distance/duration exceeds the declared speed.

  3. Continuous State Interpolation (get_state_at(t)):

    • Linearly interpolates (x, y) coordinates during active EVENT windows, holds completed positions during idle gaps between events, and computes compass heading (0° = North+Y, 90° = East+X).


Add a JSON snapshot exporter to lunar_sim_parser.py that samples the mission at fixed time steps (e.g., every 10 seconds) and outputs a single playback JSON file for an HTML5 Canvas viewer.

Below is the updated lunar_sim_parser.py with a to_playback_dict() method and export_playback_json() function added.

The exported JSON bundles the static map bounds, asset rendering metadata (shapes, dimensions, colors), initial resources, sequence markers for timeline scrubbing, and pre-sampled frame telemetry (t, x, y, heading, speed, seq, task) so an HTML5 Canvas viewer can play back or scrub the entire 4-hour EVA directly from a single file.

lunar_sim_parser.py

from __future__ import annotations

import csv
import json
import math
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple


class SimulationValidationError(Exception):
    """Raised when structural, referential, or physical validation fails."""


@dataclass
class SimulationManifest:
    title: str
    description: str
    environment_url: str
    assets_url: Optional[str] = None
    resources_url: Optional[str] = None
    mission_url: Optional[str] = None
    notes: str = ""


@dataclass
class Environment:
    description: str
    background_image_source: str
    scale_X: float
    scale_Y: float


@dataclass
class Asset:
    id: str
    name: str
    source: str
    shape: str
    pos_X: float
    pos_Y: float
    center: Tuple[float, float]
    radius: float
    length: float
    width: float
    color: str
    heading: float
    speed: float


@dataclass
class Resource:
    id: str
    name: str
    units: str
    quanity: float  # Matches schema spelling


@dataclass
class AssetAction:
    asset_id: str
    start_point: Tuple[float, float]
    end_point: Tuple[float, float]
    speed: float
    description: str


@dataclass
class MissionEvent:
    time_start: float
    time_end: float
    description: str
    assets: List[AssetAction] = field(default_factory=list)


@dataclass
class MissionSequence:
    id: str
    description: str
    events: List[MissionEvent] = field(default_factory=list)


@dataclass
class AssetState:
    asset_id: str
    name: str
    x: float
    y: float
    heading: float
    speed: float
    active_sequence: Optional[str]
    active_task: str


@dataclass
class SimulationPackage:
    manifest: SimulationManifest
    environment: Environment
    assets: Dict[str, Asset]
    resources: Dict[str, Resource]
    sequences: List[MissionSequence]

    @property
    def max_time(self) -> float:
        return max(
            (ev.time_end for seq in self.sequences for ev in seq.events),
            default=0.0,
        )

    def get_state_at(self, t: float) -> Dict[str, AssetState]:
        """
        Returns interpolated (x, y, heading, speed, active_task) for every asset
        at timestamp `t` (in mission elapsed seconds).
        """
        states: Dict[str, AssetState] = {}

        for asset_id, asset in self.assets.items():
            curr_x, curr_y = asset.pos_X, asset.pos_Y
            curr_heading = asset.heading
            curr_speed = 0.0
            active_seq = None
            active_task = "Idle at initial deployment"

            for seq in self.sequences:
                for ev in seq.events:
                    action = next(
                        (a for a in ev.assets if a.asset_id == asset_id), None
                    )
                    if action is None or t < ev.time_start:
                        continue

                    dx = action.end_point[0] - action.start_point[0]
                    dy = action.end_point[1] - action.start_point[1]
                    dist = math.hypot(dx, dy)

                    if dist > 1e-6:
                        # Compass heading: 0 deg = North (+Y), 90 deg = East (+X)
                        curr_heading = (math.degrees(math.atan2(dx, dy)) + 360.0) % 360.0

                    if ev.time_start <= t <= ev.time_end:
                        duration = ev.time_end - ev.time_start
                        alpha = (t - ev.time_start) / duration if duration > 0 else 1.0
                        curr_x = action.start_point[0] + alpha * dx
                        curr_y = action.start_point[1] + alpha * dy
                        curr_speed = action.speed if dist > 1e-6 else 0.0
                        active_seq = seq.id
                        active_task = action.description
                    elif t > ev.time_end:
                        curr_x, curr_y = action.end_point
                        curr_speed = 0.0
                        active_seq = None
                        active_task = f"Completed: {action.description}"

            states[asset_id] = AssetState(
                asset_id=asset_id,
                name=asset.name,
                x=round(curr_x, 3),
                y=round(curr_y, 3),
                heading=round(curr_heading, 2),
                speed=round(curr_speed, 3),
                active_sequence=active_seq,
                active_task=active_task,
            )

        return states

    def to_playback_dict(self, dt: float = 10.0) -> Dict[str, Any]:
        """
        Samples the entire mission timeline at fixed `dt` second intervals
        and builds a self-contained dictionary ready for HTML5 Canvas playback.
        """
        if dt <= 0:
            raise ValueError("Sample interval dt must be greater than 0.")

        total_duration = self.max_time
        timestamps: List[float] = []
        t = 0.0
        while t < total_duration:
            timestamps.append(round(t, 3))
            t += dt
        if not timestamps or timestamps[-1] < total_duration:
            timestamps.append(round(total_duration, 3))

        # Sequence timeline markers for HUD scrubber chapters
        sequence_markers = []
        for seq in self.sequences:
            seq_start = min((ev.time_start for ev in seq.events), default=0.0)
            seq_end = max((ev.time_end for ev in seq.events), default=0.0)
            sequence_markers.append({
                "id": seq.id,
                "description": seq.description,
                "time_start": seq_start,
                "time_end": seq_end,
            })

        # Sampled telemetry frames
        frames: List[Dict[str, Any]] = []
        for sample_t in timestamps:
            snapshot = self.get_state_at(sample_t)
            active_events = [
                ev.description
                for seq in self.sequences
                for ev in seq.events
                if ev.time_start <= sample_t <= ev.time_end
            ]
            frames.append({
                "t": sample_t,
                "active_events": active_events,
                "assets": {
                    aid: {
                        "x": st.x,
                        "y": st.y,
                        "heading": st.heading,
                        "speed": st.speed,
                        "seq": st.active_sequence,
                        "task": st.active_task,
                    }
                    for aid, st in snapshot.items()
                },
            })

        return {
            "meta": {
                "title": self.manifest.title,
                "description": self.manifest.description,
                "notes": self.manifest.notes,
                "duration_sec": total_duration,
                "sample_dt_sec": dt,
                "frame_count": len(frames),
            },
            "environment": {
                "description": self.environment.description,
                "background_image_source": self.environment.background_image_source,
                "scale_X": self.environment.scale_X,
                "scale_Y": self.environment.scale_Y,
            },
            "assets": {
                aid: {
                    "id": a.id,
                    "name": a.name,
                    "source": a.source,
                    "shape": a.shape,
                    "radius": a.radius,
                    "length": a.length,
                    "width": a.width,
                    "color": a.color,
                    "initial_pos": [a.pos_X, a.pos_Y],
                    "initial_heading": a.heading,
                }
                for aid, a in self.assets.items()
            },
            "resources": [asdict(r) for r in self.resources.values()],
            "sequences": sequence_markers,
            "frames": frames,
        }

    def export_playback_json(
        self,
        output_path: str | Path,
        dt: float = 10.0,
        indent: Optional[int] = 2,
    ) -> Path:
        """
        Exports the sampled playback dataset to a JSON file.
        Use `indent=None` for compact production payloads.
        """
        out = Path(output_path).resolve()
        payload = self.to_playback_dict(dt=dt)
        out.write_text(json.dumps(payload, indent=indent), encoding="utf-8")
        return out


# ---------------------------------------------------------------------------
# Parsing Helpers
# ---------------------------------------------------------------------------

def _parse_kv_file(path: Path) -> Dict[str, str]:
    if not path.exists():
        raise SimulationValidationError(f"Missing required file: {path}")
    data: Dict[str, str] = {}
    for line_no, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if ":" not in line:
            raise SimulationValidationError(
                f"{path.name}:{line_no} invalid key-value format: {raw_line!r}"
            )
        key, val = line.split(":", 1)
        data[key.strip()] = val.strip()
    return data


def _parse_coord_pair(raw: str, context: str) -> Tuple[float, float]:
    cleaned = raw.strip().strip('"').strip("'")
    parts = [p.strip() for p in cleaned.split(",")]
    if len(parts) != 2:
        raise SimulationValidationError(
            f"{context}: expected 'X,Y' coordinate pair, got {raw!r}"
        )
    try:
        return float(parts[0]), float(parts[1])
    except ValueError as exc:
        raise SimulationValidationError(
            f"{context}: non-numeric coordinate in {raw!r}"
        ) from exc


def _split_csv_line(line: str) -> List[str]:
    return next(csv.reader([line], skipinitialspace=True))


# ---------------------------------------------------------------------------
# File Loaders
# ---------------------------------------------------------------------------

def load_simulation_manifest(sim_path: Path) -> SimulationManifest:
    kv = _parse_kv_file(sim_path)
    for req in ("title", "description", "environment_url"):
        if req not in kv:
            raise SimulationValidationError(f"SIMULATION.txt missing required row: '{req}'")
    return SimulationManifest(
        title=kv["title"],
        description=kv["description"],
        environment_url=kv["environment_url"],
        assets_url=kv.get("assets_url"),
        resources_url=kv.get("resources_url"),
        mission_url=kv.get("mission_url"),
        notes=kv.get("notes", ""),
    )


def load_environment(env_path: Path) -> Environment:
    kv = _parse_kv_file(env_path)
    for req in ("description", "background_image_source", "scale_X", "scale_Y"):
        if req not in kv:
            raise SimulationValidationError(f"ENVIRONMENT.txt missing required row: '{req}'")
    try:
        scale_x = float(kv["scale_X"])
        scale_y = float(kv["scale_Y"])
    except ValueError as exc:
        raise SimulationValidationError("ENVIRONMENT.txt scale_X and scale_Y must be floats") from exc

    if scale_x <= 0 or scale_y <= 0:
        raise SimulationValidationError("ENVIRONMENT.txt scale_X and scale_Y must be > 0")

    return Environment(
        description=kv["description"],
        background_image_source=kv["background_image_source"],
        scale_X=scale_x,
        scale_Y=scale_y,
    )


def load_assets(assets_path: Path) -> Dict[str, Asset]:
    if not assets_path.exists():
        raise SimulationValidationError(f"Missing ASSETS file: {assets_path}")

    expected_cols = [
        "id", "name", "source", "shape", "pos_X", "pos_Y",
        "center", "radius", "length", "width", "color", "heading", "speed"
    ]
    assets: Dict[str, Asset] = {}

    with assets_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != expected_cols:
            raise SimulationValidationError(
                f"ASSETS.csv header mismatch.\nExpected: {expected_cols}\nGot:      {reader.fieldnames}"
            )
        for row_num, row in enumerate(reader, 2):
            aid = row["id"].strip()
            if aid in assets:
                raise SimulationValidationError(f"ASSETS.csv:{row_num} duplicate asset id '{aid}'")
            try:
                assets[aid] = Asset(
                    id=aid,
                    name=row["name"].strip(),
                    source=row["source"].strip(),
                    shape=row["shape"].strip(),
                    pos_X=float(row["pos_X"]),
                    pos_Y=float(row["pos_Y"]),
                    center=_parse_coord_pair(row["center"], f"ASSETS.csv:{row_num} center"),
                    radius=float(row["radius"]),
                    length=float(row["length"]),
                    width=float(row["width"]),
                    color=row["color"].strip(),
                    heading=float(row["heading"]),
                    speed=float(row["speed"]),
                )
            except ValueError as exc:
                raise SimulationValidationError(
                    f"ASSETS.csv:{row_num} numeric parse error on asset '{aid}'"
                ) from exc

    return assets


def load_resources(res_path: Path) -> Dict[str, Resource]:
    if not res_path.exists():
        raise SimulationValidationError(f"Missing RESOURCES file: {res_path}")

    expected_cols = ["id", "name", "units", "quanity"]
    resources: Dict[str, Resource] = {}

    with res_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != expected_cols:
            raise SimulationValidationError(
                f"RESOURCES.csv header mismatch.\nExpected: {expected_cols}\nGot:      {reader.fieldnames}"
            )
        for row_num, row in enumerate(reader, 2):
            rid = row["id"].strip()
            if rid in resources:
                raise SimulationValidationError(f"RESOURCES.csv:{row_num} duplicate resource id '{rid}'")
            try:
                qty = float(row["quanity"])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"RESOURCES.csv:{row_num} invalid numeric quanity for '{rid}'"
                ) from exc
            resources[rid] = Resource(
                id=rid,
                name=row["name"].strip(),
                units=row["units"].strip(),
                quanity=qty,
            )

    return resources


def load_mission(mission_path: Path) -> List[MissionSequence]:
    if not mission_path.exists():
        raise SimulationValidationError(f"Missing MISSION file: {mission_path}")

    sequences: List[MissionSequence] = []
    current_seq: Optional[MissionSequence] = None
    current_event: Optional[MissionEvent] = None

    for line_no, raw_line in enumerate(mission_path.read_text(encoding="utf-8").splitlines(), 1):
        stripped = raw_line.strip()
        if not stripped or stripped.startswith("#"):
            continue

        tokens = _split_csv_line(stripped)
        tag = tokens[0].upper()

        if tag == "SEQUENCE":
            if len(tokens) < 3:
                raise SimulationValidationError(f"MISSION.txt:{line_no} SEQUENCE requires id, description")
            current_seq = MissionSequence(id=tokens[1], description=",".join(tokens[2:]).strip())
            sequences.append(current_seq)
            current_event = None

        elif tag == "EVENT":
            if current_seq is None:
                raise SimulationValidationError(f"MISSION.txt:{line_no} EVENT declared outside a SEQUENCE")
            if len(tokens) < 4:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT requires time_start, time_end, description"
                )
            try:
                t_start = float(tokens[1])
                t_end = float(tokens[2])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT timestamps must be numeric"
                ) from exc
            if t_end < t_start:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} EVENT time_end ({t_end}) < time_start ({t_start})"
                )
            current_event = MissionEvent(
                time_start=t_start,
                time_end=t_end,
                description=",".join(tokens[3:]).strip(),
            )
            current_seq.events.append(current_event)

        elif tag == "ASSET":
            if current_event is None:
                raise SimulationValidationError(f"MISSION.txt:{line_no} ASSET declared outside an EVENT")
            if len(tokens) < 6:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} ASSET requires asset_id, start_point, end_point, speed, description"
                )
            start_pt = _parse_coord_pair(tokens[2], f"MISSION.txt:{line_no} start_point")
            end_pt = _parse_coord_pair(tokens[3], f"MISSION.txt:{line_no} end_point")
            try:
                spd = float(tokens[4])
            except ValueError as exc:
                raise SimulationValidationError(
                    f"MISSION.txt:{line_no} ASSET speed must be numeric"
                ) from exc

            current_event.assets.append(
                AssetAction(
                    asset_id=tokens[1],
                    start_point=start_pt,
                    end_point=end_pt,
                    speed=spd,
                    description=",".join(tokens[5:]).strip(),
                )
            )
        else:
            raise SimulationValidationError(f"MISSION.txt:{line_no} unknown record type: {tag!r}")

    return sequences


# ---------------------------------------------------------------------------
# Cross-File Validator & Loader Entrypoint
# ---------------------------------------------------------------------------

def load_and_validate_simulation(sim_file: str | Path) -> Tuple[SimulationPackage, List[str]]:
    sim_path = Path(sim_file).resolve()
    base_dir = sim_path.parent
    warnings: List[str] = []

    manifest = load_simulation_manifest(sim_path)
    env = load_environment((base_dir / manifest.environment_url).resolve())

    assets: Dict[str, Asset] = {}
    if manifest.assets_url:
        assets = load_assets((base_dir / manifest.assets_url).resolve())

    resources: Dict[str, Resource] = {}
    if manifest.resources_url:
        resources = load_resources((base_dir / manifest.resources_url).resolve())

    sequences: List[MissionSequence] = []
    if manifest.mission_url:
        sequences = load_mission((base_dir / manifest.mission_url).resolve())

    def check_bounds(x: float, y: float, label: str) -> None:
        if not (0.0 <= x <= env.scale_X and 0.0 <= y <= env.scale_Y):
            raise SimulationValidationError(
                f"Out-of-bounds coordinate in {label}: ({x}, {y}) outside "
                f"[0..{env.scale_X}, 0..{env.scale_Y}]"
            )

    for aid, asset in assets.items():
        check_bounds(asset.pos_X, asset.pos_Y, f"ASSETS.csv ({aid} pos_X/pos_Y)")
        check_bounds(asset.center[0], asset.center[1], f"ASSETS.csv ({aid} center)")

    last_known_pos: Dict[str, Tuple[float, float]] = {
        aid: (a.pos_X, a.pos_Y) for aid, a in assets.items()
    }
    last_end_time: Dict[str, float] = {aid: 0.0 for aid in assets}

    for seq in sequences:
        for ev in seq.events:
            duration = ev.time_end - ev.time_start
            seen_in_event = set()

            for act in ev.assets:
                if act.asset_id not in assets:
                    raise SimulationValidationError(
                        f"{seq.id} [{ev.time_start}-{ev.time_end}s]: unknown asset_id '{act.asset_id}'"
                    )
                if act.asset_id in seen_in_event:
                    raise SimulationValidationError(
                        f"{seq.id} [{ev.time_start}-{ev.time_end}s]: duplicate asset '{act.asset_id}' in same event"
                    )
                seen_in_event.add(act.asset_id)

                if ev.time_start < last_end_time[act.asset_id]:
                    raise SimulationValidationError(
                        f"{seq.id}: overlapping timeline for '{act.asset_id}' at t={ev.time_start}s"
                    )

                check_bounds(act.start_point[0], act.start_point[1], f"{seq.id} {act.asset_id} start_point")
                check_bounds(act.end_point[0], act.end_point[1], f"{seq.id} {act.asset_id} end_point")

                prev_x, prev_y = last_known_pos[act.asset_id]
                gap = math.hypot(act.start_point[0] - prev_x, act.start_point[1] - prev_y)
                if gap > 0.01:
                    warnings.append(
                        f"[Continuity] {seq.id} ({ev.time_start}s): {act.asset_id} starts at "
                        f"{act.start_point}, {gap:.2f}m away from prior position ({prev_x}, {prev_y})."
                    )

                dist = math.hypot(
                    act.end_point[0] - act.start_point[0],
                    act.end_point[1] - act.start_point[1],
                )
                if duration > 0 and dist > 0:
                    implied_speed = dist / duration
                    if act.speed > 0 and implied_speed > act.speed * 1.05:
                        warnings.append(
                            f"[Kinematics] {seq.id} ({ev.time_start}-{ev.time_end}s): {act.asset_id} "
                            f"travels {dist:.1f}m in {duration:.0f}s ({implied_speed:.2f} m/s), "
                            f"exceeding declared speed {act.speed:.2f} m/s."
                        )

                last_known_pos[act.asset_id] = act.end_point
                last_end_time[act.asset_id] = ev.time_end

    pkg = SimulationPackage(
        manifest=manifest,
        environment=env,
        assets=assets,
        resources=resources,
        sequences=sequences,
    )
    return pkg, warnings


# ---------------------------------------------------------------------------
# CLI Usage
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Validate lunar simulation files and export playback JSON.")
    parser.add_argument("manifest", nargs="?", default="SIMULATION.txt", help="Path to SIMULATION.txt")
    parser.add_argument("-o", "--output", default="mission_playback.json", help="Output JSON file path")
    parser.add_argument("--dt", type=float, default=10.0, help="Sampling interval in seconds (default: 10.0)")
    parser.add_argument("--compact", action="store_true", help="Minify JSON output (no whitespace)")
    args = parser.parse_args()

    package, warn_list = load_and_validate_simulation(args.manifest)
    out_file = package.export_playback_json(
        args.output,
        dt=args.dt,
        indent=None if args.compact else 2,
    )

    print(f"Validated '{package.manifest.title}' ({len(package.assets)} assets, {package.max_time:.0f}s)")
    if warn_list:
        print(f"Warnings ({len(warn_list)}):")
        for w in warn_list:
            print(f"  - {w}")
    print(f"Exported playback JSON -> {out_file} (dt={args.dt}s)")

Output JSON Structure (mission_playback.json)

Running python lunar_sim_parser.py SIMULATION.txt --dt 10 -o mission_playback.json generates 1,441 frames (covering 0s to 14400s) structured for direct HTML5 Canvas rendering:

{
  "meta": {
    "title": "Artemis Shackleton Ridge EVA-04",
    "description": "Dual-astronaut and Lunar Terrain Vehicle (LTV) traverse...",
    "duration_sec": 14400.0,
    "sample_dt_sec": 10.0,
    "frame_count": 1441
  },
  "environment": {
    "description": "Lunar South Pole - Shackleton Crater Connecting Ridge...",
    "background_image_source": "./maps/shackleton_ridge_dem_hillshade_1km.png",
    "scale_X": 1000.0,
    "scale_Y": 1000.0
  },
  "assets": {
    "AST-02": {
      "id": "AST-02",
      "name": "Lunar Terrain Vehicle (LTV-1)",
      "shape": "rectangle",
      "radius": 0.0,
      "length": 4.2,
      "width": 2.4,
      "color": "#F4A261",
      "initial_pos": [225.0, 210.0],
      "initial_heading": 45.0
    }
  },
  "resources": [
    { "id": "RES-01", "name": "EV-1 AxEMU Oxygen (Primary + Secondary)", "units": "kg", "quanity": 1.45 }
  ],
  "sequences": [
    { "id": "SEQ-01", "description": "Egress, Pre-Traverse Checkouts, and Payload Loading", "time_start": 0.0, "time_end": 1800.0 }
  ],
  "frames": [
    {
      "t": 2700.0,
      "active_events": ["Leg 1 traverse across sunlit regolith plain to Waypoint WP-1 (Boulder Field)"],
      "assets": {
        "AST-02": {
          "x": 367.5,
          "y": 352.5,
          "heading": 45.0,
          "speed": 2.2,
          "seq": "SEQ-02",
          "task": "LTV-1 drives northeast along ridge crest avoiding crater ejecta"
        }
      }
    }
  ]
}

Canvas Coordinate Mapping Note

Because ENVIRONMENT.txt uses a standard bottom-left Cartesian origin ((0,0) at bottom-left, +Y pointing North/up) while HTML5 <canvas> puts (0,0) at top-left (+Y pointing down), map world meters (x, y) to canvas pixels (px, py) via:

const px = (asset.x / data.environment.scale_X) * canvas.width;
const py = canvas.height - (asset.y / data.environment.scale_Y) * canvas.height;


From <https://gemini.google.com/app/444467e456ddc267>  Google Gemini (4 Hydrogen)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#4188 Hybrid/GraphRAG