#5051 Excel Workbook Simulator

#5051 Excel Workbook Simulator

Continued from

https://learningfromchatgpt.blogspot.com/2026/12/5047-dsl-simulation-timeline-definition.html

#5051 Describe how the simulator can be implemented in an Excel Workbook, with timeline(s) defined on separate worksheets

Implementing the SimLine simulator in an Excel workbook (.xlsm) maps cleanly onto a data-engine-view architecture: structured Excel Tables (ListObjects) replace the DSL blocks, each mission scenario lives on its own timeline worksheet, formulas compute deterministic state at any Mission Elapsed Time (MET), and a dashboard sheet renders the 2D map, telemetry gauges, and playback controls.

1. Workbook Architecture (Worksheet Layout)

Separate static world definitions from scenario timelines so you can swap or compare multiple mission plans (e.g., nominal vs. contingency EVA) without duplicating map data.

Worksheet NameRoleContents / Excel Tables
DashboardView & Controls2D Lunar Map, Play/Pause/Step buttons, Speed selector, Active Timeline dropdown, MET scrubber, Resource Gauges, Sparkline chart, Alert banner.
Scene_WorldWorld SetupScene dimensions (2048 × 2048), scale (0.5 m/px), background image path, tbl_Waypoints, tbl_Zones, tbl_CommWindows.
AssetsEntity Registrytbl_Assets (ID, Static flag, Sprite filename, Start Waypoint, Layer, Tags) and tbl_Resources (Asset ID, Resource Name, Initial, Min, Max, Unit).
TL_EVA1_NominalTimeline #1tbl_TL_EVA1_Nominal — full event schedule for the baseline 2-hour Shackleton Rim mission.
TL_EVA1_AbortTimeline #2tbl_TL_EVA1_Abort — alternate scenario (e.g., early rover battery fault and direct return) using the exact same column schema.
Sim_EngineHidden State CalcPulls the active timeline sheet, evaluates asset (X, Y), heading, parent coupling, resource levels, zone checks, and 120-point sparkline series at the current MET.

2. Defining Timelines on Separate Worksheets

Every timeline worksheet (TL_*) uses an identical Excel Table schema so the engine can switch scenarios dynamically from a single dropdown cell on Dashboard (e.g., Dashboard!B2 = "TL_EVA1_Nominal").

Timeline Table Columns

ColumnExample ValuePurpose
Event_IDoutbound_driveUnique block/event key for dependency references.
PhaseEVA-2: OutboundUsed for phase jump buttons and timeline filtering.
Trigger_ModeAFTER or ATDetermines whether Start_MET_Min is absolute or chained.
Ref_Event_IDboard_roverPrior Event_ID when Trigger_Mode = "AFTER".
Offset_Min0Delay after Ref_Event_ID completes.
Duration_Min30Event length in minutes.
Start_MET_Min(Formula)Resolves AT or XLOOKUP(Ref_Event_ID, ...) + Offset_Min.
End_MET_Min(Formula)=[@Start_MET_Min] + [@Duration_Min]
Target_Assetltv_roverData-validated dropdown bound to tbl_Assets[Asset_ID].
Event_Typemove / attach / detach / state / resource_deltaData-validated primitive type.
From_WP / To_WPlander_pad → shackleton_rimWaypoint dropdowns bound to tbl_Waypoints[WP_ID].
Via_Points520,1480; 740,1220; 1120,910Optional semicolon-delimited intermediate (x, y) coordinates.
Param_1battery / ltv_rover / downlinkingResource name, parent asset ID, or state string.
Param_2-0.8 / 2.0Signed rate_per_min or max_speed_mps.
Validation_Flag(Formula)Instant row-level check (OK, SPEED_ERR, COMM_ERR, STATIC_ERR).

Chaining after <id> with Native Formulas

In Start_MET_Min, use XLOOKUP so editing any upstream duration automatically ripples the entire mission schedule:

=IF([@Trigger_Mode]="AT", [@Offset_Min], XLOOKUP([@Ref_Event_ID], [Event_ID], [End_MET_Min], 0) + [@Offset_Min])

Multi-Timeline Switching

  • Formula-only approach: On Sim_Engine, copy the active timeline into a staging range via a single VBA Worksheet_Change handler when the Dashboard scenario dropdown changes (avoiding volatile INDIRECT recalculation overhead on large tables).

  • Scenario Comparison tab (optional): Because each timeline lives on its own sheet, a summary tab can display side-by-side KPIs (Final Rover Battery %, Min Crew O2 %, Total Distance, Constraint Errors) across all TL_* tabs simultaneously.

3. State Evaluation & Physics Engine (Sim_Engine)

A single master clock cell—Sim_Engine!B2 (Current_MET_Min, ranging from 0 to 120)—drives the entire workbook.

  1. Resource Integration (100% Formula-Driven):

    For each asset and resource, calculate the exact level at Current_MET_Min using SUMPRODUCT over the active timeline's resource_delta rows:

    =Initial_Val + SUMPRODUCT(
      (Active_Type="resource_delta") *
      (Active_Asset=Asset_ID) *
      (Active_Param1=Res_Name) *
      (Active_Param2) *
      MAX(0, MIN(Current_MET_Min, Active_End) - Active_Start)
    )
    

    Note: Wrap the MAX(0, ...) clamp with IF(Current_MET_Min > Active_Start, MIN(Current_MET_Min, Active_End) - Active_Start, 0) so it evaluates cleanly as an array formula.

  2. Position, Polyline Interpolation & Coupling:

    • Straight-line moves: Pure Excel formulas (XLOOKUP for the latest move event with Start_MET <= t, then linear/eased interpolation between From_WP and To_WP).

    • Multi-segment via polylines, heading angle, and point-in-polygon KOZ checks: Implement as clean VBA User-Defined Functions (UDFs)—SimSamplePolylineX(pathStr, frac), SimSamplePolylineY(pathStr, frac), SimHeadingDeg(pathStr, frac), and SimPointInPoly(x, y, polyStr).

    • Parent-Child Coupling (attach/detach): Find the most recent attach or detach row for each asset where Start_MET <= t. If the latest event is attach, the asset's (X, Y) formula simply references its parent asset's (X, Y) cells.

  3. Sparkline Data Table:

    Place a 121-row table (t = 0, 1, 2, ... 120 min) on Sim_Engine using the same resource integration formula. Bind a standard Excel Line Chart on Dashboard to this table, plus a vertical 2-point XY series at x = Current_MET_Min to render the moving MET playhead.

4. 2D Map Rendering & Playback Controls (Dashboard)

Excel supports two distinct rendering strategies depending on whether you prioritize zero-macro simplicity or rotated sprite graphics:

Approach A: XY Scatter Chart Map (Best for Scrubbing & Native Charts)

  • Insert a square XY Scatter Chart locked to X: [0, 2048] and Y: [0, 2048] (with Y-axis set to Values in reverse order so (0, 0) sits at the top-left, matching canvas coordinates).

  • Set the Plot Area Fill to your Shackleton Crater Rim PNG image.

  • Plot each visual layer as a chart series:

    • Zones: Closed XY polygon series with dashed borders.

    • Traverse Paths: Connected XY scatter lines (faint grey for planned, bright cyan for active).

    • Waypoints & Assets: Single-point XY series where each marker's Fill is set to your custom PNG icon (HLS Lander, Station 1, Astronaut, LTV Rover).

  • Limitation: Excel chart markers cannot rotate dynamically per frame; the rover icon stays upright.

Approach B: VBA Shapes on a Locked Map (Best for Rotated Sprites)

  • Place the Shackleton Crater Rim image as a locked background Shape on Dashboard (e.g., 600 × 600 pt).

  • Insert your transparent PNG sprites (ltv_rover, astronaut_1, hls_lander, etc.) as named Shape objects above it.

  • A lightweight VBA UpdateMapSprites() subroutine reads (X, Y, Heading, Parent) from Sim_Engine and updates each sprite:

    shp.Left = mapLeft + (worldX / 2048#) * mapWidth - (shp.Width / 2#)
    shp.Top  = mapTop  + (worldY / 2048#) * mapHeight - (shp.Height / 2#)
    shp.Rotation = headingDeg   ' Aligns LTV Rover nose to travel direction
    shp.Visible = IIf(parentId = "", msoTrue, msoFalse)
    

Playback Controls

  • Manual Scrubbing: Link a Form Control Scroll Bar (min 0, max 1200 for 0.1-min resolution) directly to Sim_Engine!B2. Dragging the bar updates the map, resource bars, alerts, and sparkline playhead in real time.

  • Play / Pause / Speed Loop: Use a VBA Do While isPlaying loop with Timer delta-clamping and DoEvents (allowing the Pause button to interrupt cleanly), stepping Current_MET_Min by dt * speedMultiplier and calling Calculate + UpdateMapSprites.

5. Constraint Validation & SimLine Round-Trip Export

  • Live Constraint Highlighting: Apply Conditional Formatting on Dashboard telemetry cards (red fill if Battery < 20% or Suit_O2 < 25%, amber if Comm = BLACKOUT during a downlink, red alert banner if SimPointInPoly returns TRUE for a hazard KOZ).

  • JSON / .simline Bridge: Add an Export Active Timeline to JSON button backed by a short VBA macro that serializes Scene_World, Assets, and the currently selected TL_* sheet into the exact SimLineTimeline JSON schema—letting you author and run quick trade studies in Excel, then drop the exported .json straight into simline_viewer.html or simline_validator.py.

Would you like me to generate a working .xlsx template workbook with the Scene_World, Assets, TL_EVA1_Nominal, TL_EVA1_Abort, Sim_Engine, and Dashboard sheets pre-wired with formulas and the XY Scatter map?


Yes

Your XLSX file is ready


What's Inside SimLine_Lunar_EVA_Simulator.xlsx

WorksheetPurposeKey Features
DashboardMission Control ViewScenario dropdown (C4), editable Current MET (min) scrubber (C5), live KPI cards (Phase, Comm Link, Active Events, Progress, Audit), Live Asset Telemetry table with conditional formatting, Nominal vs. Abort comparison table, 2D Operations XY Scatter Map, and Consumables Profile Line Chart.
Scene_WorldWorld Setup2048 × 2048 coordinate bounds, 0.5 m/px scale, 4 named waypoints, 3 environment zones (PSR shadow, lander KOZ, solar corridor), and the lunar_relay_pass_1 comm window (MET 55–80 min, 50 Mbps).
AssetsEntity & Resource RegistryStatic/dynamic asset table with INDEX/MATCH starting coordinates plus initial/min/max consumable specs for ltv_rover, astronaut_1, and astronaut_2.
TL_EVA1_NominalBaseline 2-Hour EVA31 events with chained AFTER formulas, data-validated dropdowns, and row-level Validation_Flag checks (static mutation, comm blackout downlinks, and speed limits).
TL_EVA1_AbortContingency Scenario18-event abort timeline triggered by a -2.8%/min rover battery fault on the Connecting Ridge, forcing a direct return to the HLS pad.
Sim_EngineFormula EngineNon-volatile scenario staging table, live position/coupling/resource evaluator at Current MET, map zone polygon coordinates, and a 61-point (0–120 min) telemetry curve table driving the dashboard chart.

Quick Tips for Using It in Excel

  • Scrub the Mission: Change cell Dashboard!C5 (default 60 min) to any value between 0 and 120 to watch the rover, crew, seismometer, resource levels, and comm window status update on the map and tables.

  • Compare Scenarios: Switch Dashboard!C4 between TL_EVA1_Nominal and TL_EVA1_Abort to immediately swap timelines and re-plot the consumables chart.

  • Add Your Lunar Background Image: Right-click the plot area of the 2D Operations Map chart on Dashboard → Format Plot Area → Fill → Picture or texture fill → select the Shackleton Crater Rim map image generated earlier.

  • Add a Visual Scrubber Bar (Optional): Go to Developer → Insert → Scroll Bar (Form Control), draw it next to C5, right-click → Format Control, set Minimum 0, Maximum 120, and Cell link to $C$5.

Would you like the companion VBA macro module to add a Play/Pause animation loop and an Export Active Timeline to SimLine JSON button?


Yes

Save SimLine_Lunar_EVA_Simulator.xlsx as an Excel Macro-Enabled Workbook (.xlsm), press Alt + F11 → Insert → Module, and paste the complete VBA module below. It is pre-wired to the exact sheets and cell ranges in your workbook and exports schema-valid JSON compatible with both simline_viewer.html and simline_validator.py.

Complete VBA Module (modSimLineStudio)

Option Explicit

' =============================================================================
' SimLine Studio — Playback Controller & SimLineTimeline JSON Exporter
' Wired to: Dashboard, Scene_World, Assets, TL_EVA1_Nominal, TL_EVA1_Abort
' =============================================================================

Private gIsPlaying As Boolean
Private gSpeedSimMinPerSec As Double  ' Simulation minutes advanced per real second

' -----------------------------------------------------------------------------
' 1. PLAYBACK CONTROLS (Assign these macros to Dashboard Form Control Buttons)
' -----------------------------------------------------------------------------

Public Sub Sim_TogglePlayPause()
    If gIsPlaying Then
        gIsPlaying = False
        Application.StatusBar = "SimLine: Paused"
        Exit Sub
    End If

    If gSpeedSimMinPerSec <= 0 Then gSpeedSimMinPerSec = 2# ' Default: 120x (2 min/sec)

    Dim wsDash As Worksheet
    Dim wsWorld As Worksheet
    Dim maxMet As Double
    Dim curMet As Double
    Dim lastTick As Double
    Dim nowTick As Double
    Dim dt As Double

    Set wsDash = ThisWorkbook.Worksheets("Dashboard")
    Set wsWorld = ThisWorkbook.Worksheets("Scene_World")
    maxMet = Val(wsWorld.Range("B11").Value)
    If maxMet <= 0 Then maxMet = 120#

    ' Restart from 0 if already at end of mission
    If Val(wsDash.Range("C5").Value) >= maxMet Then
        wsDash.Range("C5").Value = 0
    End If

    gIsPlaying = True
    lastTick = Timer
    Application.StatusBar = "SimLine: Playing (" & gSpeedSimMinPerSec & " sim-min/sec) — Click Play/Pause again to stop"

    Do While gIsPlaying
        nowTick = Timer
        dt = nowTick - lastTick
        If dt < 0 Then dt = dt + 86400# ' Handle midnight Timer rollover

        ' Throttle updates to ~15 FPS so Excel charts redraw smoothly
        If dt >= 0.065 Then
            lastTick = nowTick
            curMet = Val(wsDash.Range("C5").Value) + (dt * gSpeedSimMinPerSec)

            If curMet >= maxMet Then
                wsDash.Range("C5").Value = maxMet
                wsDash.Calculate
                gIsPlaying = False
                Application.StatusBar = "SimLine: Mission Complete (MET " & maxMet & " min)"
                Exit Do
            Else
                wsDash.Range("C5").Value = Round(curMet, 2)
                Application.Calculate
            End If
        End If

        DoEvents
    Loop
End Sub

Public Sub Sim_Reset()
    gIsPlaying = False
    ThisWorkbook.Worksheets("Dashboard").Range("C5").Value = 0
    Application.Calculate
    Application.StatusBar = "SimLine: Reset to MET 00:00:00"
End Sub

Public Sub Sim_StepForward()
    Dim wsDash As Worksheet
    Dim maxMet As Double
    gIsPlaying = False
    Set wsDash = ThisWorkbook.Worksheets("Dashboard")
    maxMet = Val(ThisWorkbook.Worksheets("Scene_World").Range("B11").Value)
    wsDash.Range("C5").Value = Application.WorksheetFunction.Min(maxMet, Val(wsDash.Range("C5").Value) + 2#)
    Application.Calculate
End Sub

Public Sub Sim_StepBack()
    Dim wsDash As Worksheet
    gIsPlaying = False
    Set wsDash = ThisWorkbook.Worksheets("Dashboard")
    wsDash.Range("C5").Value = Application.WorksheetFunction.Max(0, Val(wsDash.Range("C5").Value) - 2#)
    Application.Calculate
End Sub

Public Sub Sim_CycleSpeed()
    Select Case gSpeedSimMinPerSec
        Case 1#:  gSpeedSimMinPerSec = 2#   ' 120x
        Case 2#:  gSpeedSimMinPerSec = 5#   ' 300x
        Case 5#:  gSpeedSimMinPerSec = 0.5  ' 30x
        Case Else: gSpeedSimMinPerSec = 1#  ' 60x
    End Select
    Application.StatusBar = "SimLine Speed: " & gSpeedSimMinPerSec & " sim-min/sec"
    MsgBox "Playback speed set to " & gSpeedSimMinPerSec & " sim-min/sec (" & (gSpeedSimMinPerSec * 60) & "x).", vbInformation, "SimLine Studio"
End Sub

' -----------------------------------------------------------------------------
' 2. EXPORT ACTIVE TIMELINE TO SIMLINE JSON (Schema v1.0.0)
' -----------------------------------------------------------------------------

Public Sub ExportActiveTimelineToJSON()
    Dim wsDash As Worksheet, wsWorld As Worksheet, wsAssets As Worksheet, wsTL As Worksheet
    Dim scenName As String, sceneId As String
    Dim savePath As Variant
    Dim json As String
    Dim fNum As Integer

    gIsPlaying = False
    Set wsDash = ThisWorkbook.Worksheets("Dashboard")
    Set wsWorld = ThisWorkbook.Worksheets("Scene_World")
    Set wsAssets = ThisWorkbook.Worksheets("Assets")

    scenName = Trim$(CStr(wsDash.Range("C4").Value))
    On Error Resume Next
    Set wsTL = ThisWorkbook.Worksheets(scenName)
    On Error GoTo 0
    If wsTL Is Nothing Then
        MsgBox "Timeline worksheet '" & scenName & "' not found.", vbCritical, "Export Failed"
        Exit Sub
    End If

    sceneId = Trim$(CStr(wsWorld.Range("B6").Value))
    savePath = Application.GetSaveAsFilename( _
        InitialFileName:=sceneId & "_" & scenName & ".json", _
        FileFilter:="SimLine JSON Files (*.json), *.json", _
        Title:="Export Active Timeline to SimLine JSON")

    If savePath = False Then Exit Sub

    json = BuildSimLineJSON(wsWorld, wsAssets, wsTL)

    fNum = FreeFile
    Open CStr(savePath) For Output As #fNum
    Print #fNum, json
    Close #fNum

    MsgBox "Exported '" & scenName & "' to:" & vbCrLf & CStr(savePath), vbInformation, "SimLine Export Complete"
End Sub

Private Function BuildSimLineJSON(wsWorld As Worksheet, wsAssets As Worksheet, wsTL As Worksheet) As String
    Dim sb As String
    Dim r As Long, i As Long, j As Long
    Dim firstItem As Boolean

    ' --- Header & Scene ---
    sb = "{" & vbCrLf
    sb = sb & "  ""schema_version"": ""1.0.0""," & vbCrLf
    sb = sb & "  ""scene"": {" & vbCrLf
    sb = sb & "    ""id"": """ & JsonEsc(wsWorld.Range("B6").Value) & """," & vbCrLf
    sb = sb & "    ""background"": """ & JsonEsc(wsWorld.Range("B7").Value) & """," & vbCrLf
    sb = sb & "    ""dimensions"": { ""width"": " & CLng(wsWorld.Range("B8").Value) & ", ""height"": " & CLng(wsWorld.Range("B9").Value) & " }," & vbCrLf
    sb = sb & "    ""scale_m_per_px"": " & NumStr(wsWorld.Range("B10").Value) & "," & vbCrLf
    sb = sb & "    ""duration_ms"": " & CLng(Val(wsWorld.Range("B11").Value) * 60000#) & vbCrLf
    sb = sb & "  }," & vbCrLf

    ' --- Waypoints (Scene_World rows 15..18+) ---
    sb = sb & "  ""waypoints"": {" & vbCrLf
    firstItem = True
    r = 15
    Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
        If Not firstItem Then sb = sb & "," & vbCrLf
        firstItem = False
        sb = sb & "    """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """: { "
        sb = sb & """pos"": [" & NumStr(wsWorld.Cells(r, 2).Value) & ", " & NumStr(wsWorld.Cells(r, 3).Value) & "], "
        sb = sb & """label"": """ & JsonEsc(wsWorld.Cells(r, 4).Value) & """"
        If Trim$(CStr(wsWorld.Cells(r, 5).Value)) <> "" Then
            sb = sb & ", ""image"": """ & JsonEsc(wsWorld.Cells(r, 5).Value) & """"
        End If
        sb = sb & " }"
        r = r + 1
    Loop
    sb = sb & vbCrLf & "  }," & vbCrLf

    ' --- Zones (Scene_World rows 22..24+) ---
    sb = sb & "  ""zones"": [" & vbCrLf
    firstItem = True
    r = 22
    Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
        If Not firstItem Then sb = sb & "," & vbCrLf
        firstItem = False
        sb = sb & "    { ""id"": """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """, "
        sb = sb & """type"": """ & JsonEsc(wsWorld.Cells(r, 2).Value) & """, "
        If LCase$(Trim$(CStr(wsWorld.Cells(r, 3).Value))) = "circle" Then
            sb = sb & """geometry"": { ""shape"": ""circle"", ""center"": [" & ParseCoordPair(wsWorld.Cells(r, 7).Value) & "], ""radius_px"": " & NumStr(wsWorld.Cells(r, 6).Value) & " }"
        Else
            sb = sb & """geometry"": { ""shape"": ""polygon"", ""points"": [" & ParseCoordList(wsWorld.Cells(r, 7).Value) & "] }"
        End If
        If Trim$(CStr(wsWorld.Cells(r, 4).Value)) <> "" Or Trim$(CStr(wsWorld.Cells(r, 5).Value)) <> "" Then
            sb = sb & ", ""modifiers"": { ""solar_multiplier"": " & NumStr(wsWorld.Cells(r, 4).Value) & ", ""thermal_penalty"": """ & JsonEsc(wsWorld.Cells(r, 5).Value) & """ }"
        End If
        sb = sb & " }"
        r = r + 1
    Loop
    sb = sb & vbCrLf & "  ]," & vbCrLf

    ' --- Comm Windows (Scene_World rows 28+) ---
    sb = sb & "  ""windows"": [" & vbCrLf
    firstItem = True
    r = 28
    Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
        If Not firstItem Then sb = sb & "," & vbCrLf
        firstItem = False
        sb = sb & "    { ""id"": """ & JsonEsc(wsWorld.Cells(r, 1).Value) & """, "
        sb = sb & """start_ms"": " & CLng(Val(wsWorld.Cells(r, 2).Value) * 60000#) & ", "
        sb = sb & """end_ms"": " & CLng(Val(wsWorld.Cells(r, 4).Value) * 60000#) & ", "
        sb = sb & """bandwidth_mbps"": " & NumStr(wsWorld.Cells(r, 5).Value) & " }"
        r = r + 1
    Loop
    sb = sb & vbCrLf & "  ]," & vbCrLf

    ' --- Assets & Resources (Assets rows 6..10, Resources rows 15..20+) ---
    sb = sb & "  ""assets"": {" & vbCrLf
    firstItem = True
    r = 6
    Do While Trim$(CStr(wsAssets.Cells(r, 1).Value)) <> ""
        Dim aId As String, isStat As String, resJson As String, rr As Long, firstRes As Boolean
        aId = Trim$(CStr(wsAssets.Cells(r, 1).Value))
        isStat = IIf(UCase$(Trim$(CStr(wsAssets.Cells(r, 2).Value))) = "TRUE", "true", "false")

        If Not firstItem Then sb = sb & "," & vbCrLf
        firstItem = False

        resJson = "{"
        firstRes = True
        rr = 15
        Do While Trim$(CStr(wsAssets.Cells(rr, 1).Value)) <> ""
            If Trim$(CStr(wsAssets.Cells(rr, 2).Value)) = aId Then
                If Not firstRes Then resJson = resJson & ", "
                firstRes = False
                resJson = resJson & """" & JsonEsc(wsAssets.Cells(rr, 3).Value) & """: { "
                resJson = resJson & """initial"": " & NumStr(wsAssets.Cells(rr, 4).Value) & ", "
                resJson = resJson & """unit"": """ & JsonEsc(wsAssets.Cells(rr, 7).Value) & """, "
                resJson = resJson & """min"": " & NumStr(wsAssets.Cells(rr, 5).Value) & ", "
                resJson = resJson & """max"": " & NumStr(wsAssets.Cells(rr, 6).Value) & " }"
            End If
            rr = rr + 1
        Loop
        resJson = resJson & "}"

        sb = sb & "    """ & JsonEsc(aId) & """: { "
        sb = sb & """is_static"": " & isStat & ", "
        sb = sb & """image"": """ & JsonEsc(wsAssets.Cells(r, 8).Value) & """, "
        sb = sb & """start_pos"": [" & NumStr(wsAssets.Cells(r, 5).Value) & ", " & NumStr(wsAssets.Cells(r, 6).Value) & "], "
        sb = sb & """start_waypoint_id"": """ & JsonEsc(wsAssets.Cells(r, 4).Value) & """, "
        sb = sb & """layer"": " & CLng(wsAssets.Cells(r, 7).Value) & ", "
        sb = sb & """tags"": [""" & JsonEsc(wsAssets.Cells(r, 3).Value) & """], "
        sb = sb & """resources"": " & resJson & " }"
        r = r + 1
    Loop
    sb = sb & vbCrLf & "  }," & vbCrLf

    ' --- Collect & Sort Timeline Rows by Start_MET_Min (Required by SimLine schema) ---
    Dim evRows() As Long
    Dim evCount As Long
    evCount = 0
    For r = 5 To 39
        If Trim$(CStr(wsTL.Cells(r, 1).Value)) <> "" Then
            evCount = evCount + 1
            ReDim Preserve evRows(1 To evCount)
            evRows(evCount) = r
        End If
    Next r

    ' Insertion sort by Start_MET_Min (col H = 8)
    For i = 2 To evCount
        Dim keyRow As Long, keyStart As Double
        keyRow = evRows(i)
        keyStart = Val(wsTL.Cells(keyRow, 8).Value)
        j = i - 1
        Do While j >= 1
            If Val(wsTL.Cells(evRows(j), 8).Value) > keyStart Then
                evRows(j + 1) = evRows(j)
                j = j - 1
            Else
                Exit Do
            End If
        Loop
        evRows(j + 1) = keyRow
    Next i

    ' --- Phases (Aggregated from Events) ---
    Dim phNames() As String, phStart() As Long, phEnd() As Long
    Dim phCount As Long, pIdx As Long, foundPh As Long
    phCount = 0
    For i = 1 To evCount
        r = evRows(i)
        Dim pName As String, sMs As Long, eMs As Long
        pName = Trim$(CStr(wsTL.Cells(r, 3).Value))
        sMs = CLng(Val(wsTL.Cells(r, 8).Value) * 60000#)
        eMs = CLng(Val(wsTL.Cells(r, 9).Value) * 60000#)
        foundPh = 0
        For pIdx = 1 To phCount
            If phNames(pIdx) = pName Then foundPh = pIdx: Exit For
        Next pIdx
        If foundPh = 0 Then
            phCount = phCount + 1
            ReDim Preserve phNames(1 To phCount)
            ReDim Preserve phStart(1 To phCount)
            ReDim Preserve phEnd(1 To phCount)
            phNames(phCount) = pName
            phStart(phCount) = sMs
            phEnd(phCount) = eMs
        Else
            If sMs < phStart(foundPh) Then phStart(foundPh) = sMs
            If eMs > phEnd(foundPh) Then phEnd(foundPh) = eMs
        End If
    Next i

    sb = sb & "  ""phases"": [" & vbCrLf
    For pIdx = 1 To phCount
        If pIdx > 1 Then sb = sb & "," & vbCrLf
        sb = sb & "    { ""id"": """ & Slugify(phNames(pIdx)) & """, ""name"": """ & JsonEsc(phNames(pIdx)) & """, ""start_ms"": " & phStart(pIdx) & ", ""end_ms"": " & phEnd(pIdx) & " }"
    Next pIdx
    sb = sb & vbCrLf & "  ]," & vbCrLf

    ' --- Events ---
    sb = sb & "  ""events"": [" & vbCrLf
    For i = 1 To evCount
        r = evRows(i)
        Dim evType As String, fromWp As String, toWp As String, p1 As String, p2 As String
        evType = LCase$(Trim$(CStr(wsTL.Cells(r, 11).Value)))
        fromWp = Trim$(CStr(wsTL.Cells(r, 12).Value))
        toWp = Trim$(CStr(wsTL.Cells(r, 13).Value))
        p1 = Trim$(CStr(wsTL.Cells(r, 14).Value))
        p2 = Trim$(CStr(wsTL.Cells(r, 15).Value))

        If i > 1 Then sb = sb & "," & vbCrLf
        sb = sb & "    { ""id"": """ & JsonEsc(wsTL.Cells(r, 1).Value) & """, "
        sb = sb & """phase_id"": """ & Slugify(CStr(wsTL.Cells(r, 3).Value)) & """, "
        sb = sb & """start_ms"": " & CLng(Val(wsTL.Cells(r, 8).Value) * 60000#) & ", "
        sb = sb & """end_ms"": " & CLng(Val(wsTL.Cells(r, 9).Value) * 60000#) & ", "
        sb = sb & """target_asset_id"": """ & JsonEsc(wsTL.Cells(r, 10).Value) & """, "
        sb = sb & """type"": """ & evType & """"

        Select Case evType
            Case "move"
                sb = sb & ", ""from_waypoint_id"": """ & JsonEsc(fromWp) & """, ""to_waypoint_id"": """ & JsonEsc(toWp) & """"
                sb = sb & ", ""path"": [[" & LookupWpPos(wsWorld, fromWp) & "], [" & LookupWpPos(wsWorld, toWp) & "]]"
                sb = sb & ", ""easing"": """ & IIf(p1 <> "", JsonEsc(p1), "linear") & """"
                If Val(p2) > 0 Then sb = sb & ", ""max_speed_mps"": " & NumStr(p2)
            Case "attach"
                sb = sb & ", ""parent_asset_id"": """ & JsonEsc(p1) & """"
            Case "detach"
                sb = sb & ", ""parent_asset_id"": """ & JsonEsc(p1) & """"
                If toWp <> "" Then sb = sb & ", ""detach_pos"": [" & LookupWpPos(wsWorld, toWp) & "]"
            Case "state"
                sb = sb & ", ""state"": """ & JsonEsc(p1) & """"
            Case "label"
                sb = sb & ", ""text"": """ & JsonEsc(p1) & """"
            Case "resource_delta"
                sb = sb & ", ""resource"": """ & JsonEsc(p1) & """, ""rate_per_min"": " & NumStr(p2)
        End Select

        sb = sb & " }"
    Next i
    sb = sb & vbCrLf & "  ]" & vbCrLf & "}"

    BuildSimLineJSON = sb
End Function

' -----------------------------------------------------------------------------
' 3. HELPER FUNCTIONS
' -----------------------------------------------------------------------------

Private Function LookupWpPos(wsWorld As Worksheet, wpId As String) As String
    Dim r As Long
    r = 15
    Do While Trim$(CStr(wsWorld.Cells(r, 1).Value)) <> ""
        If Trim$(CStr(wsWorld.Cells(r, 1).Value)) = wpId Then
            LookupWpPos = NumStr(wsWorld.Cells(r, 2).Value) & ", " & NumStr(wsWorld.Cells(r, 3).Value)
            Exit Function
        End If
        r = r + 1
    Loop
    LookupWpPos = "0, 0"
End Function

Private Function ParseCoordPair(ByVal s As String) As String
    Dim parts() As String
    parts = Split(Trim$(s), ",")
    If UBound(parts) >= 1 Then
        ParseCoordPair = NumStr(parts(0)) & ", " & NumStr(parts(1))
    Else
        ParseCoordPair = "0, 0"
    End If
End Function

Private Function ParseCoordList(ByVal s As String) As String
    Dim pairs() As String, out As String, k As Long
    pairs = Split(s, ";")
    For k = LBound(pairs) To UBound(pairs)
        If Trim$(pairs(k)) <> "" Then
            If out <> "" Then out = out & ", "
            out = out & "[" & ParseCoordPair(pairs(k)) & "]"
        End If
    Next k
    ParseCoordList = out
End Function

Private Function JsonEsc(ByVal v As Variant) As String
    Dim s As String
    s = CStr(v)
    s = Replace(s, "\", "\\")
    s = Replace(s, """", "\""")
    s = Replace(s, vbCrLf, " ")
    s = Replace(s, vbLf, " ")
    JsonEsc = s
End Function

Private Function NumStr(ByVal v As Variant) As String
    NumStr = Replace(Trim$(Str$(Val(v))), ",", ".")
End Function

Private Function Slugify(ByVal s As String) As String
    Dim i As Long, ch As String, res As String
    s = LCase$(Trim$(s))
    For i = 1 To Len(s)
        ch = Mid$(s, i, 1)
        If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Then
            res = res & ch
        ElseIf Right$(res, 1) <> "_" And Len(res) > 0 Then
            res = res & "_"
        End If
    Next i
    If Right$(res, 1) = "_" Then res = Left$(res, Len(res) - 1)
    Slugify = res
End Function

Wiring the Buttons on Dashboard

  1. Go to Developer → Insert → Button (Form Control) and draw 5 small buttons along row 6 (or next to C4:D5) on Dashboard.

  2. Assign each button to its matching macro:

    • Play / Pause → Sim_TogglePlayPause

    • Reset → Sim_Reset

    • -2m → Sim_StepBack

    • +2m → Sim_StepForward

    • Speed → Sim_CycleSpeed

    • Export JSON → ExportActiveTimelineToJSON

  3. Click Export JSON to write a SimLineTimeline v1.0.0 file you can drop directly into simline_viewer.html (via Load Compiled JSON) or audit with python simline_validator.py <exported>.json.


Provide a tutorial for adding a timeline

Adding a new mission scenario (for example, TL_EVA1_Extended) to SimLine_Lunar_EVA_Simulator.xlsx takes five steps. Because the VBA exporter reads the active sheet name directly from Dashboard!C4, no VBA code changes are required.

Step 1: Duplicate an Existing Timeline Sheet

  1. Right-click the TL_EVA1_Nominal tab at the bottom of Excel and select Move or Copy...

  2. Check Create a copy, place it next to TL_EVA1_Abort, and click OK.

  3. Rename the new tab to your scenario name (e.g., TL_EVA1_Extended). Keep the name free of spaces so formulas stay clean.

  4. Update the banner title in A1:A2 to describe your new scenario.

Step 2: Author Your Mission Events (Rows 5–39)

Edit the event rows in A5:P39. Do not overwrite the formulas in columns H (Start_MET_Min), I (End_MET_Min), or Q (Validation_Flag).

  • Clearing unused rows: If your new timeline has fewer than 31 events, clear columns A:P on the extra rows (leaving them blank).

  • Chaining events: Set Trigger_Mode (Col D) to AT for absolute timestamps (entered in Offset_Min, Col F), or AFTER to chain off any prior Block_ID (entered in Ref_Block_ID, Col E).

  • Adding new assets or waypoints: If your scenario needs a new location or asset, add it to Scene_World (below row 18) or Assets (below row 10) first, then expand the INDEX/MATCH ranges if you go beyond the existing rows.

  • Verify inline: Check Column Q (Validation_Flag)—every active row should turn green (OK). Any red ERR: flag indicates a speed limit, static asset, or comm blackout violation.

Step 3: Add the New Sheet to the Dashboard Dropdown

  1. Go to the Dashboard sheet and select cell C4 (Active Timeline).

  2. On the ribbon, go to Data → Data Validation.

  3. In the Source box, append your new sheet's exact tab name:

    TL_EVA1_Nominal,TL_EVA1_Abort,TL_EVA1_Extended
  4. Click OK.

Step 4: Wire the New Sheet into Sim_Engine

  1. Go to the Sim_Engine sheet and select cell A5.

  2. Replace the existing IF formula with a nested IF (works in all Excel versions) or IFS (Excel 2019+/365) that includes your new sheet:

    =IF(Dashboard!$C$4="TL_EVA1_Nominal", TL_EVA1_Nominal!A5, IF(Dashboard!$C$4="TL_EVA1_Abort", TL_EVA1_Abort!A5, TL_EVA1_Extended!A5))
    
  3. Copy cell A5 across columns A5:Q5, then fill down through A39:Q39.

    • Tip: Do not touch columns R:V—those automatically compute active status, elapsed overlap, and interpolated (X, Y) coordinates from A5:Q39.

Step 5: Add the Scenario to the Comparison Table (Optional)

If you want your new timeline to appear in the side-by-side Scenario Comparison table:

  1. On Sim_Engine, copy row O44:T44 down to O45:T45.

  2. In O45, type TL_EVA1_Extended.

  3. Select P45:T45, press Ctrl + H (Find & Replace), replace TL_EVA1_Abort with TL_EVA1_Extended, and click Replace All.

  4. On Dashboard, insert a row below row 18 (or use row 19) and copy A18:G18 down so it references Sim_Engine!O45:T45.

Step 6: Test & Export

  1. Switch Dashboard!C4 to TL_EVA1_Extended.

  2. Scrub Dashboard!C5 (or click Play / Pause) to verify the 2D Operations Map, Live Asset Telemetry, and Consumables Profile chart update to your new mission.

  3. Click Export JSON to generate a SimLineTimeline v1.0.0 .json file for simline_viewer.html or simline_validator.py.


From <https://gemini.google.com/app/26be29b0585d5221>  Google Gemini (4 Neon)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#761 New Ways to Access Online Content, particularly Virtual Reality Content