diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..369aa91 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: samspring diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..4a94ca3 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,46 @@ +name: Build + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + macos: + runs-on: macos-14 + steps: + - uses: actions/checkout@v4 + - name: Test telemetry and layout safeguards + run: swift test -c release --jobs 2 + - name: Build and package + run: UNIVERSAL=1 VERSION=0.0.0-ci BUILD_NUMBER=${{ github.run_number }} ./scripts/package_app.sh + - name: Verify bundle + run: | + plutil -lint build/Retrolemetry.app/Contents/Info.plist + codesign --verify --deep --strict build/Retrolemetry.app + codesign --display --entitlements - --xml build/Retrolemetry.app > build/signed-entitlements.plist + test "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.personal-information.location' build/signed-entitlements.plist)" = true + test -x build/Retrolemetry.app/Contents/MacOS/Retrolemetry + test -s build/Retrolemetry.app/Contents/Resources/default.metallib + test -s build/Retrolemetry.app/Contents/Resources/AppIcon.icns + test -s build/Retrolemetry.app/Contents/Resources/Sparkle-LICENSE.txt + cmp LICENSE build/Retrolemetry.app/Contents/Resources/Retrolemetry-LICENSE.txt + cmp NOTICE.txt build/Retrolemetry.app/Contents/Resources/Retrolemetry-NOTICE.txt + test -x build/Retrolemetry.app/Contents/Frameworks/Sparkle.framework/Versions/B/Autoupdate + test -x build/Retrolemetry.app/Contents/Frameworks/Sparkle.framework/Versions/B/Updater.app/Contents/MacOS/Updater + test "$(/usr/libexec/PlistBuddy -c 'Print :SUFeedURL' build/Retrolemetry.app/Contents/Info.plist)" = https://samspring.github.io/Retrolemetry/appcast.xml + test "$(/usr/libexec/PlistBuddy -c 'Print :SURequireSignedFeed' build/Retrolemetry.app/Contents/Info.plist)" = true + test "$(/usr/libexec/PlistBuddy -c 'Print :SUVerifyUpdateBeforeExtraction' build/Retrolemetry.app/Contents/Info.plist)" = true + otool -l build/Retrolemetry.app/Contents/MacOS/Retrolemetry | grep -q '@executable_path/../Frameworks' + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIconFile' build/Retrolemetry.app/Contents/Info.plist)" = AppIcon.icns + ARCHS=$(lipo -archs build/Retrolemetry.app/Contents/MacOS/Retrolemetry) + echo "$ARCHS" | grep -qw arm64 + echo "$ARCHS" | grep -qw x86_64 + - name: Verify update feed and release-site safeguards + run: | + swift scripts/verify_appcast.swift Resources/Info.plist site/appcast.xml + python3 scripts/validate_site.py + sh -n scripts/package_app.sh scripts/embed_sparkle.sh scripts/notarize_app.sh diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..7b9af9a --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,37 @@ +name: Publish Retrolemetry website + +on: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + prepare: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Require validated public download + run: python3 scripts/validate_site.py --release + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: site + + deploy: + needs: prepare + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/deploy-pages@v4 + id: deployment diff --git a/.gitignore b/.gitignore index b17a858..c201aea 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ Icon? .build/ .swiftpm/ Packages/ -Package.resolved # Xcode build products and local state build/ @@ -32,6 +31,10 @@ DerivedData/ *.provisionprofile *.key *.pem +*.p8 +*.pfx +*.ed25519 +*.certSigningRequest .env .env.* !.env.example @@ -39,9 +42,13 @@ DerivedData/ # Local app bundles, archives, packaging, and exported settings *.app/ *.zip +*.dmg *.xcarchive/ outputs/ work/ +dist/ +.release-prep/ +__pycache__/ # Editors .vscode/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..836f49f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,95 @@ +# Changelog + +All notable changes to Retrolemetry will be documented here. This project follows [Semantic Versioning](https://semver.org/). + +## 1.0.0 - 2026-10-18 + +First public release. + +- Matched memory/disk used/free amounts to their dim labels, removed the space before GB/TB, and made both labels and amounts 20% smaller with close-set lower headings, without changing the central percentages or saved layout +- Centered memory/disk headings and percentages at their original fit, with larger used/free readouts alongside them instead of reducing the main type +- Added bounded local-forecast retries for transient server/connection failures and cancellation of superseded requests, with privacy-safe error diagnostics +- Fixed missing location-access signing capability in hardened app bundles so macOS can request the user's consent for weather; packaging and CI now check the signed entitlement +- Added current CPU/memory percentages to Signal Analysis traces and real used/free amounts to the memory/disk tiles +- Split the metrics network history into TX above/RX below a shared center line, with pink/cyan synthwave traces, a TX current reading and an RX lower readout; saved module IDs and frames stay unchanged +- Bundled the application's MIT license and map-data notices alongside Sparkle's license +- Added Sparkle 2.10.0 update checks, verified download/install/relaunch, a dedicated Retrolemetry signing key and signed HTTPS feed, and an automatic-check setting; existing preferences, layouts, credentials and login identity remain unchanged +- Embedded and signed Sparkle's nested helpers before outer app signing; added private feed preparation, reproducible dependency locking and isolated native updater QA +- Added the approved split phosphor-green/synthwave app icon, transparent native edges and all standard/Retina icon sizes; the menu-bar waveform stays unchanged +- Renamed Headers/main text to Main text and made Dark texts control every dim text element across all scenes, including dim titles, clock labels, and ticker columns; saved settings and module frames remain unchanged +- Added double-click slideshow start/stop without triggering a stock/radar single-click action; manual scrolling remains available while paused +- Split typography into Metrics/Stats, Dark texts, Main text, Frame header, and Frame footer with independent global/per-view controls and backward-compatible saved sizes +- Added automatic weather-region selection using existing location coverage, plus manual Israel/North America/Europe selection in General and Weather layout settings +- Added cached, bounded regional vector maps and region-specific six-location forecast batches; region switches cancel outdated requests and cannot show another region's weather points +- Replaced Settings scene dropdowns with tabs and extended all typography controls to 300%, without changing saved values or module frames +- Fixed the Signal Analysis network I/O border to occupy its saved module frame instead of creating extra inset horizontal edges +- Added a bounded GPU-drawn Israel map, with only Tel Aviv-Yafo outlined inside it, and six geographically positioned forecast samples for rain probability, temperature, and wind speed/direction +- Replaced pseudo-spatial weather contacts with actual regional Open-Meteo forecasts, refreshed in one batch every 15 minutes; missing/stale data stays unavailable and decorative contacts remain labeled as demo +- Added complete globe meridians, continent outlines, an approximate-weather-location pulse, and offline weekday trading-region lights +- Kept native vectors throughout scene switches and synchronized their progress with the text, masks, and transition effects +- Added ticker-row focus selection without changing stock symbols or chart timeframes +- Standardized typography roles and added global/per-view controls without resetting existing font values or layouts +- Removed hidden-module editor outlines and matched curved/effected previews and drag coordinates to the live view +- Expanded only the outer frame's vertical clearance so 200% frame text fits without moving saved modules +- Moved steady-scene globe, radar, signal/grid, and CRT grain/tracking animation to bounded native Metal layers instead of rebuilding SwiftUI paths each frame +- Removed duplicate per-frame signal-grid state updates; retained metric smoothing, animation choices, calibration, and typography +- Removed hidden-console rendering work and limited in-flight GPU frames and effect-buffer resolution +- Replaced the Signal Analysis memory-at-horizon option with real GPU history, retaining existing horizon selections +- Added optional GPU utilization, GPU-history, and battery power/voltage modules to Live System Metrics +- Read GPU counters once per second and battery flow every five seconds through public IOKit functions, with explicit unavailable states and no CPU-load proxy +- Preserved custom module frames while offering an expanded six-tile/four-graph metrics default +- Kept radar and globe shape calibration exclusively on their corresponding layout-editor pages without resetting saved corrections +- Reduced CPU use by limiting animation clocks to moving elements instead of rebuilding complete scenes every frame +- Reused CRT noise textures and batched stationary scanline/grid drawing while preserving the visual controls +- Added a 15/30/60 fps performance selector, defaulting to 30 fps, and paused animation while hidden, occluded, or asleep +- Consolidated system samples into one snapshot update and reduced disk-capacity checks to once every 30 seconds +- Added a Signal Analysis display selector for the spinning signal or a live GPU-history silhouette along the grid horizon +- Added optional GPU-rendered CRT tube curvature with a global strength slider and matching curved-screen click coordinates +- Added click-to-cycle Today, Week, Month, and Year ranges to the Market Watch focus chart +- Stabilized horizontal scene scrolling so each direct gesture moves once and momentum cannot reverse it +- Added click-to-cycle target modes directly on the live weather radar +- Kept full-system graph traces below their title and value headers at every typography scale +- Enlarged daily weather low and high temperatures and reserved enough width to prevent truncation +- Restored the green phosphor background tint control without making scene transitions transparent +- Restored the preferred external display by saved identity when macOS reassigns temporary display IDs + +### Earlier release-preparation changes + +#### Added + +- First public macOS release preparation +- Four animated telemetry and vector scenes +- Dedicated 960×540 display selection and reconnection behavior +- Layout, typography, theme, and physical-display calibration controls +- Optional Core Location and Open-Meteo weather panel +- Menu-bar controls, Launch at Login, settings export, and `SIGUSR1` automation +- A menu-bar synthwave toggle and independent thickness controls for two moving VHS tracking lines +- Dynamic Show/Hide menu text, keyboard equivalents, and separate BetterTouchTool signals for visibility and theme +- Pan, diagonal wipe, and CRT sync-roll scene transitions +- A third typography control for chrome, status, and remaining interface text +- A live Finnhub market panel with editable symbols and a Keychain-protected personal API key +- A dedicated market-watch layout with no system meters competing for space +- Three configurable world clocks on the market panel, defaulting to Florida, Los Angeles, and London +- A restored rotating market globe, separate clock module, two five-symbol ticker boards, and a compact USD→ILS daily reference graph +- Configurable slideshow ordering, 15/30/60/180-second presets, and a custom interval field +- Optional CPU-driven synthwave perspective grid for Signal Analysis +- Match-display, common Mac/iPad/phone-landscape, and custom output sizing with proportional 960×540 rendering +- A combined 12-hour weather forecast and configurable 3–7-day daily outlook +- Reproducible `.app` bundle packaging, Developer ID signing hooks, and notarization workflow +- Optional 5/10/20-pixel snapping for moving and resizing modules in the layout editor +- Signal-grid animation controls for motion, telemetry source, pattern, and response speed +- Weather-driven radar targets for precipitation, temperature, and wind, plus optional target pulsing + +#### Changed + +- Public package, product, target, executable, and process name standardized as Retrolemetry +- Existing `DockTelemetry.*` preference keys retained to preserve settings for early builds +- Scene changes now keep both views on screen for a continuous edge-to-edge pan +- The System Telemetry globe area now presents live quotes, daily changes, ranges, and accumulating price traces +- Signal Analysis now uses a slower, stable perspective grid that travels toward the horizon +- Wipe transitions are fully opaque, and Sync Roll now collapses and restores the CRT image at the center line +- Settings navigation and the layout editor inspector were reorganized for clearer editing at practical window sizes +- All three typography controls now support scaling up to 200% +- Settings now use one AppKit-owned window, preventing duplicate windows after backup export and eliminating unused top space +- Signal grids now span beyond the viewport, show the selected live input in the header, and use stronger data-driven terrain motion with a synthwave-pink horizon +- The layout editor now uses its lower workspace for typography, modules, and selected-module controls instead of a narrow scrolling sidebar diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b86b075 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,17 @@ +# Contributing + +Thanks for helping improve Retrolemetry. Focused fixes and documentation improvements are welcome. + +## Before opening a pull request + +1. Open an issue first for behavior changes or large features. +2. Keep the native SwiftUI/AppKit design and macOS 14 minimum unless a change is discussed. +3. Preserve the 960×540 base composition, proportional output sizing, and preferred-display behavior. +4. Do not add analytics, credentials, private APIs, or third-party dependencies without prior discussion. +5. Run `swift test -c release --jobs 2` and test the affected view on a secondary display when possible. Use a scratch directory outside cloud-synced storage for local builds. + +Sparkle is the existing update dependency. Changes to its feed, public key, verification policy, or packaging require release-owner review. Private signing keys and credentials must remain outside the repository. Native updater tests and release artifacts are separate from unit tests; do not describe an update as accepted solely because the unit suite passes. + +Use a clear commit message and explain user-visible effects, validation, and any signing or hardware limits in the pull request. + +By contributing, you agree that your contribution is licensed under the project's MIT License. diff --git a/LAUNCH.md b/LAUNCH.md new file mode 100644 index 0000000..02553b2 --- /dev/null +++ b/LAUNCH.md @@ -0,0 +1,57 @@ +# Retrolemetry launch copy + +Drafts for use after v1.0.0 is published. Confirm the release/download links work, check each community's current posting rules, and attach a clean native-resolution screenshot or short capture before posting. + +## r/macapps + +**Title:** Retrolemetry — a native system console for tiny secondary Mac displays + +I built Retrolemetry for the 960×540 display in a Mac dock. Its console scales proportionally to other macOS-visible displays. It is a SwiftUI/AppKit menu-bar app with local CPU, memory, disk, network, GPU and battery-flow readings, optional weather and market data, and four animated views. + +It remembers a dedicated display, waits safely if that screen is disconnected, supports Launch at Login, and includes a visual layout editor plus green-phosphor and synthwave themes. There is also a `SIGUSR1` toggle for BetterTouchTool automation. + +The app code is open source under MIT. There is no Electron, account, analytics, or bundled credential. Weather uses Core Location plus Open-Meteo; optional live quotes use your own Finnhub key stored in Keychain. In-app updates use Sparkle with signed feeds and downloads. + +GitHub / download: https://github.com/SamSpring/Retrolemetry/releases/tag/v1.0.0 + +I would especially appreciate feedback from people using unusual dock displays or compact HDMI screens. + +## r/macOS + +**Title:** I made a native macOS telemetry display for the tiny screen in my dock + +Retrolemetry turns a compact secondary display into a live system console. It has CPU, memory, disk and network telemetry, animated weather and vector scenes, optional local weather and market data, two visual themes, and a layout editor. Its 960×540 composition scales proportionally to other display sizes. + +The app is native SwiftUI/AppKit, runs from the menu bar, remembers its target display, and hides instead of jumping onto the main screen when that display disconnects. It includes signed in-app updates through Sparkle. The app code is MIT licensed, with no accounts or analytics. + +Project and download: https://github.com/SamSpring/Retrolemetry/releases/tag/v1.0.0 + +## Show HN + +**Title:** Show HN: Retrolemetry – a native macOS console for dedicated mini displays + +Retrolemetry is an open-source SwiftUI/AppKit menu-bar app that turns a secondary display into a live system and vector console. It began on a 960×540 dock display and now scales to other display sizes. + +I built it to solve the awkward parts of using a dock display: it remembers a specific monitor, restores itself after reconnection, can cover only that display's menu bar, and stays hidden rather than moving to the primary display when its target is absent. It includes real CPU, memory, disk, network, load and uptime data; four animated views; optional Open-Meteo weather; layout editing; and signal-based automation for BetterTouchTool. + +The console is native SwiftUI/AppKit with Metal rendering; Sparkle 2 handles signed update checks, downloads, installation, and relaunch. No Electron, accounts, analytics, or embedded API keys. Optional Finnhub quotes use your own Keychain-protected key. macOS 14+; application code MIT licensed. + +Code and release: https://github.com/SamSpring/Retrolemetry + +I would welcome feedback on the display-selection behavior, packaging, and other small-screen hardware people want to support. + +## Ko-fi page + +**Page title:** Support Retrolemetry + +Retrolemetry is a native, open-source macOS console for compact secondary displays. It began as a way to make the tiny screen in a Mac dock genuinely useful, with live system telemetry, animated vector views, local weather, and careful dedicated-display behavior. + +If you enjoy the app, a tip helps cover Apple developer costs, test hardware, and time spent improving compatibility and polish. Retrolemetry remains MIT licensed and available on GitHub. + +Download and source: https://github.com/SamSpring/Retrolemetry + +Thank you for supporting small, focused Mac software. + +## Short Ko-fi announcement + +Retrolemetry v1.0.0 is out: a native, open-source macOS telemetry console for tiny secondary displays. Four animated views, optional local weather, display memory, layout controls, and no Electron or analytics. Download it here: https://github.com/SamSpring/Retrolemetry/releases/tag/v1.0.0 diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 0000000..2e56f9f --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,30 @@ +Retrolemetry notices + +Application code +The application code is licensed under MIT. The full license and copyright +notice are in LICENSE in the source repository and Retrolemetry-LICENSE.txt +inside the packaged app's Contents/Resources directory. + +Sparkle +Retrolemetry uses Sparkle 2.10.0 for updates. Sparkle's license is reproduced +without modification in Sparkle-LICENSE.txt inside Contents/Resources. +https://github.com/sparkle-project/Sparkle + +Natural Earth map artwork +The continent and country outlines use simplified public-domain Natural Earth +110m land and 50m admin-0 country datasets. Map artwork is illustrative and is +not a navigation or boundary authority. +https://www.naturalearthdata.com/about/terms-of-use/ + +Tel Aviv-Yafo city coordinates +The city coordinate ring in Sources/Retrolemetry/RadarMapData.swift is derived +from OpenStreetMap relation 1382494. Copyright OpenStreetMap contributors. +This coordinate dataset remains under the Open Database License (ODbL) 1.0, +separately from the application's MIT-licensed code. Its coordinates and +provenance are available in the public source repository. +https://www.openstreetmap.org/relation/1382494 +https://www.openstreetmap.org/copyright +https://opendatacommons.org/licenses/odbl/1-0/ + +Source repository +https://github.com/SamSpring/Retrolemetry diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..89a223c --- /dev/null +++ b/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100", + "version" : "2.10.0" + } + } + ], + "version" : 2 +} diff --git a/Package.swift b/Package.swift index e97a46b..0240840 100644 --- a/Package.swift +++ b/Package.swift @@ -2,15 +2,21 @@ import PackageDescription let package = Package( - name: "DockTelemetry", + name: "Retrolemetry", platforms: [.macOS(.v14)], products: [ - .executable(name: "DockTelemetry", targets: ["DockTelemetry"]) + .executable(name: "Retrolemetry", targets: ["Retrolemetry"]) + ], + dependencies: [ + .package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0") ], targets: [ .executableTarget( - name: "DockTelemetry", - path: "Sources/DockTelemetry" - ) + name: "Retrolemetry", + dependencies: [.product(name: "Sparkle", package: "Sparkle")], + path: "Sources/Retrolemetry", + linkerSettings: [.unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks"])] + ), + .testTarget(name: "RetrolemetryTests", dependencies: ["Retrolemetry"]) ] ) diff --git a/README.md b/README.md index b993789..87c6e78 100644 --- a/README.md +++ b/README.md @@ -1,78 +1,155 @@ # Retrolemetry -A lightweight native macOS console made for a dedicated 960×540 novelty dock display. It uses SwiftUI Canvas and AppKit only—no Electron, web view, bundled assets, or external CRT filter. - -Released under the [MIT License](LICENSE). - -## Included in this first version - -- Exact 960×540 borderless black window -- Remembers a display by its macOS display ID; initially chooses the smallest connected external display -- Repositions itself when that display reconnects -- Settings includes a default-display picker with monitor name, resolution, and connection type -- If an explicitly selected display is disconnected, the console waits hidden instead of opening on the main monitor -- Covers the menu bar on the 960×540 display by default without hiding the menu bar on the main Mac display -- Live CPU, memory, disk, network, load-average, and uptime telemetry -- Four scenes—System Telemetry, Sector Scan, Signal Analysis, and data-only Live System Metrics—with optional automatic cycling -- Segmented meters, CPU history, blinking indicators, a rotating wireframe globe, radar, Lissajous scope, and vector terrain -- Global visual-style toggle: classic green phosphor or cyan/magenta synthwave, applied live to every scene -- Adjustable green background tint in phosphor mode, ranging from true black to a deep green wash -- Visual layout editor with static scene previews, draggable and resizable modules, visibility toggles, per-scene reset, immediate saving, and global font sizing -- Correct 3D globe rotation plus prominent, independent sphere width and height calibration controls for the physical display -- Independent radar width/height calibration, primary and secondary typography controls, and exportable settings backups -- Direct-click layout editing with deterministic movement and isolated corner-handle resizing -- Built-in adjustable bloom, high-definition scan bands, independently adjustable phosphor noise, vignette, and an optional moving VHS tracking band in both styles -- 60 Hz procedural animation with a reduced curve workload for smoother motion -- Larger radar telemetry, trace panels, and labels for the physical 960×540 screen -- Menu-bar waveform icon with Show/Hide, Move Display, Settings, and Quit -- Optional native macOS Launch at Login registration -- Horizontal mouse-wheel navigation between scenes, with no scroll bars -- Smooth pan/wipe transitions between scenes -- Real CPU, memory, disk, and network data integrated throughout -- Full-screen data-only scene with oversized metrics and CPU, memory, and network history -- Radar scene weather panel with current temperature, feels-like temperature, humidity, wind, rain, and 12-hour temperature/precipitation graphs -- `SIGUSR1` toggle for BetterTouchTool automation - -GPU utilization and temperatures are intentionally omitted: macOS does not expose them through a stable public API suitable for a lightweight App Store-safe implementation. - -## Run - -Open `Package.swift` in Xcode and run the internal `DockTelemetry` executable, or from Terminal: +Retrolemetry turns a secondary Mac display into a native, animated system console. Its composition is designed at 960×540, then scales proportionally to Mac, iPad/Sidecar, phone-landscape, and custom display sizes without distorting the layout. It stays out of the Dock and uses SwiftUI and AppKit—no Electron. + +![Retrolemetry Signal Analysis](assets/screenshots/retrolemetry-signal-analysis.png) + +![Retrolemetry Local Weather Radar](assets/screenshots/retrolemetry-local-weather-radar.png) + +![Retrolemetry Live System Metrics](assets/screenshots/retrolemetry-live-system-metrics.png) + +## Features + +### Live console + +- CPU, memory, disk, network, load average, and uptime telemetry, plus optional GPU utilization and battery power/voltage +- Four views: Market Watch, Weather, Signal Analysis, and Live System Metrics +- A dedicated live stock-market screen with a rotating globe, separate world clocks, two five-symbol ticker boards, a click-to-cycle Today/Week/Month/Year focus chart, and a compact USD→ILS reference-rate history +- Green-phosphor and synthwave themes, plus adjustable bloom, scan bands, noise, vignette, and dual VHS tracking lines +- 30 fps animation by default, with 15/60 fps options in Settings; only moving elements refresh rapidly, and hidden or sleeping output pauses animation +- Native Metal renders steady-scene vectors and moving CRT effects independently of the text/data UI; hidden output does not render scenes. Layout previews stay static and scene transitions retain their existing appearance. +- Optional GPU-rendered CRT tube curvature with adjustable strength across every live scene +- Local conditions, a 12-hour temperature/precipitation forecast, a configurable 3–7-day outlook, and click-to-cycle weather radar targets + +### Dedicated-display behavior + +- Borderless output with Match Display, common Mac/iPad/phone-landscape presets, and custom dimensions +- Automatically chooses the smallest external display, or remembers a display selected in Settings +- Returns to that display after reconnection +- Waits hidden when an explicitly selected display is disconnected instead of falling back to the main Mac display +- Can cover the menu bar on the dock display without changing the main display + +### Customization and control + +- Optional automatic scene cycling, configurable scene order and interval, horizontal mouse-wheel navigation, and selectable Pan, Diagonal Wipe, or Sync Roll transitions +- Keys `1`–`4` select a scene; `0` or `A` resumes automatic cycling +- Visual layout editor with drag, resize, visibility, five typography groups, and per-view reset controls +- Scene tabs in Settings and typography adjustment up to 300% (text fits within each saved module's available space) +- Radar and globe aspect-ratio calibration on their corresponding layout-editor pages +- Editable Finnhub watch symbols with a Keychain-protected personal API key +- Three configurable market-panel world clocks with automatic daylight-saving changes +- Click a ticker row to hold that stock in the focus chart; click the same row again to resume automatic stock rotation. Clicking the large chart still cycles its timeframe. +- The globe includes continent coastlines, a pulsing marker using the existing approximate weather location, and weekday-session lights for US, European, and Asian regions. These lights are clock-based, not a feed: holidays, early closes, and extended trading are not included. +- Typography groups are Metrics/Stats, Dark texts (all dim, less-phosphorescent text, including titles and labels), Main text (bright labels, stock symbols, weather days/conditions), Frame header, and Frame footer. “Apply to all views” shares the controls; uncheck it to edit just the selected view. Existing three-slider values and exported layouts retain their appearance until a new group is adjusted. +- Static layout previews can show the same CRT curvature/effects as the live screen; hidden modules have no remaining selection outline. +- Optional animated synthwave perspective grid in Signal Analysis, with selectable patterns and CPU, GPU, network, or disk response +- Signal Analysis can show the spinning signal or a live 96-second GPU graph above the grid horizon +- Signal Analysis CPU/memory traces include current percentages. Memory/disk tiles show actual used/free capacity; memory free includes cached/reclaimable RAM, and amounts use decimal GB/TB. +- Live System Metrics plots TX (uploads) upward and RX (downloads) downward on the same adaptive scale over about 96 seconds. Synthwave uses pink TX and cyan RX; the graph header shows current TX and the lower readout shows current RX. +- Settings export, menu-bar controls, Launch at Login, a `SIGUSR1` automation toggle, and one-gesture horizontal scene navigation that ignores momentum reversals + +GPU utilization is read through public IOKit functions from optional graphics-driver counters. It reports the busiest exposed GPU on multi-GPU Macs; driver support can vary with hardware and macOS versions. Unsupported readings show N/A and gaps in the graph, never CPU/system load masquerading as GPU activity. Battery voltage and electrical flow (voltage × current) use optional IOPowerSources/exported battery properties; the displayed wattage is **battery flow, not CPU/GPU or total Mac power consumption**. No privileged helper, password, private sensor connection, or external process is needed for these readings. Temperature sensors remain unavailable. + +Live System Metrics includes separately movable GPU, power/voltage, and GPU-history modules. Hand-arranged older layouts keep every saved frame and start these new modules hidden to prevent overlaps. Enable them in the layout editor, or reset that view to use the expanded six-tile/four-graph default. + +## Requirements + +- macOS 14 Sonoma or later +- Any macOS-visible secondary display. Match Display is recommended; iPad works through Sidecar, while an iPhone requires third-party software that exposes it to macOS as an external display. +- Apple silicon or Intel, depending on the architecture included in the downloaded release + +## Install from GitHub Releases + +The first public download is still in preparation. The following steps apply once v1.0.0 appears on the Releases page; source builds are available now. + +1. Download the latest `Retrolemetry-*.zip` from [GitHub Releases](https://github.com/SamSpring/Retrolemetry/releases). +2. Unzip it and move `Retrolemetry.app` to `/Applications`. +3. Open Retrolemetry. Grant location access only if you want local weather. +4. Use the waveform icon in the menu bar to choose the dock display and adjust Settings. + +The public release will provide a universal app for Apple silicon and Intel, a Developer ID signature, Apple notarization, and a ZIP checksum. Local builds use an ad-hoc signature by default and are not notarized. + +## Build from source + +Open `Package.swift` in Xcode and run the `Retrolemetry` executable, or use Terminal: ```sh -swift run DockTelemetry +swift run Retrolemetry ``` -Use full Xcode or a Command Line Tools installation whose Swift compiler and macOS SDK versions match. +To produce a standard app bundle and zip in `build/` and `dist/`: -## Controls +```sh +./scripts/package_app.sh +``` -- **1–4:** select a scene; **4** opens the data-only Live System Metrics view -- **0** or **A:** resume automatic 24-second cycling -- Disable **Automatically cycle scenes** in Settings to keep the current scene fixed while retaining horizontal scrolling and keys 1–4 -- Menu-bar icon → **Show / Hide Console** -- **⌘⇧D:** toggle while the menu is open/active +Use a matching Swift 6 or later compiler and macOS SDK. Packaging requires full Xcode with its Metal tools. The packaging script applies an ad-hoc signature unless `CODESIGN_IDENTITY` is set to a Developer ID Application identity. Sparkle 2.10.0 is pinned in `Package.swift` and `Package.resolved`; the initial source build downloads its official Swift Package artifact. -## Layout editor +Packaging converts the approved transparent `Resources/AppIcon.png` into all standard and Retina macOS icon sizes. The app icon combines phosphor green on the left and synthwave cyan/magenta on the right; the menu-bar waveform stays monochrome. -Open the menu-bar icon → **Settings…** → **Layout Editor**. Choose a scene, then: +Packaging also compiles the CRT curvature shader with Xcode's Metal tools. If a recent Xcode installation reports a missing Metal Toolchain, install that free component with `xcodebuild -downloadComponent MetalToolchain`. A raw source run enables curvature when a compiled `default.metallib` is available beside the executable; packaging a native build puts it there automatically. -- Click and drag any outlined module to move it -- Drag the yellow lower-right handle to resize it -- Use the module checkboxes to show or remove individual blocks -- Adjust **Font size** for all scenes -- Use **Reset this view** to restore only the selected scene +## Controls and automation -Every edit is saved immediately and applied to the live dock display. The permanent header, footer, and outer frame remain locked so the console chrome cannot be accidentally lost. +- `1`–`4`: select a scene +- `0` or `A`: resume automatic cycling +- Horizontal mouse wheel: move between scenes +- Double-click anywhere on the live console: pause/resume the slideshow without changing the selected stock or radar mode. Horizontal navigation remains available while paused. +- Menu-bar waveform: show/hide, toggle synthwave colors, move display, open Settings, or quit +- `⌘⇧D` toggles the console and `⌘⇧S` toggles synthwave while Retrolemetry is active For BetterTouchTool, add a **Run Shell Script / Task** action: ```sh -killall -USR1 DockTelemetry +killall -USR1 Retrolemetry ``` -That hides the window to reveal Wallspace underneath, or shows it again on the preferred dock display. The app keeps running while hidden, so the return is immediate. +The signal hides the console to reveal the content underneath, or restores it to the preferred display. The process remains running, so the response is immediate. + +To bind synthwave switching in BetterTouchTool, use a second **Run Shell Script / Task** action: + +```sh +killall -USR2 Retrolemetry +``` + +## Display setup and Launch at Login + +Retrolemetry starts as a menu-bar accessory app and centers its proportionally scaled console on the selected display. If no display is selected, it chooses the smallest connected external display. You can turn off menu-bar covering or change the target in Settings. + +**Launch Retrolemetry at login** uses Apple's `SMAppService.mainApp`. It is intended for an installed `.app` bundle in `/Applications`; it is not available when running the raw Swift Package executable from Terminal. + +## Updates + +Choose **Check for Updates…** from Retrolemetry's menu-bar menu (or Settings → Updates). [Sparkle 2](https://sparkle-project.org/) downloads the update, verifies it, installs it and relaunches the app. Updates preserve the existing preference domain, saved layouts, Keychain credentials and login-item identity. Settings also lets you opt in or out of automatic update checks. + +The dedicated HTTPS update feed is `https://samspring.github.io/Retrolemetry/appcast.xml`. Both the feed and update archives must carry Retrolemetry's own Ed25519 signature; archives are verified before extraction. No system profile, weather location, stock symbols or API key is attached to update requests. GitHub receives ordinary web requests (including the network address and Sparkle's app/version user agent). Source-run executables do not start the updater. + +Before the first public release, the feed is prepared but not deployed. A source-built app's public update check can therefore report a connection error until Publisher deploys the validated feed. This is not a claim that v1.0.0 is available. + +## Privacy and weather + +Retrolemetry has no accounts, analytics, advertising, or bundled tracking SDKs. System telemetry is read and displayed locally. + +Personal-location weather is optional. When location access is allowed, Core Location provides an approximate coordinate and Retrolemetry sends that coordinate to the [Open-Meteo](https://open-meteo.com/) forecast API over HTTPS. The app does not include a weather API key and does not store a location history. Denying location access leaves local weather and automatic region selection unavailable; system telemetry and a manually selected regional map still work. + +The weather scan supports Israel, North America and Europe. **Automatic (location)** is the default: a local coverage test chooses a supported map from the existing approximate weather location, without reverse-geocoding or requesting new permissions. Outside those coverage areas, or without a location, choose a manual region in Settings → Weather forecast or Layout Editor → Weather → Map region. Manual selection changes only the map and its representative forecast points, not the personal-location hourly/daily forecast. Israel retains Tel Aviv-Yafo's city outline; other regions do not display it. + +Six fixed public locations in the selected region are queried together through [Open-Meteo's forecast API](https://open-meteo.com/en/docs) every 15 minutes. North America samples Seattle, Los Angeles, Chicago, New York, Toronto and Mexico City; Europe samples London, Paris, Berlin, Madrid, Rome and Warsaw; Israel samples North, Haifa, Tel Aviv, Jerusalem, Beer Sheva and Eilat. These are representative points, not a continuous weather field. Region switches cancel outdated requests and never attach one region's forecasts to another map. Click the radar to cycle current-hour rain probability, temperature, wind speed/direction, and explicitly decorative contacts. Arrows show wind flow. These are weather-model forecasts, **not live precipitation radar or observed storm locations**. Missing readings show N/A; markers disappear when the retained forecast is over an hour old. + +Map artwork is deliberately simplified and is not a boundary or navigation authority. The country outline uses Natural Earth's public-domain 50m admin-0 default de facto dataset. The Tel Aviv coordinate ring in `RadarMapData.swift` is separate data licensed under [OpenStreetMap's ODbL](https://www.openstreetmap.org/copyright), © OpenStreetMap contributors, from [relation 1382494](https://www.openstreetmap.org/relation/1382494). That city dataset remains ODbL; the application code remains MIT. Map attribution is also displayed inside the radar. + +Live market data is also optional. Retrolemetry sends only the configured ticker symbols directly to Finnhub and stores the user's personal Finnhub API key in macOS Keychain. The key is never written to preferences, exported settings, source control, or release archives. Focus-chart requests send only the selected ticker symbol to Yahoo's public, no-login chart endpoint; Retrolemetry never connects to a Yahoo account or portfolio. The USD→ILS panel requests public daily reference-rate history from [Frankfurter](https://frankfurter.dev/) and is explicitly labeled as daily data, not a live trading quote. Quotes are informational and are not trading advice. + +## Support + +If Retrolemetry is useful to you, you can [support future development on Ko-fi](https://ko-fi.com/samspring). + +Bug reports and focused feature requests are welcome in [GitHub Issues](https://github.com/SamSpring/Retrolemetry/issues). + +## Development + +Small, behavior-preserving fixes are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). Maintainers can find signing, notarization, and release packaging steps in [RELEASING.md](RELEASING.md). -The waveform-icon **Settings…** panel lets you choose the default display, enable Launch at Login, enable or disable the slideshow, switch every scene between phosphor and synthwave styles, change the automatic scene interval, tune the built-in CRT effect, and turn menu-bar covering on or off. +Retrolemetry's application code is available under the [MIT License](LICENSE). [NOTICE.txt](NOTICE.txt) records the separate Sparkle and map-data notices, which are also included in the packaged app. -Local weather uses macOS Core Location and the Open-Meteo forecast API. The first launch of this version asks for location permission. Weather data comes directly from the forecast service because macOS does not expose the Weather app's saved locations or displayed forecast to third-party apps. +The bundled continent outlines are simplified public-domain [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/) 110m land data. They are display artwork, not a boundary or navigation map. The offline weekday lights follow core sessions documented by [NYSE](https://www.nyse.com/trade/trading-information), [London Stock Exchange](https://docs.londonstockexchange.com/sites/default/files/documents/servicetechnicaldescriptionintroductionofnewtradingcurrencies.pdf), [Xetra](https://www.xetra.com/xetra-en/trading/trading-calendar-and-trading-hours), [Japan Exchange Group](https://www.jpx.co.jp/english/equities/trading/domestic/01.html), and [HKEX](https://www.hkex.com.hk/Services/Trading-hours-and-Severe-Weather-Arrangements/Trading-Hours/Securities-Market?sc_lang=en). Region lighting is approximate and is not trading advice or a live market-status indication. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 0000000..6c3a789 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,51 @@ +# Retrolemetry v1.0.0 + +Retrolemetry is a native macOS system console designed around compact 960×540 secondary displays and scaled proportionally to other display sizes. It combines live system telemetry, vector-style animation, local weather, and precise display controls in a lightweight menu-bar app. + +## Highlights + +- Secure in-app update checks through the menu-bar menu, with verified downloads, installation and relaunch; optional automatic checks in Settings +- Four animated views: Market Watch, Weather, Signal Analysis, and Live System Metrics +- Automatic external-display selection with a remembered preferred display +- Green-phosphor and synthwave themes with configurable CRT-style effects +- Menu-bar synthwave switching, dual adjustable VHS tracking lines, and three scene transition styles +- A visual layout editor with module positioning, sizing, visibility, and typography controls +- Optional layout snapping and a no-scroll editing tray for typography, modules, and precise frame controls +- Separate typography scaling for primary values, secondary labels, and remaining chrome/status text +- Scene tabs in Settings and text scaling up to 300% without resetting saved layouts +- Five independent text-size groups for readings, all dim less-phosphorescent text, bright main text, and separate frame headers/footers; old saved sizes stay intact +- Double-click the live console to pause/resume the slideshow; horizontal scene navigation still works while paused +- A live Finnhub market panel with editable watch symbols and secure Keychain credential storage +- A dedicated market-watch scene with a rotating globe, separate clocks, two five-symbol ticker boards, a click-to-cycle Today/Week/Month/Year focus chart, and USD→ILS daily reference history +- Configurable Florida, Los Angeles, and London world clocks with automatic daylight-saving handling +- A richer weather view with upcoming hourly conditions, a configurable 3–7-day outlook, and weather-driven radar targets that cycle when the radar is clicked +- Automatic or manual Israel/North America/Europe forecast maps with regional rain probability, temperature, and wind arrows at six public locations (forecast models, not live radar imagery); Israel retains its Tel Aviv-Yafo outline +- Configurable slideshow ordering and intervals, plus a responsive synthwave perspective grid with three animation patterns and selectable telemetry input +- Proportional output sizing for compact displays, Macs, iPad/Sidecar, phone-landscape adapters, and custom dimensions +- Physical-display calibration for globe and radar proportions +- Optional Launch at Login and BetterTouchTool-compatible show/hide automation +- Stable one-gesture horizontal scene navigation that ignores trailing momentum reversals + +## Install + +Download `Retrolemetry-1.0.0.zip`, move `Retrolemetry.app` to `/Applications`, and open it. Retrolemetry requires macOS 14 or later. Grant location permission only if you want local weather. + +## Privacy + +System telemetry stays on the Mac. If weather is enabled, an approximate coordinate is sent directly to Open-Meteo over HTTPS. Retrolemetry has no account, analytics, advertising, bundled tracking SDK, or weather API key. + +The selected Israel, North America, or Europe forecast map also requests six fixed public coordinates from Open-Meteo every 15 minutes. These regional forecast requests do not include the personal coordinate. Natural Earth supplies public-domain map artwork and the Tel Aviv city-coordinate dataset is © OpenStreetMap contributors under ODbL, separately from the MIT application code. + +If live market data is configured, ticker symbols are sent directly to Finnhub and the user's personal API key remains in macOS Keychain. Focus-chart requests send the selected symbol to Yahoo's public chart endpoint. The USD→ILS panel requests public daily reference-rate history from Frankfurter. No market-data credential is bundled with the app or repository. + +Update checks contact Retrolemetry's GitHub Pages feed and GitHub release downloads. No system profile, location, stock symbols, or personal API key is attached to those requests. GitHub receives ordinary network requests, including the network address and app/version user agent. + +## Known limitations + +- The interface is composed at 960×540 and scales proportionally; narrow or portrait displays may show letterboxing. +- GPU utilization depends on optional driver counters and shows N/A on unsupported hardware. Battery wattage is electrical flow through the battery, not total Mac or CPU/GPU consumption; voltage/current may be unavailable. Temperature sensors are not included. +- Launch at Login requires the bundled app to be installed in a stable location such as `/Applications`. + +## Release integrity + +This universal release is Developer ID signed and Apple notarized. `SHA256SUMS.txt` identifies the exact ZIP used by the signed update feed. Installation and updates preserve existing preferences, layouts and Keychain data. diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..d5df7db --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,108 @@ +# Releasing Retrolemetry + +This checklist produces a downloadable macOS app from the Swift Package. Do not describe a release as notarized until `notarytool`, `stapler`, and Gatekeeper validation all succeed for the exact uploaded artifact. + +Samuel authorized publication of the app-owner-accepted v1.0.0 build 28 on 18 October 2026, including the release-source merge, GitHub Release, download website and signed update feed. Publish only the exact reviewed archive through the procedure below. Keep the working host installation and settings unchanged. + +Build 28 is a universal, updater-enabled candidate with the application license and map-data notices. Its exact retained archive passed Developer ID signing, Apple notarization, stapled-ticket validation and Gatekeeper checks. Its app source is commit `4b206ce63b29ad501b08a44b26b6e9f3493f0f5a`; later documentation-only commits do not change that archive. The developer's 60 tests passed, native weather and the requested layout changes were verified within their recorded scopes, and all 47 protected settings remained unchanged. + +Final production-app acceptance passed in an isolated macOS test clone on 17 October 2026: normal signed predecessor installation, native build 27 → exact build 28 update and relaunch, equal-version/no-update, and rejection of a wrong feed key, wrong archive key and altered archive. All 22 saved synthetic settings matched before and after the update. The synthetic Keychain entry remained configured after the update and a guest restart; Launch at Login reopened the app after login with session reopening disabled. The installed app's 103 files and links matched the exact candidate, with strict signature, stapled-ticket and Gatekeeper checks passing. The separate encrypted updater-key recovery image was reopened, independently verified and locked. These private checks do not establish a live public download or feed; the public verification steps below remain required after publication. + +A configured, stopped macOS base is now available on native APFS development storage. Use an isolated official Tart clone for app acceptance; do not reinstall macOS for each app or test inside the clean base. Keep the working host app, shared base and older recovery images untouched. Preserve every retained candidate archive and its evidence; do not treat the shared-code updater harness, static checks or a previous candidate as final production-app acceptance. + +## 1. Prepare the release + +- Update `CHANGELOG.md` with the version and date. +- Confirm `Resources/Info.plist` and `RELEASE_NOTES.md` identify the intended candidate. The retained current candidate is build 28. Any replacement with changed signed bytes needs a new, higher numeric build and new evidence; never overwrite a retained or released archive. +- Add privacy-safe screenshots under `assets/screenshots/`. +- Confirm the working tree is clean and GitHub Actions passes. + +## 2. Build a universal app + +Install the current full Xcode release and select it with `xcode-select`. The following is the build-28 recipe, not an instruction to rebuild or replace its retained final ZIP. For a later candidate, choose a new increasing build and isolated output directories before running: + +```sh +UNIVERSAL=1 VERSION=1.0.0 BUILD_NUMBER=28 \ + CODESIGN_IDENTITY="Developer ID Application: Your Name (TEAMID)" \ + ./scripts/package_app.sh +``` + +This creates `build/Retrolemetry.app` and `dist/Retrolemetry-1.0.0.zip`. The stable bundle identifier is `io.github.SamSpring.Retrolemetry`. The app bundle contains the location usage description required by Core Location. `SMAppService.mainApp` handles Launch at Login and does not require a separate helper target. + +Sparkle 2.10.0 is pinned in `Package.swift` and `Package.resolved`. The packager uses its official SwiftPM binary artifact, embeds the intact framework with symlinks, includes its license alongside the application license and data notices, then signs Downloader.xpc, Installer.xpc, Autoupdate, Updater.app and the framework, in that order, preserving helper entitlements. It signs the outer app last with hardened runtime and a secure timestamp. Public apps must not disable library validation. CI-only ad-hoc packages are not distribution builds. + +The outer app is signed with `Resources/Retrolemetry.entitlements`, containing only `com.apple.security.personal-information.location`. Hardened Runtime requires this resource capability in addition to the Info.plist usage descriptions; it allows the normal macOS consent request, not silent authorization. Packaging and CI verify the entitlement in the actual signed app. Retained builds 21 and 22 predate this correction and must not be treated as weather-accepted release candidates. Build 23 restored native location/regional forecasts but was not accepted for successful local forecasts. Build 24 also centers/enlarges the capacity readouts and adds bounded local-forecast retries. Each candidate's actual native acceptance and release decision remain separate from earlier evidence. + +Prefer `SWIFT_SCRATCH_PATH`, `OUTPUT_DIR` and `DIST_DIR` on non-cloud local storage. For example, set `SWIFT_SCRATCH_PATH=/private/tmp/retrolemetry-release-build` when the source is cloud-synced. The packaging script resolves and embeds Sparkle from that same scratch directory. Both QA/feed scripts accept `--sparkle-tools /private/tmp/retrolemetry-release-build/artifacts/sparkle/Sparkle/bin`. Validate a fresh extraction of the final ZIP, not just the staging app; cloud sync can damage unpacked frameworks. Keep the final archive immutable. + +Verify the architecture and signature: + +```sh +lipo -archs build/Retrolemetry.app/Contents/MacOS/Retrolemetry +codesign --verify --deep --strict --verbose=2 build/Retrolemetry.app +codesign -dvvv build/Retrolemetry.app +``` + +## 3. Notarize and staple + +Reuse the existing approved notarytool Keychain profile. The example profile name below is a placeholder, not a requirement to create another account or credential. Creating credentials needs separate approval; never commit them. + +```sh +NOTARY_PROFILE="retrolemetry-notary" VERSION=1.0.0 \ + ./scripts/notarize_app.sh build/Retrolemetry.app +``` + +The script submits a temporary zip, waits for Apple's result, staples the ticket to the app, validates it, and recreates `dist/Retrolemetry-1.0.0.zip` from the stapled app. + +Run final Gatekeeper checks on the exact app and archive contents: + +```sh +spctl --assess --type execute --verbose=4 build/Retrolemetry.app +xcrun stapler validate build/Retrolemetry.app +``` + +Test first launch, location permission, preferred-display reconnection, Launch at Login, menu controls, and `killall -USR1 Retrolemetry` on a clean macOS user account. + +## 4. Prepare the signed update feed privately + +The Retrolemetry-specific signing account is `io.github.SamSpring.Retrolemetry.sparkle`. The private key lives in macOS Keychain. Only `SUPublicEDKey` is committed. Never use Sparkle's default account or a SpaceBar key/feed. Never export a key to a source checkout, cloud folder, environment variable, build archive, chat or log. + +The dedicated feed is `https://samspring.github.io/Retrolemetry/appcast.xml`, deployed with the existing `site/` GitHub Pages workflow. For the initial release, keep the signed feed empty until the public archive is verified; then publish only the reviewed signed release feed. `SURequireSignedFeed` and `SUVerifyUpdateBeforeExtraction` are enabled. A zero feed-failure expiration prevents falling back to an unverified feed even after prolonged failure. Changing any feed bytes requires re-signing. + +After notarizing/stapling the exact final ZIP, prepare a NEW private folder outside the checkout: + +```sh +python3 scripts/prepare_appcast.py /private/release/Retrolemetry-1.0.0.zip /private/release/feed-1.0.0 +``` + +Use your own existing local paths. This script does not upload anything. It verifies the archived identity, universal architectures, macOS minimum, Developer ID/hardened-runtime signature, stapled ticket, Gatekeeper acceptance and matching Keychain public key. It generates and verifies both feed and archive signatures, validates the exact enclosure URL/length/build and writes a checksum/validation receipt. macOS may request local Keychain authorization for the official Sparkle signing tools. + +For later versions, pass `--previous /private/release/previous-feed`. Keep old entries and immutable download URLs; use a strictly greater build number and a new version/archive name. Delta updates are disabled for the initial workflow. Never edit a generated feed without re-signing it. + +Back up the Retrolemetry key separately using Publisher's protected recovery workflow: export directly into a mounted password-encrypted image outside the repository/cloud staging, reopen it, reproduce an archive signature, and lock/eject it. Do not modify or reuse SpaceBar's updater-key backup. The shared Developer ID certificate may be used; the updater key may not. Keychain storage alone is not proof of an independently verified recovery backup. + +## 5. Updater acceptance + +```sh +swift test -c release --jobs 2 +python3 scripts/test_updater.py --output /private/tmp/retrolemetry-unique-updater-qa +``` + +The native harness shares `AppUpdater.swift`, uses a unique QA bundle ID, synthetic settings, temporary non-Keychain signing keys and a loopback-only allowlisted server. It invokes the real Check for Updates menu action, clicks Sparkle's normal Install Update / Install and Relaunch controls, verifies the new launch, and checks that tampered archives, wrong-key archives and wrong-key feeds leave the older signed app and layout/settings intact. It never launches the production console, accesses Finnhub/location or registers login items. Keep failed runs and logs; a timeout is incomplete, not a pass. Temporary test keys are deleted on exit. + +That harness is a real native updater test, but is not final acceptance of the exact notarized production app. Before publishing, repeat in an isolated clean Mac account/VM with the stable production bundle ID: a signed/notarized QA-only older build → the exact final candidate; equal/no-update; tampered/wrong-key rejection; relaunch; layout/typography/display preferences; synthetic Keychain data; and Launch at Login continuity. Use Sparkle's documented **guest-only** `SUFeedURL` override for an allowlisted private test feed. Never point the host's installed app at QA feeds or upload QA-only builds. Do not alter quarantine or bypass Gatekeeper. This does not authorize restarting SpaceBar's suspended VM; coordinate a separately approved guest session with Publisher. + +## 6. Publish — only after Samuel authorizes it + +- Tag the release as `v1.0.0` only after validation. +- Create the GitHub Release from `RELEASE_NOTES.md`. +- Attach the final stapled `dist/Retrolemetry-1.0.0.zip` and checksums. +- Download the public ZIP normally, verify its checksum, signature and Gatekeeper state, and confirm it is byte-identical to the appcast enclosure archive. +- Copy ONLY the reviewed signed `appcast.xml` into `site/`. Update `site/release.json` with the new final checksum and verified state, replacing stale pre-updater metadata. +- Run `swift scripts/verify_appcast.swift Resources/Info.plist site/appcast.xml` and `python3 scripts/validate_site.py --release`. +- Deploy the existing manual Pages workflow from approved `main` only after the public Release download exists. Do not upload private feed staging, QA fixtures, validation logs, certificates or keys. +- Fetch the HTTPS feed back after deployment and verify its signature and exact public archive. Private loopback QA does not prove the public endpoint is live. +- Remove the pre-publication warning from public release notes only after final acceptance and notarization are confirmed. +- Move the changelog's unreleased changes under `1.0.0` with the actual publication date. + +The site defaults to a source link and a preparation notice. Its Download button and signature/checksum wording activate only when `site/release.json` contains the verified public release metadata. Keep those flags false until the public ZIP is fetched and checked. The manual Pages workflow deploys only from `main`. diff --git a/Resources/AppIcon.png b/Resources/AppIcon.png new file mode 100644 index 0000000..a4191e3 Binary files /dev/null and b/Resources/AppIcon.png differ diff --git a/Resources/CRT.metal b/Resources/CRT.metal new file mode 100644 index 0000000..0f7c2ac --- /dev/null +++ b/Resources/CRT.metal @@ -0,0 +1,87 @@ +#include +#include "Vectors.metal" +using namespace metal; + +struct CRTParameters { + float4 color; + float4 effects; // scanlines, noise, tracking, curvature + float4 motion; // seconds, first thickness, second thickness, reserved +}; + +struct CRTVertex { + float4 position [[position]]; + float2 uv; +}; + +vertex CRTVertex crtOverlayVertex(uint index [[vertex_id]]) { + float2 uv = float2((index << 1) & 2, index & 2); + return {float4(uv * float2(2, -2) + float2(-1, 1), 0, 1), uv}; +} + +static float grainHash(uint2 pixel, uint frame) { + uint n = pixel.x * 73856093u ^ pixel.y * 19349663u ^ frame * 83492791u; + n ^= n >> 13; n *= 1274126177u; n ^= n >> 16; + return float(n & 0xffffffu) / 16777216.0; +} + +static void over(thread float4 &result, float3 rgb, float alpha) { + alpha = saturate(alpha); + result = float4(rgb * alpha, alpha) + result * (1 - alpha); +} + +static void trackingBand(thread float4 &result, float2 p, float y, float thickness, + float strength, int frame, float3 color) { + float width = max(0.5, thickness); + float height = max(18.0, width * 4.2); + float delta = p.y - y; + if (abs(delta) > height * 0.5 + 10) return; + float phase = (delta / height + 0.5) * 3; + if (phase >= 0 && phase < 1) over(result, float3(0), phase * 0.12 * strength); + if (phase >= 1 && phase < 2) { + over(result, float3(0), (2 - phase) * 0.12 * strength); + over(result, color, (phase - 1) * 0.075 * strength); + } + if (phase >= 2 && phase <= 3) over(result, color, (3 - phase) * 0.075 * strength); + over(result, color, (1 - smoothstep(width * 0.5 - 0.5, width * 0.5 + 0.5, abs(delta))) * 0.34 * strength); + for (int i = 0; i < 13; ++i) { + float start = float((i * 137 + frame * 29) % 900); + float length = float(18 + (i * 23) % 96); + float offset = float(i % 5 - 2) * max(2.5, width * 0.65); + float coverage = saturate(max(1.0, width * 0.22) * 0.5 + 0.5 - abs(delta - offset)); + if (p.x >= start && p.x < start + length) over(result, float3(1), coverage * (0.10 + float(i % 3) * 0.035) * strength); + } +} + +fragment float4 crtOverlayFragment(CRTVertex input [[stage_in]], constant CRTParameters &u [[buffer(0)]]) { + float2 p = input.uv * 2 - 1; + p *= 1 + saturate(u.effects.w) * 0.18 * float2(p.y * p.y, p.x * p.x); + if (any(abs(p) > 1)) return float4(0, 0, 0, 1); + p = (p + 1) * float2(480, 270); + float4 result = 0; + if (u.effects.x > 0.001) { + // Dark line centered on y=1 mod 4, highlight at y=2.35. + float scan = abs(fmod(p.y - 1 + 2 + 4, 4) - 2); + over(result, float3(0), saturate(1.075 - scan) * (0.12 + u.effects.x * 0.60)); + float highlight = abs(fmod(p.y - 2.35 + 2 + 4, 4) - 2); + over(result, u.color.rgb, saturate(0.775 - highlight) * (0.025 + u.effects.x * 0.14)); + } + if (u.effects.y > 0.001) { + float grain = grainHash(uint2(p), uint(u.motion.x * 14)); + if (grain > 0.9984) over(result, grain > 0.99968 ? float3(1) : u.color.rgb, 0.035 + u.effects.y * 0.26); + } + if (u.effects.z > 0.5) { + trackingBand(result, p, fmod(u.motion.x * 72, 640.0) - 50, u.motion.y, 0.78, int(u.motion.x * 9), u.color.rgb); + trackingBand(result, p, fmod(u.motion.x * 43 + 286.2, 690.0) - 75, u.motion.z, 1, int(u.motion.x * 6) + 117, u.color.rgb); + } + float vignette = saturate((distance(p, float2(480, 270)) - 385) / 205) * 0.30; + over(result, float3(0), vignette); + return result; // Premultiplied alpha for the transparent CAMetalLayer. +} + +// Output pixel -> source pixel. Keep the same map in CRTTubeGeometry for click targets. +[[ stitchable ]] float2 crtTube(float2 position, float2 size, float strength) { + float2 p = position / size * 2.0 - 1.0; + float amount = clamp(strength, 0.0, 1.0) * 0.18; + float2 source = p * (1.0 + amount * float2(p.y * p.y, p.x * p.x)); + return (source + 1.0) * size * 0.5; +} diff --git a/Resources/Info.plist b/Resources/Info.plist new file mode 100644 index 0000000..fbf1337 --- /dev/null +++ b/Resources/Info.plist @@ -0,0 +1,48 @@ + + + + + CFBundleDisplayName + Retrolemetry + CFBundleExecutable + Retrolemetry + CFBundleIdentifier + io.github.SamSpring.Retrolemetry + CFBundleInfoDictionaryVersion + 6.0 + CFBundleIconFile + AppIcon.icns + CFBundleName + Retrolemetry + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0.0 + CFBundleVersion + 28 + LSMinimumSystemVersion + 14.0 + SUFeedURL + https://samspring.github.io/Retrolemetry/appcast.xml + SUPublicEDKey + rPCCnQ2uJbuBh7gnxN4ObX9SJGh+JLGDhiy8Qr9BeF8= + SURequireSignedFeed + + SUSignedFeedFailureExpirationInterval + 0 + SUVerifyUpdateBeforeExtraction + + SUSendProfileInfo + + SUAutomaticallyUpdate + + LSUIElement + + NSHighResolutionCapable + + NSLocationUsageDescription + Retrolemetry uses your approximate location to request local weather from Open-Meteo. + NSLocationWhenInUseUsageDescription + Retrolemetry uses your approximate location to request local weather from Open-Meteo. + + diff --git a/Resources/Retrolemetry.entitlements b/Resources/Retrolemetry.entitlements new file mode 100644 index 0000000..09fb4c4 --- /dev/null +++ b/Resources/Retrolemetry.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.personal-information.location + + + diff --git a/Resources/Vectors.metal b/Resources/Vectors.metal new file mode 100644 index 0000000..a1af885 --- /dev/null +++ b/Resources/Vectors.metal @@ -0,0 +1,291 @@ +#include +using namespace metal; + +struct VectorUniforms { + float4 rect, primary, secondary, style, shape, motion, extra, globe, location, transition; +}; +struct VectorVertex { + float4 position [[position]]; + float2 source; + float4 rect [[flat]]; + float4 color [[flat]]; + float edge; + float width [[flat]]; + float2 screenSource; + float4 transition [[flat]]; +}; +struct Segment { + float2 a, b; + float4 color; + float width; +}; + +static float2 circlePoint(float2 center, float2 radius, float t) { + return center + radius * float2(cos(t), sin(t)); +} +static float3 globePoint(float longitude, float latitude, float rotation) { + return float3(cos(latitude) * sin(longitude + rotation), -sin(latitude), cos(latitude) * cos(longitude + rotation)); +} +static float2 terrainLong(int index, float depth, float2 size, constant VectorUniforms &u) { + float perspective = pow(depth, 1.58); + float energy = pow(saturate(u.motion.w), 0.72) * (0.72 + u.shape.w * 0.52); + float phase, amplitude; + int pattern = int(u.shape.y); + if (pattern == 0) { phase = depth * 6.2 + float(index) * 0.43 + u.motion.z * 0.16; amplitude = 8 + energy * 24; } + else if (pattern == 1) { phase = depth * 7.4 + float(index) * 0.43 - u.motion.z * 1.10; amplitude = 10 + energy * (18 + (sin(u.motion.z * 1.6) + 1) * 18); } + else { phase = depth * 10 + float(index) * 0.43 - u.motion.z * 1.35; amplitude = 9 + energy * 34; } + return float2(size.x * 0.5 + float(index) * size.x / 7.5 * perspective, + size.y * (0.32 + 0.68 * perspective) + sin(phase) * amplitude * (0.16 + perspective * 0.84)); +} +static float2 terrainRow(float depth, float x, float2 size, constant VectorUniforms &u) { + float perspective = pow(depth, 1.82); + float energy = pow(saturate(u.motion.w), 0.72) * (0.72 + u.shape.w * 0.52); + float phase, amplitude; + int pattern = int(u.shape.y); + if (pattern == 0) { phase = x * M_PI_F * 2.2 + depth * 6.2 + u.motion.z * 0.16; amplitude = 8 + energy * 24; } + else if (pattern == 1) { phase = x * M_PI_F * 2.6 + depth * 7.4 - u.motion.z * 1.10; amplitude = 10 + energy * (18 + (sin(u.motion.z * 1.6) + 1) * 18); } + else { phase = x * M_PI_F * 3 + depth * 10 - u.motion.z * 1.35; amplitude = 9 + energy * 34; } + return float2(size.x * 0.5 + x * size.x * (0.16 + perspective * 1.18), + size.y * (0.32 + 0.68 * perspective) + sin(phase) * amplitude * (0.18 + perspective * 0.82)); +} +static float2 lissajousPoint(float t, float echo, float2 size, float time) { + float amplitude = 108 + sin(time * 0.19) * 7; + float lag = echo * 0.025; + return size * 0.5 + float2(sin(t * 3.04 + time * 0.82 - lag) * amplitude * 2.05, + sin(t * 4.07 + time * 0.61 + sin(time * 0.16) * 0.72 - lag) * amplitude); +} + +static Segment vectorSegment(uint id, constant VectorUniforms &u, + constant float *history, constant float4 *targets, constant float4 *coastlines, constant float4 *radarMap) { + float2 size = u.rect.zw, center = size * 0.5; + float time = u.motion.x; + Segment s = {float2(0), float2(0), u.primary, 1}; + int scene = int(u.style.x); + if (scene == 0) { + float radius = min(size.x, size.y) * 0.41; + if (id < 128) { + s.a = circlePoint(center, float2(radius), float(id) / 128 * 2 * M_PI_F); + s.b = circlePoint(center, float2(radius), float(id + 1) / 128 * 2 * M_PI_F); + s.width = 1.4; + } else if ((id -= 128) < 7 * 96) { + float latitude = (float(id / 96) * 20 - 60) * M_PI_F / 180; + float scale = cos(latitude), t = float(id % 96) / 96 * 2 * M_PI_F; + float2 c = center + float2(0, sin(latitude) * radius); + s.a = circlePoint(c, float2(radius * scale, radius * 0.10 * scale), t); + s.b = circlePoint(c, float2(radius * scale, radius * 0.10 * scale), t + 2 * M_PI_F / 96); + s.color = u.secondary; + } else if ((id -= 7 * 96) < 16 * 72) { + float longitude = float(id / 72) * 2 * M_PI_F / 16 + time * 0.48; + float t = -M_PI_F * 0.5 + float(id % 72) / 72 * M_PI_F; + s.a = center + radius * float2(cos(t) * sin(longitude), sin(t)); + s.b = center + radius * float2(cos(t + M_PI_F / 72) * sin(longitude), sin(t + M_PI_F / 72)); + s.color = u.secondary; + s.color.a *= cos(longitude) >= 0 ? 0.92 : 0.46; + s.width = cos(longitude) >= 0 ? 1.05 : 0.7; + } else if ((id -= 16 * 72) < 24) { + float y = center.y - radius - 9 + float(id) / 24 * (2 * radius + 18); + s.a = float2(center.x, y); + s.b = float2(center.x, min(y + 4, center.y + radius + 9)); + s.color.a *= 0.5; + } else if ((id -= 24) < uint(u.globe.w)) { + float4 a = coastlines[id * 2], b = coastlines[id * 2 + 1]; + float3 pa = globePoint(a.x,a.y,time * 0.48), pb = globePoint(b.x,b.y,time * 0.48); + s.a = center + pa.xy * radius; s.b = center + pb.xy * radius; + bool active = (a.z == 1 && u.globe.x > 0.5) || (a.z == 2 && u.globe.y > 0.5) || (a.z == 3 && u.globe.z > 0.5); + s.color = active ? u.primary : u.secondary; + s.color.a *= pa.z >= 0 && pb.z >= 0 ? (active ? 1.0 : 0.88) : 0.14; + s.width = active ? 1.7 : 1.05; + } else { + id -= uint(u.globe.w); + uint marker = id / 32, part = id % 32; + float2 coordinates[] = {u.location.xy, float2(-74.006,40.713) * M_PI_F / 180, float2(-0.128,51.507) * M_PI_F / 180, float2(139.692,35.690) * M_PI_F / 180}; + float3 p = globePoint(coordinates[marker].x,coordinates[marker].y,time * 0.48); + float2 c = center + radius * p.xy; + float pulse = marker == 0 ? 0.80 + (sin(time * 3.0)+1)*0.25 : 1; + float r = (part < 16 ? 1.2 : 4.6) * pulse; + float t = float(part % 16) / 16 * 2 * M_PI_F; + s.a = circlePoint(c,float2(r),t); s.b = circlePoint(c,float2(r),t + 2 * M_PI_F / 16); + s.width = part < 16 ? 2.2 : 0.9; + bool active = marker == 0 ? u.location.z > 0.5 : (marker == 1 ? u.globe.x > 0.5 : marker == 2 ? u.globe.y > 0.5 : u.globe.z > 0.5); + s.color = active ? u.primary : u.secondary; + s.color.a *= part < 16 ? 1 : 0.45; + if(p.z < 0 || (marker == 0 && !active)) s.color.a = 0; + } + s.a = center + (s.a - center) * u.shape.xy; + s.b = center + (s.b - center) * u.shape.xy; + } else if (scene == 1) { + float radius = min(size.x, size.y) * 0.47; + if (id < 4 * 96) { + float r = radius * float(id / 96 + 1) / 4; + float t = float(id % 96) / 96 * 2 * M_PI_F; + s.a = circlePoint(center, float2(r), t); s.b = circlePoint(center, float2(r), t + 2 * M_PI_F / 96); + s.color = u.secondary; s.color.a *= 0.35; s.width = 1.1; + } else if ((id -= 4 * 96) < 12) { + s.a = center; s.b = circlePoint(center, float2(radius), float(id) * M_PI_F / 6); + s.color = u.secondary; s.color.a *= 0.35; s.width = 1.1; + } else if ((id -= 12) < 16) { + s.a = center; s.b = circlePoint(center, float2(radius), (u.extra.y - float(id) * 2.3) * M_PI_F / 180); + s.color.a *= 0.25 * (1 - float(id) / 16); s.width = 2; + } else if ((id -= 16) < uint(u.extra.z)) { + float4 edge = radarMap[id]; + float2 mapCenter = center + float2(size.x * 0.10,0); + s.a = mapCenter + radius * edge.xy; s.b = mapCenter + radius * edge.zw; + bool city = id >= uint(u.extra.w); + s.color = city ? u.secondary : u.primary; s.color.a *= city ? 1.0 : 0.92; + s.width = city ? 1.6 : 1.2; + } else { + id -= uint(u.extra.z); + uint index = id / 32, segment = id % 32; + float4 target = targets[index]; + float mode = u.shape.z; + float drift = mode > 2.5 ? sin(time * 0.15 + float(index)) * 15 : 0; + float angle = (mode > 2.5 ? target.y + drift : target.w) * M_PI_F / 180; + float2 c = mode > 2.5 ? circlePoint(center, float2(radius * target.x), angle) + : center + float2(size.x * 0.10,0) + radius * target.xy; + float pulse = u.shape.w > 0.5 ? 0.76 + (sin(time * 3.1 + float(index) * 0.78) + 1) * 0.25 : 1; + float r = (2.1 + target.z * 5.6) * pulse; + s.color.a *= 0.20 + target.z * 0.80; + if (segment >= 16) { + float t = float(segment - 16) / 16 * 2 * M_PI_F; + s.a = circlePoint(c, float2(r * 1.9), t); s.b = circlePoint(c, float2(r * 1.9), t + 2 * M_PI_F / 16); + s.width = 0.8; s.color.a *= u.shape.w > 0.5 ? 0.32 : 0; + } else if (mode > 0.5 && mode < 1.5) { + // Four straight diamond edges, each subdivided to match the segment count. + float2 corners[] = {float2(0,-r),float2(r,0),float2(0,r),float2(-r,0),float2(0,-r)}; + s.a = c + mix(corners[segment / 4], corners[segment / 4 + 1], float(segment % 4) / 4); + s.b = c + mix(corners[segment / 4], corners[segment / 4 + 1], float(segment % 4 + 1) / 4); + s.width = 1.4; + } else if (mode > 1.5 && mode < 2.5) { + s.a = circlePoint(c, float2(r * 1.8), angle + M_PI_F); s.b = circlePoint(c, float2(r * 1.8), angle); + if (segment == 1 || segment == 2) { + s.a = s.b; + s.b = s.a - r * float2(cos(angle + (segment == 1 ? -0.55 : 0.55)),sin(angle + (segment == 1 ? -0.55 : 0.55))); + } + s.width = 1.8; if (segment > 2) s.color.a = 0; + } else { + float t = float(segment) / 16 * 2 * M_PI_F; + s.a = circlePoint(c, float2(r * 0.5), t); s.b = circlePoint(c, float2(r * 0.5), t + 2 * M_PI_F / 16); + s.width = r; // Filled-looking contact, not a hollow ring. + } + } + s.a = center + (s.a - center) * u.shape.xy; + s.b = center + (s.b - center) * u.shape.xy; + } else { + uint gridCount = u.shape.x > 0.5 ? 2625 : 26; + if (id < gridCount) { + if (u.shape.x < 0.5) { + if (id < 17) { float x = float(id) / 16 * size.x; s.a = float2(x,0); s.b = float2(x,size.y); } + else { float y = float(id - 17) / 8 * size.y; s.a = float2(0,y); s.b = float2(size.x,y); } + s.color = u.secondary; s.color.a *= 0.72; s.width = 0.8; + } else if (id < 1344) { + int index = int(id / 64) - 10; + float depth = float(id % 64) / 64; + s.a = terrainLong(index, depth, size, u); s.b = terrainLong(index, depth + 1.0 / 64, size, u); + s.color = u.secondary; s.color.a *= 0.78; s.width = 0.9; + } else if (id < 2624) { + uint rowID = id - 1344; + float travel = int(u.shape.y) == 1 ? sin(u.motion.z * 0.7) * 0.025 : u.motion.y * (int(u.shape.y) == 2 ? 0.45 : 1); + float depth = fract(float(rowID / 80) / 16 - travel), x = float(rowID % 80) / 80 * 2 - 1; + float perspective = pow(depth, 1.82); + s.a = terrainRow(depth,x,size,u); s.b = terrainRow(depth,x + 2.0 / 80,size,u); + s.color.a *= 0.38 + perspective * 0.56; s.width = 0.8 + perspective; + } else { + s.a = float2(0,size.y * 0.32); s.b = float2(size.x,size.y * 0.32); + s.color = u.secondary; s.color.a *= 0.98; s.width = 1.45; + } + } else { + id -= gridCount; + if (u.shape.z > 0.5) { + float topInset = min(size.y * 0.30, max(42.0, 13 * u.extra.x + 26)); + float height = max(0.0, min(size.y * 0.26, size.y * 0.32 - topInset)); + if (id >= 191) { + id -= 191; + float2 point = float2(float(id) / 95 * size.x, size.y * 0.32 - saturate(history[id]) * height); + s.a = point - float2(0.1,0); s.b = point + float2(0.1,0); s.width = 4; + bool isolated = (id == 0 || history[id-1] < 0) && (id == 95 || history[id+1] < 0); + if (history[id] < 0 || !isolated) s.color.a = 0; + } else if (id == 95) { + s.a = float2(0,size.y * 0.32); s.b = float2(size.x,size.y * 0.32); s.color = u.secondary; s.width = 1.3; + } else { + if (id >= 96) { id -= 96; s.width = -1; s.color.a *= 0.13; } + else { s.width = 1.8; } + s.a = float2(float(id) / 95 * size.x, size.y * 0.32 - saturate(history[id]) * height); + s.b = float2(float(id + 1) / 95 * size.x, size.y * 0.32 - saturate(history[id + 1]) * height); + if (history[id] < 0 || history[id + 1] < 0) s.color.a = 0; + } + } else { + float echo = 3 - float(id / 360), t = float(id % 360) / 360 * 2 * M_PI_F; + s.a = lissajousPoint(t,echo,size,time); s.b = lissajousPoint(t + 2 * M_PI_F / 360,echo,size,time); + s.color.a *= echo == 0 ? 1 : 0.11 + (3 - echo) * 0.075; s.width = echo == 0 ? 1.5 : 0.8; + } + } + } + return s; +} + +vertex VectorVertex consoleVectorVertex(uint id [[vertex_id]], uint instance [[instance_id]], + constant VectorUniforms &u [[buffer(0)]], + constant float *history [[buffer(1)]], + constant float4 *targets [[buffer(2)]], + constant float4 *coastlines [[buffer(3)]], + constant float4 *radarMap [[buffer(4)]]) { + Segment s = vectorSegment(id / 6,u,history,targets,coastlines,radarMap); + bool area = s.width < 0; + // Draw the broad glow first, then the bright center; no blur render passes. + if (u.style.z > 0) { + if (area && instance != 2) s.color.a = 0; + else if (instance == 0) { s.width += 7; s.color.a *= 0.025 * u.style.z; } + else if (instance == 1) { s.width += 3; s.color.a *= 0.06 * u.style.z; } + } + float2 direction = s.b - s.a; + float length = max(0.001, metal::length(direction)); + float2 normal = float2(-direction.y, direction.x) / length; + uint corner = id % 6; + bool end = corner == 1 || corner == 2 || corner == 4; + float side = corner == 0 || corner == 1 || corner == 3 ? -1 : 1; + float edge = side * (s.width * 0.5 + 0.5); + float2 source = (end ? s.b : s.a) + normal * edge + u.rect.xy; + if (area) { + source = (end ? s.b : s.a) + u.rect.xy; + if (side > 0) source.y = u.rect.y + u.rect.w * 0.32; + edge = 0; s.width = 0; + } + float2 screenSource = source; + if(u.transition.x >= 0) { + float progress = u.transition.x; + bool incoming = u.transition.z > 0.5; + if(u.transition.y < 0.5) { + screenSource.x += u.transition.w * 960 * (incoming ? 1-progress : -progress); + } else if(u.transition.y > 1.5) { + float halfProgress = incoming ? saturate((progress - 0.48)/0.52) : saturate(progress/0.52); + float scale = max(0.018,incoming ? halfProgress : 1-halfProgress); + screenSource = (screenSource-float2(480,270)) * float2(1+(1-scale)*0.018,scale) + float2(480,270); + screenSource.x += sin(progress*M_PI_F*15)*(1-scale)*11; + if(incoming ? progress < 0.48 : progress >= 0.52) s.color.a = 0; + } + } + float2 p = screenSource / float2(480,270) - 1; + float2 original = p; + float curvature = saturate(u.style.y) * 0.18; + for (int i = 0; i < 8; ++i) { + p.x = original.x / (1 + curvature * p.y * p.y); + p.y = original.y / (1 + curvature * p.x * p.x); + } + VectorVertex v; + v.position = float4(p * float2(1,-1),0,1); + v.source = source; v.rect = u.rect; v.color = s.color; v.edge = edge; v.width = s.width; + v.screenSource = screenSource; v.transition = u.transition; + return v; +} + +fragment float4 consoleVectorFragment(VectorVertex in [[stage_in]]) { + if (any(in.source < in.rect.xy) || any(in.source > in.rect.xy + in.rect.zw)) discard_fragment(); + if(in.transition.x >= 0 && in.transition.y > 0.5 && in.transition.y < 1.5) { + float boundary = in.transition.x * (960+94) - 94 + 94 * in.screenSource.y / 540; + bool revealed = in.transition.w > 0 ? in.screenSource.x <= boundary : in.screenSource.x >= 960-boundary; + if(revealed != (in.transition.z > 0.5)) discard_fragment(); + } + float coverage = in.width == 0 ? 1 : saturate(in.width * 0.5 + 0.5 - abs(in.edge)); + float alpha = coverage * in.color.a; + return float4(in.color.rgb * alpha, alpha); +} diff --git a/Sources/DockTelemetry/ConsoleView.swift b/Sources/DockTelemetry/ConsoleView.swift deleted file mode 100644 index 5652c53..0000000 --- a/Sources/DockTelemetry/ConsoleView.swift +++ /dev/null @@ -1,802 +0,0 @@ -import AppKit -import SwiftUI -import Combine - -private var mono: Font { consoleFont(14, weight: .medium) } - -enum ConsoleScene: Int, CaseIterable { - case system, radar, signal, fullMetrics - - var title: String { - switch self { - case .system: "SYSTEM TELEMETRY" - case .radar: "SECTOR SCAN" - case .signal: "SIGNAL ANALYSIS" - case .fullMetrics: "LIVE SYSTEM METRICS" - } - } -} - -struct ConsoleView: View { - @StateObject private var telemetry = TelemetryModel() - @StateObject private var weather = WeatherModel() - @AppStorage("DockTelemetry.cycleDuration") private var cycleDuration = 24.0 - @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true - @AppStorage("DockTelemetry.crtEnabled") private var crtEnabled = true - @AppStorage("DockTelemetry.bloomStrength") private var bloomStrength = 0.72 - @AppStorage("DockTelemetry.scanlineStrength") private var scanlineStrength = 0.22 - @AppStorage("DockTelemetry.noiseStrength") private var noiseStrength = 0.32 - @AppStorage("DockTelemetry.vhsTrackingEnabled") private var vhsTrackingEnabled = true - @AppStorage("DockTelemetry.phosphorBackgroundTint") private var phosphorBackgroundTint = 0.12 - @AppStorage("DockTelemetry.visualStyle") private var visualStyleRaw = ConsoleStyle.phosphor.rawValue - @ObservedObject private var layouts = LayoutStore.shared - @State private var activeScene: ConsoleScene = .system - @State private var nextSwitch = Date().addingTimeInterval(24) - private let sceneClock = Timer.publish(every: 0.25, on: .main, in: .common).autoconnect() - - var body: some View { - let style = ConsoleStyle(rawValue: visualStyleRaw) ?? .phosphor - ThemeRuntime.palette = style.palette - FontRuntime.scale = layouts.fontScale - FontRuntime.secondaryScale = layouts.secondaryFontScale - return TimelineView(.animation(minimumInterval: 1.0 / 60.0)) { timeline in - let elapsed = timeline.date.timeIntervalSinceReferenceDate - - ZStack { - ConsoleBackground(style: style, phosphorTintStrength: phosphorBackgroundTint) - sceneView(activeScene, time: elapsed) - .id(activeScene) - .transition(.asymmetric( - insertion: .move(edge: .trailing).combined(with: .opacity), - removal: .move(edge: .leading).combined(with: .opacity) - )) - .compositingGroup() - .shadow( - color: crtEnabled ? phosphor.opacity(0.24 * bloomStrength) : .clear, - radius: 2.5 + 3.5 * bloomStrength - ) - if crtEnabled { - CRTOverlay( - scanlineStrength: scanlineStrength, - noiseStrength: noiseStrength, - vhsTrackingEnabled: vhsTrackingEnabled, - time: elapsed - ) - } - HorizontalScrollCapture { direction in - moveScene(direction) - } - .frame(width: 960, height: 540) - } - .animation(.smooth(duration: 0.9), value: activeScene) - .frame(width: 960, height: 540) - .foregroundStyle(phosphor) - .font(mono) - .clipped() - .focusable() - .onKeyPress { press in - switch press.characters { - case "1": select(.system) - case "2": select(.radar) - case "3": select(.signal) - case "4": select(.fullMetrics) - case "0", "a", "A": - if automaticCycleEnabled { - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - default: return .ignored - } - return .handled - } - } - .onAppear { - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - .onReceive(sceneClock) { now in - guard automaticCycleEnabled, now >= nextSwitch else { return } - withAnimation(.smooth(duration: 0.9)) { - activeScene = ConsoleScene(rawValue: (activeScene.rawValue + 1) % ConsoleScene.allCases.count) ?? .system - } - nextSwitch = now.addingTimeInterval(cycleDuration) - } - .onChange(of: cycleDuration) { - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - .onChange(of: automaticCycleEnabled) { - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - } - - private func select(_ scene: ConsoleScene) { - withAnimation(.smooth(duration: 0.9)) { activeScene = scene } - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - - private func moveScene(_ direction: Int) { - let count = ConsoleScene.allCases.count - let next = (activeScene.rawValue + direction + count) % count - withAnimation(.smooth(duration: 0.9)) { - activeScene = ConsoleScene(rawValue: next) ?? .system - } - nextSwitch = Date().addingTimeInterval(cycleDuration) - } - - @ViewBuilder - private func sceneView(_ scene: ConsoleScene, time: Double) -> some View { - switch scene { - case .system: - SystemScene(snapshot: telemetry.snapshot, history: telemetry.cpuHistory, time: time) - case .radar: - RadarScene( - weather: weather.snapshot, - time: time - ) - case .signal: - SignalScene( - snapshot: telemetry.snapshot, - cpuHistory: telemetry.cpuHistory, - memoryHistory: telemetry.memoryHistory, - networkHistory: telemetry.networkHistory, - time: time - ) - case .fullMetrics: - FullMetricsScene( - snapshot: telemetry.snapshot, - cpuHistory: telemetry.cpuHistory, - memoryHistory: telemetry.memoryHistory, - networkHistory: telemetry.networkHistory, - time: time - ) - } - } -} - -struct HorizontalScrollCapture: NSViewRepresentable { - let onScroll: (Int) -> Void - - func makeNSView(context: Context) -> HorizontalScrollView { - let view = HorizontalScrollView() - view.onScroll = onScroll - return view - } - - func updateNSView(_ nsView: HorizontalScrollView, context: Context) { - nsView.onScroll = onScroll - } -} - -final class HorizontalScrollView: NSView { - var onScroll: ((Int) -> Void)? - private var accumulated: CGFloat = 0 - private var lastSwitch = Date.distantPast - - override var acceptsFirstResponder: Bool { false } - - override func scrollWheel(with event: NSEvent) { - let horizontal = event.scrollingDeltaX - guard abs(horizontal) > 0.01 else { - super.scrollWheel(with: event) - return - } - - accumulated += horizontal - let threshold: CGFloat = event.hasPreciseScrollingDeltas ? 34 : 1 - guard abs(accumulated) >= threshold, - Date().timeIntervalSince(lastSwitch) > 0.45 else { return } - - let direction = accumulated < 0 ? 1 : -1 - accumulated = 0 - lastSwitch = Date() - onScroll?(direction) - } -} - -struct FrameChrome: View { - let title: String - let section: String - let time: Double - @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true - - var body: some View { - ZStack { - Rectangle().stroke(phosphor.opacity(0.72), lineWidth: 1) - .padding(14) - VStack(spacing: 0) { - HStack { - Text("CG//DOCK NODE 01") - Spacer() - Text(title) - Spacer() - Text("LINK \(Int(time * 2).isMultiple(of: 2) ? "●" : "○") ACTIVE") - } - .font(consoleSecondaryFont(13, weight: .bold)) - .padding(.horizontal, 26) - .frame(height: 42) - Rectangle().fill(phosphor.opacity(0.6)).frame(height: 1).padding(.horizontal, 14) - Spacer() - HStack { - Text("MODE \(section)") - Spacer() - Text(automaticCycleEnabled - ? "AUTO CYCLE // 1–4 SELECT // 0 AUTO" - : "AUTO OFF // 1–4 SELECT // H-SCROLL") - } - .font(consoleSecondaryFont(11, weight: .semibold)) - .padding(.horizontal, 26) - .frame(height: 30) - } - } - .allowsHitTesting(false) - } -} - -struct SystemScene: View { - let snapshot: TelemetrySnapshot - let history: [Double] - let time: Double - - var body: some View { - ZStack { - FrameChrome(title: "SYSTEM TELEMETRY", section: "SYS", time: time) - LayoutModuleContainer(scene: .system, module: "meters") { - VStack(alignment: .leading, spacing: 14) { - Text("PRIMARY LOAD CHANNELS").font(consoleSecondaryFont(13, weight: .bold)) - SegmentedMeter(label: "CPU", value: snapshot.cpu, detail: percent(snapshot.cpu)) - SegmentedMeter(label: "MEM", value: snapshot.memory, detail: percent(snapshot.memory)) - SegmentedMeter(label: "DSK", value: snapshot.disk, detail: percent(snapshot.disk)) - SegmentedMeter(label: "NET", value: min(1, (snapshot.networkIn + snapshot.networkOut) / 12_000_000), detail: byteRate(snapshot.networkIn)) - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - } - LayoutModuleContainer(scene: .system, module: "readouts") { - HStack(spacing: 18) { - Readout(label: "UPTIME", value: snapshot.uptime.compactUptime) - Readout(label: "NET OUT", value: byteRate(snapshot.networkOut)) - } - } - LayoutModuleContainer(scene: .system, module: "history") { - LineGraph(values: history) - .overlay(alignment: .topLeading) { - Text("CPU HISTORY // 96 SEC").font(consoleSecondaryFont(11, weight: .bold)).padding(7) - } - } - LayoutModuleContainer(scene: .system, module: "globe") { - WireGlobe(time: time) - } - LayoutModuleContainer(scene: .system, module: "globeStatus") { - VStack(spacing: 10) { - HStack(spacing: 10) { - PulseIndicator(label: "CORE", active: true, time: time) - PulseIndicator(label: "I/O", active: snapshot.networkIn > 100, time: time + 0.4) - PulseIndicator(label: "THERM", active: true, time: time + 0.8) - } - Text(String(format: "LOAD %.2f %.2f %.2f", snapshot.load.0, snapshot.load.1, snapshot.load.2)) - .font(consoleSecondaryFont(11)) - } - } - } - } - - private func percent(_ value: Double) -> String { String(format: "%03.0f%%", value * 100) } -} - -struct FullMetricsScene: View { - let snapshot: TelemetrySnapshot - let cpuHistory: [Double] - let memoryHistory: [Double] - let networkHistory: [Double] - let time: Double - - var body: some View { - ZStack { - FrameChrome(title: "LIVE SYSTEM METRICS", section: "DAT", time: time) - LayoutModuleContainer(scene: .fullMetrics, module: "metricCPU") { LargeMetricTile(label: "CPU LOAD", value: percent(snapshot.cpu), level: snapshot.cpu) } - LayoutModuleContainer(scene: .fullMetrics, module: "metricMemory") { LargeMetricTile(label: "MEMORY", value: percent(snapshot.memory), level: snapshot.memory) } - LayoutModuleContainer(scene: .fullMetrics, module: "metricDisk") { LargeMetricTile(label: "DISK USED", value: percent(snapshot.disk), level: snapshot.disk) } - LayoutModuleContainer(scene: .fullMetrics, module: "metricNetwork") { LargeMetricTile(label: "NETWORK RX", value: byteRate(snapshot.networkIn), level: min(1, snapshot.networkIn / 12_000_000)) } - LayoutModuleContainer(scene: .fullMetrics, module: "graphCPU") { LargeDataGraph(label: "CPU // 96 SEC", value: percent(snapshot.cpu), values: cpuHistory) } - LayoutModuleContainer(scene: .fullMetrics, module: "graphMemory") { LargeDataGraph(label: "MEMORY // 96 SEC", value: percent(snapshot.memory), values: memoryHistory) } - LayoutModuleContainer(scene: .fullMetrics, module: "graphNetwork") { LargeDataGraph(label: "NETWORK // 96 SEC", value: byteRate(snapshot.networkIn), values: networkHistory) } - LayoutModuleContainer(scene: .fullMetrics, module: "statusUptime") { LargeStatusReadout(label: "UPTIME", value: snapshot.uptime.compactUptime) } - LayoutModuleContainer(scene: .fullMetrics, module: "statusLoad") { LargeStatusReadout(label: "LOAD 1 / 5 / 15", value: String(format: "%.1f %.1f %.1f", snapshot.load.0, snapshot.load.1, snapshot.load.2)) } - LayoutModuleContainer(scene: .fullMetrics, module: "statusTX") { LargeStatusReadout(label: "NETWORK TX", value: byteRate(snapshot.networkOut)) } - } - } - - private func percent(_ value: Double) -> String { - String(format: "%03.0f%%", value * 100) - } -} - -struct LargeMetricTile: View { - let label: String - let value: String - let level: Double - - var body: some View { - VStack(alignment: .leading, spacing: 8) { - Text(label) - .font(consoleSecondaryFont(13, weight: .bold)) - Text(value) - .font(consoleFont(value.count > 7 ? 23 : 31, weight: .bold)) - .lineLimit(1) - .minimumScaleFactor(0.72) - HStack(spacing: 3) { - ForEach(0..<12, id: \.self) { index in - Rectangle() - .fill(Double(index) / 12 < level ? phosphor : dimPhosphor) - } - } - .frame(height: 13) - } - .padding(12) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.2)) - } -} - -struct LargeDataGraph: View { - let label: String - let value: String - let values: [Double] - - var body: some View { - LineGraph(values: values) - .overlay(alignment: .top) { - HStack(spacing: 8) { - Text(label) - .font(consoleSecondaryFont(13, weight: .bold)) - .lineLimit(1) - .minimumScaleFactor(0.55) - Spacer(minLength: 4) - Text(value) - .font(consoleFont(18, weight: .bold)) - .lineLimit(1) - .minimumScaleFactor(0.60) - } - .padding(9) - } - } -} - -struct LargeStatusReadout: View { - let label: String - let value: String - - var body: some View { - VStack(alignment: .leading, spacing: 5) { - Text(label) - .font(consoleSecondaryFont(11, weight: .bold)) - .foregroundStyle(dimPhosphor) - Text(value) - .font(consoleFont(20, weight: .bold)) - .lineLimit(1) - .minimumScaleFactor(0.75) - } - .padding(.horizontal, 12) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.2)) - } -} - -struct SegmentedMeter: View { - let label: String - let value: Double - let detail: String - - var body: some View { - HStack(spacing: 8) { - Text(label).frame(width: 34, alignment: .leading) - HStack(spacing: 3) { - ForEach(0..<20, id: \.self) { index in - Rectangle() - .fill(Double(index) / 20 < value ? phosphor : dimPhosphor) - .frame(width: 17, height: 17) - } - } - Text(detail).frame(width: 76, alignment: .trailing) - } - .font(consoleSecondaryFont(12, weight: .bold)) - } -} - -struct Readout: View { - let label: String - let value: String - - var body: some View { - VStack(alignment: .leading, spacing: 4) { - Text(label).font(consoleSecondaryFont(9)).foregroundStyle(dimPhosphor) - Text(value).font(consoleFont(15, weight: .semibold)) - } - .padding(9) - .frame(maxWidth: .infinity, alignment: .leading) - .overlay(Rectangle().stroke(dimPhosphor, lineWidth: 1)) - } -} - -struct PulseIndicator: View { - let label: String - let active: Bool - let time: Double - - var body: some View { - HStack(spacing: 5) { - Circle().fill(active && sin(time * 4) > -0.2 ? phosphor : dimPhosphor).frame(width: 7, height: 7) - Text(label).font(consoleSecondaryFont(9)) - } - } -} - -struct LineGraph: View { - let values: [Double] - var body: some View { - Canvas { context, size in - drawGrid(context: &context, size: size, columns: 12, rows: 4) - guard values.count > 1 else { return } - var path = Path() - for (index, value) in values.enumerated() { - let x = size.width * CGFloat(index) / CGFloat(values.count - 1) - let y = size.height - CGFloat(value) * (size.height - 12) - 6 - index == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) - } - context.stroke(path, with: .color(phosphor), lineWidth: 2.2) - } - .overlay(Rectangle().stroke(dimPhosphor, lineWidth: 1)) - } -} - -struct WireGlobe: View { - let time: Double - @AppStorage("DockTelemetry.globeWidthCorrection") private var widthCorrection = 1.10 - @AppStorage("DockTelemetry.globeHeightCorrection") private var heightCorrection = 1.00 - - var body: some View { - Canvas { context, size in - let center = CGPoint(x: size.width / 2, y: size.height / 2) - let radius = min(size.width, size.height) * 0.41 - let rotation = time * 0.48 - context.stroke(Path(ellipseIn: CGRect(x: center.x-radius, y: center.y-radius, width: radius*2, height: radius*2)), with: .color(phosphor), lineWidth: 1.4) - - for latitude in stride(from: -60.0, through: 60.0, by: 20) { - let scale = CGFloat(cos(latitude * .pi / 180)) - let y = center.y + CGFloat(sin(latitude * .pi / 180)) * radius - let rect = CGRect(x: center.x - radius * scale, y: y - radius * 0.10 * scale, width: radius * 2 * scale, height: radius * 0.20 * scale) - context.stroke(Path(ellipseIn: rect), with: .color(dimPhosphor), lineWidth: 1) - } - for longitude in stride(from: 0.0, to: Double.pi, by: Double.pi / 8) { - var front = Path() - var back = Path() - var frontStarted = false - var backStarted = false - for step in 0...72 { - let latitude = -Double.pi / 2 + Double(step) / 72 * Double.pi - let longitudeRotated = longitude + rotation - let x = cos(latitude) * sin(longitudeRotated) - let y = sin(latitude) - let z = cos(latitude) * cos(longitudeRotated) - let projected = CGPoint(x: center.x + CGFloat(x) * radius, y: center.y + CGFloat(y) * radius) - if z >= 0 { - frontStarted ? front.addLine(to: projected) : front.move(to: projected) - frontStarted = true; backStarted = false - } else { - backStarted ? back.addLine(to: projected) : back.move(to: projected) - backStarted = true; frontStarted = false - } - } - context.stroke(back, with: .color(dimPhosphor.opacity(0.34)), lineWidth: 0.7) - context.stroke(front, with: .color(dimPhosphor.opacity(0.92)), lineWidth: 1.05) - } - - // An asymmetric orbital marker makes the continuous rotation direction perceptible. - let markerLongitude = rotation + 0.65 - let markerLatitude = 0.34 - let markerX = cos(markerLatitude) * sin(markerLongitude) - let markerY = sin(markerLatitude) - let markerZ = cos(markerLatitude) * cos(markerLongitude) - let marker = CGPoint(x: center.x + CGFloat(markerX) * radius, y: center.y + CGFloat(markerY) * radius) - context.fill(Path(ellipseIn: CGRect(x: marker.x - 3, y: marker.y - 3, width: 6, height: 6)), with: .color(phosphor.opacity(markerZ >= 0 ? 1 : 0))) - var axis = Path() - axis.move(to: CGPoint(x: center.x, y: center.y-radius-12)); axis.addLine(to: CGPoint(x: center.x, y: center.y+radius+12)) - context.stroke(axis, with: .color(phosphor.opacity(0.5)), style: StrokeStyle(lineWidth: 1, dash: [4, 5])) - } - .scaleEffect(x: widthCorrection, y: heightCorrection, anchor: .center) - } -} - -struct RadarScene: View { - let weather: WeatherSnapshot - let time: Double - @AppStorage("DockTelemetry.radarWidthCorrection") private var radarWidthCorrection = 1.10 - @AppStorage("DockTelemetry.radarHeightCorrection") private var radarHeightCorrection = 0.9254 - var body: some View { - ZStack { - FrameChrome(title: "LOCAL WEATHER RADAR", section: "WX", time: time) - LayoutModuleContainer(scene: .radar, module: "radar") { - Canvas { context, size in - let center = CGPoint(x: size.width / 2, y: size.height / 2) - let radius = min(size.width, size.height) * 0.47 - for ring in 1...4 { - let r = radius * CGFloat(ring) / 4 - context.stroke(Path(ellipseIn: CGRect(x: center.x-r, y: center.y-r, width: r*2, height: r*2)), with: .color(dimPhosphor.opacity(0.82)), lineWidth: 1.1) - } - for angle in stride(from: 0.0, to: 360.0, by: 30) { - let p = point(center: center, radius: radius, angle: angle) - var line = Path(); line.move(to: center); line.addLine(to: p) - context.stroke(line, with: .color(dimPhosphor.opacity(0.82)), lineWidth: 1.1) - } - let sweep = time * 42 - for trail in 0..<16 { - let angle = sweep - Double(trail) * 2.3 - var line = Path(); line.move(to: center); line.addLine(to: point(center: center, radius: radius, angle: angle)) - context.stroke(line, with: .color(phosphor.opacity(0.75 * (1 - Double(trail)/16))), lineWidth: 2) - } - for index in 0..<7 { - let angle = Double(index * 53) + sin(time * 0.15 + Double(index)) * 15 - let r = radius * (0.25 + Double((index * 37) % 65) / 100) - let p = point(center: center, radius: r, angle: angle) - context.fill(Path(ellipseIn: CGRect(x: p.x-3, y: p.y-3, width: 6, height: 6)), with: .color(phosphor)) - } - } - .scaleEffect(x: radarWidthCorrection, y: radarHeightCorrection, anchor: .center) - } - LayoutModuleContainer(scene: .radar, module: "weatherHeader") { - HStack(alignment: .top) { - VStack(alignment: .leading, spacing: 3) { - Text(weather.location) - .font(consoleSecondaryFont(11, weight: .bold)) - .foregroundStyle(dimPhosphor) - Text(weather.condition) - .font(consoleFont(18, weight: .bold)) - } - Spacer() - Text(String(format: "%.0f°C", weather.temperature)) - .font(consoleFont(40, weight: .bold)) - } - } - LayoutModuleContainer(scene: .radar, module: "weatherStats") { - HStack(spacing: 8) { - WeatherReadout(label: "FEELS", value: String(format: "%.0f°C", weather.apparentTemperature)) - WeatherReadout(label: "HUMID", value: String(format: "%.0f%%", weather.humidity * 100)) - WeatherReadout(label: "WIND", value: String(format: "%.0f KM/H", weather.windSpeed)) - WeatherReadout(label: "RAIN", value: String(format: "%.1f MM", weather.precipitation)) - } - } - LayoutModuleContainer(scene: .radar, module: "temperature") { - MiniTrace(label: "TEMPERATURE // NEXT 12 HOURS", values: weather.temperatureForecast) - } - LayoutModuleContainer(scene: .radar, module: "precipitation") { - MiniTrace(label: "PRECIPITATION CHANCE // NEXT 12 HOURS", values: weather.precipitationForecast) - } - LayoutModuleContainer(scene: .radar, module: "weatherStatus") { - HStack { - Text(weather.status) - Spacer() - Text("RADAR SWEEP 042°/S") - } - .font(consoleSecondaryFont(10, weight: .bold)) - } - } - } -} - -struct WeatherReadout: View { - let label: String - let value: String - - var body: some View { - VStack(alignment: .leading, spacing: 4) { - Text(label) - .font(consoleSecondaryFont(10, weight: .bold)) - .foregroundStyle(dimPhosphor) - Text(value) - .font(consoleFont(15, weight: .bold)) - .lineLimit(1) - .minimumScaleFactor(0.7) - } - .padding(8) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1)) - } -} - -struct SignalScene: View { - let snapshot: TelemetrySnapshot - let cpuHistory: [Double] - let memoryHistory: [Double] - let networkHistory: [Double] - let time: Double - var body: some View { - ZStack { - FrameChrome(title: "SIGNAL ANALYSIS", section: "SIG", time: time) - LayoutModuleContainer(scene: .signal, module: "scope") { - Canvas { context, size in - let rect = CGRect(origin: .zero, size: size) - context.stroke(Path(rect), with: .color(dimPhosphor), lineWidth: 1) - drawGrid(context: &context, size: rect.size, columns: 16, rows: 8, origin: rect.origin, strength: 0.72) - let amplitude = 108 + sin(time * 0.19) * 7 - let frequencyA = 3.04 - let frequencyB = 4.07 - let continuousPhase = sin(time * 0.16) * 0.72 - for echo in stride(from: 3, through: 0, by: -1) { - var path = Path() - let lag = Double(echo) * 0.025 - for i in 0...360 { - let t = Double(i) / 360 * Double.pi * 2 - let x = rect.midX + CGFloat(sin(t * frequencyA + time * 0.82 - lag)) * amplitude * 2.05 - let y = rect.midY + CGFloat(sin(t * frequencyB + time * 0.61 + continuousPhase - lag)) * amplitude - i == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) - } - let opacity = echo == 0 ? 1.0 : 0.11 + Double(3 - echo) * 0.075 - context.stroke(path, with: .color(phosphor.opacity(opacity)), lineWidth: echo == 0 ? 1.5 : 0.8) - } - } - } - LayoutModuleContainer(scene: .signal, module: "signalHeader") { - HStack { - Text(String(format: "CH A CPU %03.0f%%", snapshot.cpu * 100)) - Spacer() - Text(String(format: "CH B MEM %03.0f%%", snapshot.memory * 100)) - Spacer() - Text("PHASE \(Int(time*22)%360)°") - } - .font(consoleSecondaryFont(13, weight: .bold)) - } - LayoutModuleContainer(scene: .signal, module: "cpuTrace") { MiniTrace(label: "CPU", values: cpuHistory) } - LayoutModuleContainer(scene: .signal, module: "memoryTrace") { MiniTrace(label: "MEMORY", values: memoryHistory) } - LayoutModuleContainer(scene: .signal, module: "networkTrace") { MiniTrace(label: "NETWORK", values: networkHistory) } - LayoutModuleContainer(scene: .signal, module: "ioReadout") { Readout(label: "I/O RX / TX", value: "\(byteRate(snapshot.networkIn)) / \(byteRate(snapshot.networkOut))") } - } - } -} - -struct CompactMeter: View { - let label: String - let value: Double - - var body: some View { - HStack(spacing: 5) { - Text(label).frame(width: 38, alignment: .leading) - HStack(spacing: 2) { - ForEach(0..<10, id: \.self) { index in - Rectangle() - .fill(Double(index) / 10 < value ? phosphor : dimPhosphor) - .frame(height: 12) - } - } - Text(String(format: "%02.0f", value * 100)).frame(width: 30, alignment: .trailing) - } - .font(consoleSecondaryFont(12, weight: .bold)) - } -} - -struct MiniTrace: View { - let label: String - let values: [Double] - - var body: some View { - Canvas { context, size in - guard values.count > 1 else { return } - var path = Path() - for (index, value) in values.enumerated() { - let x = size.width * CGFloat(index) / CGFloat(values.count - 1) - let y = size.height - CGFloat(value) * (size.height - 14) - 3 - index == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) - } - context.stroke(path, with: .color(phosphor), lineWidth: 1.5) - } - .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1.2)) - .overlay(alignment: .topLeading) { - Text(label) - .font(consoleSecondaryFont(11, weight: .bold)) - .padding(6) - } - } -} - -struct CRTOverlay: View { - let scanlineStrength: Double - let noiseStrength: Double - let vhsTrackingEnabled: Bool - let time: Double - - var body: some View { - ZStack { - Canvas(opaque: false, rendersAsynchronously: true) { context, size in - if scanlineStrength > 0.001 { - let darkOpacity = 0.12 + scanlineStrength * 0.60 - let highlightOpacity = 0.025 + scanlineStrength * 0.14 - for y in stride(from: 1.0, through: size.height, by: 4) { - var darkLine = Path() - darkLine.move(to: CGPoint(x: 0, y: y)) - darkLine.addLine(to: CGPoint(x: size.width, y: y)) - context.stroke(darkLine, with: .color(.black.opacity(darkOpacity)), lineWidth: 1.15) - - var highlight = Path() - highlight.move(to: CGPoint(x: 0, y: y + 1.35)) - highlight.addLine(to: CGPoint(x: size.width, y: y + 1.35)) - context.stroke(highlight, with: .color(phosphor.opacity(highlightOpacity)), lineWidth: 0.55) - } - } - - if noiseStrength > 0.001 { - let frame = Int(time * 14) - let grainOpacity = 0.035 + noiseStrength * 0.26 - for index in 0..<820 { - let hash = (index &* 73_856_093) ^ (frame &* 19_349_663) - let positive = hash & 0x7fff_ffff - let x = CGFloat((positive &* 37) % 960) - let y = CGFloat((positive &* 91 + index &* 17) % 540) - let width: CGFloat = index.isMultiple(of: 7) ? 2.5 : 1 - context.fill( - Path(CGRect(x: x, y: y, width: width, height: 1)), - with: .color((index.isMultiple(of: 5) ? Color.white : phosphor).opacity(grainOpacity)) - ) - } - } - - if vhsTrackingEnabled { - let travel = (time * 72).truncatingRemainder(dividingBy: size.height + 100) - let y = CGFloat(travel) - 50 - let band = CGRect(x: 0, y: y - 14, width: size.width, height: 29) - context.fill( - Path(band), - with: .linearGradient( - Gradient(colors: [.clear, .black.opacity(0.17), phosphor.opacity(0.10), .clear]), - startPoint: CGPoint(x: 0, y: y - 14), - endPoint: CGPoint(x: 0, y: y + 15) - ) - ) - - var trackingEdge = Path() - trackingEdge.move(to: CGPoint(x: 0, y: y)) - trackingEdge.addLine(to: CGPoint(x: size.width, y: y)) - context.stroke(trackingEdge, with: .color(phosphor.opacity(0.34)), lineWidth: 1.15) - - let segmentFrame = Int(time * 9) - for index in 0..<13 { - let start = CGFloat((index * 137 + segmentFrame * 29) % 900) - let length = CGFloat(18 + (index * 23) % 96) - let offset = CGFloat((index % 5) - 2) * 2.5 - context.fill( - Path(CGRect(x: start, y: y + offset, width: length, height: 1)), - with: .color(Color.white.opacity(0.10 + Double(index % 3) * 0.035)) - ) - } - } - } - RadialGradient( - colors: [.clear, .clear, .black.opacity(0.30)], - center: .center, - startRadius: 180, - endRadius: 590 - ) - } - .allowsHitTesting(false) - } -} - -private func drawGrid( - context: inout GraphicsContext, - size: CGSize, - columns: Int, - rows: Int, - origin: CGPoint = .zero, - strength: Double = 0.62 -) { - for column in 0...columns { - let x = origin.x + size.width * CGFloat(column) / CGFloat(columns) - var path = Path(); path.move(to: CGPoint(x: x, y: origin.y)); path.addLine(to: CGPoint(x: x, y: origin.y + size.height)) - context.stroke(path, with: .color(dimPhosphor.opacity(strength)), lineWidth: 0.8) - } - for row in 0...rows { - let y = origin.y + size.height * CGFloat(row) / CGFloat(rows) - var path = Path(); path.move(to: CGPoint(x: origin.x, y: y)); path.addLine(to: CGPoint(x: origin.x + size.width, y: y)) - context.stroke(path, with: .color(dimPhosphor.opacity(strength)), lineWidth: 0.8) - } -} - -private func point(center: CGPoint, radius: CGFloat, angle: Double) -> CGPoint { - let radians = angle * .pi / 180 - return CGPoint(x: center.x + CGFloat(cos(radians)) * radius, y: center.y + CGFloat(sin(radians)) * radius) -} diff --git a/Sources/DockTelemetry/DockTelemetryApp.swift b/Sources/DockTelemetry/DockTelemetryApp.swift deleted file mode 100644 index 87e9c88..0000000 --- a/Sources/DockTelemetry/DockTelemetryApp.swift +++ /dev/null @@ -1,548 +0,0 @@ -import AppKit -import SwiftUI -import CoreGraphics -import ServiceManagement - -@main -struct DockTelemetryApp: App { - @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate - - var body: some Scene { - Settings { - SettingsView() - } - } -} - -struct SettingsView: View { - @ObservedObject private var layouts = LayoutStore.shared - @AppStorage("DockTelemetry.cycleDuration") private var cycleDuration = 24.0 - @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true - @AppStorage("DockTelemetry.coverMenuBar") private var coverMenuBar = true - @AppStorage("DockTelemetry.crtEnabled") private var crtEnabled = true - @AppStorage("DockTelemetry.bloomStrength") private var bloomStrength = 0.72 - @AppStorage("DockTelemetry.scanlineStrength") private var scanlineStrength = 0.22 - @AppStorage("DockTelemetry.noiseStrength") private var noiseStrength = 0.32 - @AppStorage("DockTelemetry.vhsTrackingEnabled") private var vhsTrackingEnabled = true - @AppStorage("DockTelemetry.phosphorBackgroundTint") private var phosphorBackgroundTint = 0.12 - @AppStorage("DockTelemetry.visualStyle") private var visualStyleRaw = ConsoleStyle.phosphor.rawValue - @AppStorage("DockTelemetry.globeWidthCorrection") private var globeWidthCorrection = 1.10 - @AppStorage("DockTelemetry.globeHeightCorrection") private var globeHeightCorrection = 1.00 - @AppStorage("DockTelemetry.radarWidthCorrection") private var radarWidthCorrection = 1.10 - @AppStorage("DockTelemetry.radarHeightCorrection") private var radarHeightCorrection = 0.9254 - @State private var selectedDisplayID = 0 - @State private var displayRefresh = UUID() - @State private var launchAtLogin = false - @State private var launchError: String? - @State private var exportMessage: String? - - private var screens: [NSScreen] { - _ = displayRefresh - return NSScreen.screens.sorted { - if $0.displayID == NSScreen.main?.displayID { return true } - if $1.displayID == NSScreen.main?.displayID { return false } - return $0.localizedName < $1.localizedName - } - } - - var body: some View { - TabView { - Form { - Section("Display") { - Picker("Default display", selection: $selectedDisplayID) { - Text("Automatic — smallest external display").tag(0) - ForEach(screens, id: \.displayID) { screen in - Text(screen.displayLabel).tag(Int(screen.displayID)) - } - } - .onChange(of: selectedDisplayID) { - saveDisplaySelection(selectedDisplayID) - } - Toggle("Cover the menu bar on the dock display", isOn: $coverMenuBar) - Text("The console stays exactly 960×540 and draws above the menu bar only on its own display.") - .font(.caption) - .foregroundStyle(.secondary) - } - Section("Startup") { - Toggle("Launch Retrolemetry at login", isOn: Binding( - get: { launchAtLogin }, - set: { updateLaunchAtLogin($0) } - )) - if let launchError { - Text(launchError) - .font(.caption) - .foregroundStyle(.red) - } - } - Section("Automatic scenes") { - Toggle("Automatically cycle scenes", isOn: $automaticCycleEnabled) - Picker("Change scene every", selection: $cycleDuration) { - Text("15 seconds").tag(15.0) - Text("24 seconds").tag(24.0) - Text("40 seconds").tag(40.0) - } - .pickerStyle(.segmented) - .disabled(!automaticCycleEnabled) - Text("When disabled, horizontal mouse scrolling and keys 1–4 still change scenes.") - .font(.caption) - .foregroundStyle(.secondary) - } - Section("Typography") { - LabeledContent("Primary values") { - Slider(value: $layouts.fontScale, in: 0.75...1.45).frame(width: 220) - } - Text("Primary \(Int(layouts.fontScale * 100))%") - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - LabeledContent("Secondary text") { - Slider(value: $layouts.secondaryFontScale, in: 0.65...1.45).frame(width: 220) - } - Text("Labels and headings \(Int(layouts.secondaryFontScale * 100))%") - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - } - Section("Visual style") { - Toggle("Synthwave colors", isOn: Binding( - get: { visualStyleRaw == ConsoleStyle.synthwave.rawValue }, - set: { visualStyleRaw = $0 ? ConsoleStyle.synthwave.rawValue : ConsoleStyle.phosphor.rawValue } - )) - HStack { - Text(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? "CYAN / MAGENTA / MIDNIGHT" : "GREEN PHOSPHOR / BLACK") - .font(.system(.caption, design: .monospaced).weight(.bold)) - Spacer() - Circle() - .fill(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? Color.cyan : Color.green) - .frame(width: 10, height: 10) - Circle() - .fill(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? Color.pink : Color.green.opacity(0.45)) - .frame(width: 10, height: 10) - } - if visualStyleRaw == ConsoleStyle.phosphor.rawValue { - LabeledContent("Green background tint") { - Slider(value: $phosphorBackgroundTint, in: 0...1) - .frame(width: 220) - } - Text("Zero is true black; maximum adds a deep green phosphor wash.") - .font(.caption) - .foregroundStyle(.secondary) - } - Toggle("Bloom, scanlines, noise, and vignette", isOn: $crtEnabled) - if crtEnabled { - LabeledContent("Bloom") { - Slider(value: $bloomStrength, in: 0...1).frame(width: 220) - } - LabeledContent("Scanlines") { - Slider(value: $scanlineStrength, in: 0...1).frame(width: 220) - } - LabeledContent("Noise") { - Slider(value: $noiseStrength, in: 0...1).frame(width: 220) - } - Toggle("Moving VHS tracking line", isOn: $vhsTrackingEnabled) - } - Text("The selected style applies to every telemetry, weather, and vector scene.") - .font(.caption) - .foregroundStyle(.secondary) - } - Section("Sphere shape") { - LabeledContent("Sphere width") { - Slider(value: $globeWidthCorrection, in: 0.70...1.35) - .frame(width: 220) - } - HStack { - Text("NARROWER") - Spacer() - Text("\(String(format: "%.0f%%", globeWidthCorrection * 100))") - Spacer() - Text("WIDER") - } - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - LabeledContent("Sphere height") { - Slider(value: $globeHeightCorrection, in: 0.70...1.35) - .frame(width: 220) - } - HStack { - Text("SHORTER") - Spacer() - Text("\(String(format: "%.0f%%", globeHeightCorrection * 100))") - Spacer() - Text("TALLER") - } - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - Text("Adjust width and height while looking at the physical dock display until the sphere is circular. Both controls are always visible at the top of Layout Editor.") - .font(.caption) - .foregroundStyle(.secondary) - } - Section("Radar shape") { - LabeledContent("Radar width") { - Slider(value: $radarWidthCorrection, in: 0.70...1.35).frame(width: 220) - } - Text("Width \(String(format: "%.0f%%", radarWidthCorrection * 100))") - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - LabeledContent("Radar height") { - Slider(value: $radarHeightCorrection, in: 0.70...1.35).frame(width: 220) - } - Text("Height \(String(format: "%.0f%%", radarHeightCorrection * 100))") - .font(.system(.caption2, design: .monospaced)) - .foregroundStyle(.secondary) - } - Section("Settings backup") { - Button("Export Settings Backup…") { exportSettings() } - if let exportMessage { - Text(exportMessage).font(.caption).foregroundStyle(.secondary) - } - Text("Exports layouts, module visibility, display choice, typography, slideshow, visual style, CRT, and roundness settings.") - .font(.caption) - .foregroundStyle(.secondary) - } - Section { - Text("Keys 1–4 choose a scene. Press 0 or A to resume cycling when automatic scenes are enabled. Horizontal mouse scrolling always moves between scenes.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - .formStyle(.grouped) - .padding(12) - .tabItem { Label("General", systemImage: "gearshape") } - - LayoutEditorView() - .tabItem { Label("Layout Editor", systemImage: "rectangle.3.group") } - } - .frame(width: 920, height: 650) - .onAppear { - selectedDisplayID = UserDefaults.standard.integer(forKey: DisplayPreference.idKey) - launchAtLogin = SMAppService.mainApp.status == .enabled - } - .onReceive(NotificationCenter.default.publisher(for: NSApplication.didChangeScreenParametersNotification)) { _ in - displayRefresh = UUID() - } - } - - private func saveDisplaySelection(_ id: Int) { - guard id != 0, - let screen = NSScreen.screens.first(where: { Int($0.displayID) == id }) else { - DisplayPreference.clear() - return - } - DisplayPreference.save(screen) - } - - private func updateLaunchAtLogin(_ enabled: Bool) { - launchError = nil - do { - if enabled { - try SMAppService.mainApp.register() - } else { - try SMAppService.mainApp.unregister() - } - launchAtLogin = SMAppService.mainApp.status == .enabled - } catch { - launchAtLogin = SMAppService.mainApp.status == .enabled - launchError = "macOS could not update Login Items: \(error.localizedDescription)" - } - } - - private func exportSettings() { - let panel = NSSavePanel() - panel.title = "Export Retrolemetry Settings" - panel.nameFieldStringValue = "Retrolemetry-Settings-Backup.plist" - guard panel.runModal() == .OK, let url = panel.url else { return } - - let bundleID = Bundle.main.bundleIdentifier ?? "com.sam.docktelemetry" - var values = UserDefaults.standard.persistentDomain(forName: bundleID) ?? [:] - values = values.filter { $0.key.hasPrefix("DockTelemetry.") } - values["DockTelemetry.backupFormat"] = 1 - values["DockTelemetry.backupCreatedAt"] = Date() - do { - let data = try PropertyListSerialization.data(fromPropertyList: values, format: .xml, options: 0) - try data.write(to: url, options: .atomic) - exportMessage = "Saved \(url.lastPathComponent)" - } catch { - exportMessage = "Export failed: \(error.localizedDescription)" - } - } -} - -@MainActor -final class AppDelegate: NSObject, NSApplicationDelegate { - private var controller: DisplayWindowController? - private var settingsController: SettingsWindowController? - private var statusItem: NSStatusItem? - - func applicationDidFinishLaunching(_ notification: Notification) { - UserDefaults.standard.register(defaults: [ - "DockTelemetry.cycleDuration": 40.0, - "DockTelemetry.automaticCycleEnabled": true, - "DockTelemetry.coverMenuBar": true, - "DockTelemetry.crtEnabled": true, - "DockTelemetry.bloomStrength": 0.80466796875, - "DockTelemetry.scanlineStrength": 0.8629296875, - "DockTelemetry.noiseStrength": 0.82953125, - "DockTelemetry.vhsTrackingEnabled": true, - "DockTelemetry.phosphorBackgroundTint": 0.3661328125, - "DockTelemetry.globeWidthCorrection": 1.10, - "DockTelemetry.globeHeightCorrection": 0.9254256185, - "DockTelemetry.radarWidthCorrection": 1.10, - "DockTelemetry.radarHeightCorrection": 0.9254256185, - "DockTelemetry.fontScale": 1.45, - "DockTelemetry.secondaryFontScale": 1.0, - "DockTelemetry.visualStyle": ConsoleStyle.phosphor.rawValue - ]) - NSApp.setActivationPolicy(.accessory) - controller = DisplayWindowController() - controller?.show() - installStatusItem() - installSignalToggle() - closeLegacySettingsWindow() - } - - func applicationShouldRestoreState(_ app: NSApplication) -> Bool { false } - - private func closeLegacySettingsWindow() { - DispatchQueue.main.async { - NSApp.windows - .filter { $0.identifier?.rawValue == "com_apple_SwiftUI_Settings_window" } - .forEach { $0.close() } - } - } - - private func installStatusItem() { - let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) - item.button?.image = NSImage(systemSymbolName: "waveform.path.ecg.rectangle", accessibilityDescription: "Retrolemetry") - item.button?.toolTip = "Retrolemetry" - - let menu = NSMenu() - let toggle = NSMenuItem(title: "Show / Hide Console", action: #selector(toggleConsole), keyEquivalent: "d") - toggle.target = self - toggle.keyEquivalentModifierMask = [.command, .shift] - menu.addItem(toggle) - let move = NSMenuItem(title: "Move to Preferred Display", action: #selector(moveConsole), keyEquivalent: "") - move.target = self - menu.addItem(move) - let settings = NSMenuItem(title: "Settings…", action: #selector(showSettings), keyEquivalent: ",") - settings.target = self - menu.addItem(settings) - menu.addItem(.separator()) - let quitItem = NSMenuItem(title: "Quit Retrolemetry", action: #selector(quit), keyEquivalent: "q") - quitItem.target = self - menu.addItem(quitItem) - item.menu = menu - statusItem = item - } - - private func installSignalToggle() { - signal(SIGUSR1, SIG_IGN) - let source = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main) - source.setEventHandler { [weak self] in self?.controller?.toggle() } - source.resume() - SignalHolder.shared.source = source - } - - @objc private func toggleConsole() { controller?.toggle() } - @objc private func moveConsole() { controller?.moveToPreferredDisplay(force: true) } - @objc private func showSettings() { - NSApp.activate(ignoringOtherApps: true) - if settingsController == nil { - settingsController = SettingsWindowController() - } - settingsController?.show() - } - @objc private func quit() { NSApp.terminate(nil) } -} - -private final class SignalHolder { - static let shared = SignalHolder() - var source: DispatchSourceSignal? -} - -@MainActor -final class DisplayWindowController { - private let window: ConsoleWindow - private var screenObserver: NSObjectProtocol? - private var defaultsObserver: NSObjectProtocol? - private var requestedVisible = true - - init() { - let root = ConsoleView() - window = ConsoleWindow( - contentRect: NSRect(x: 0, y: 0, width: 960, height: 540), - styleMask: [.borderless], - backing: .buffered, - defer: false - ) - window.contentView = NSHostingView(rootView: root) - window.backgroundColor = .black - window.isOpaque = true - window.hasShadow = false - window.level = Self.consoleLevel - window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary] - window.isMovableByWindowBackground = false - window.setContentSize(NSSize(width: 960, height: 540)) - - screenObserver = NotificationCenter.default.addObserver( - forName: NSApplication.didChangeScreenParametersNotification, - object: nil, - queue: .main - ) { [weak self] _ in - Task { @MainActor in self?.displayConfigurationChanged() } - } - defaultsObserver = NotificationCenter.default.addObserver( - forName: UserDefaults.didChangeNotification, - object: nil, - queue: .main - ) { [weak self] _ in - Task { @MainActor in - self?.applyWindowLevel() - self?.moveToPreferredDisplay(force: true) - } - } - applyWindowLevel() - } - - deinit { - if let screenObserver { NotificationCenter.default.removeObserver(screenObserver) } - if let defaultsObserver { NotificationCenter.default.removeObserver(defaultsObserver) } - } - - func show() { - requestedVisible = true - if moveToPreferredDisplay(force: false) { - window.orderFrontRegardless() - } else { - window.orderOut(nil) - } - } - - func toggle() { - if window.isVisible || requestedVisible { - requestedVisible = false - window.orderOut(nil) - } else { - show() - } - } - - @discardableResult - func moveToPreferredDisplay(force: Bool) -> Bool { - guard let target = preferredScreen() else { - window.orderOut(nil) - return false - } - if force || window.screen?.displayID != target.displayID || !window.isVisible { - let frame = target.frame - let origin = NSPoint( - x: frame.midX - 480, - y: frame.midY - 270 - ) - window.setFrame(NSRect(origin: origin, size: NSSize(width: 960, height: 540)), display: true) - } - if requestedVisible { window.orderFrontRegardless() } - return true - } - - private func displayConfigurationChanged() { - guard requestedVisible else { return } - _ = moveToPreferredDisplay(force: true) - } - - private func applyWindowLevel() { - window.level = UserDefaults.standard.bool(forKey: "DockTelemetry.coverMenuBar") - ? Self.consoleLevel - : .normal - } - - private static var consoleLevel: NSWindow.Level { - NSWindow.Level(rawValue: NSWindow.Level.mainMenu.rawValue + 1) - } - - private func preferredScreen() -> NSScreen? { - let stored = UInt32(UserDefaults.standard.integer(forKey: DisplayPreference.idKey)) - if stored != 0, let match = NSScreen.screens.first(where: { $0.displayID == stored }) { - return match - } - if stored != 0 { - guard let restored = DisplayPreference.restoredScreen() else { return nil } - DisplayPreference.save(restored) - return restored - } - - let external = NSScreen.screens.filter { CGDisplayIsBuiltin($0.displayID) == 0 } - return external.min(by: { ($0.frame.width * $0.frame.height) < ($1.frame.width * $1.frame.height) }) - ?? NSScreen.main - ?? NSScreen.screens.first - } -} - -@MainActor -final class SettingsWindowController: NSObject, NSWindowDelegate { - private let window: NSWindow - - override init() { - window = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: 920, height: 650), - styleMask: [.titled, .closable, .resizable], - backing: .buffered, - defer: false - ) - super.init() - window.title = "Retrolemetry Settings" - window.identifier = NSUserInterfaceItemIdentifier("DockTelemetry.Settings") - window.contentView = NSHostingView(rootView: SettingsView()) - window.isReleasedWhenClosed = false - window.delegate = self - } - - func show() { - window.center() - window.makeKeyAndOrderFront(nil) - } -} - -enum DisplayPreference { - static let idKey = "DockTelemetry.preferredDisplayID" - private static let nameKey = "DockTelemetry.preferredDisplayName" - private static let widthKey = "DockTelemetry.preferredDisplayWidth" - private static let heightKey = "DockTelemetry.preferredDisplayHeight" - - static func save(_ screen: NSScreen) { - let defaults = UserDefaults.standard - defaults.set(Int(screen.displayID), forKey: idKey) - defaults.set(screen.localizedName, forKey: nameKey) - defaults.set(Int(screen.frame.width.rounded()), forKey: widthKey) - defaults.set(Int(screen.frame.height.rounded()), forKey: heightKey) - } - - static func clear() { - let defaults = UserDefaults.standard - [idKey, nameKey, widthKey, heightKey].forEach { defaults.removeObject(forKey: $0) } - } - - static func restoredScreen() -> NSScreen? { - let defaults = UserDefaults.standard - let name = defaults.string(forKey: nameKey) - let width = defaults.integer(forKey: widthKey) - let height = defaults.integer(forKey: heightKey) - return NSScreen.screens.first { - let sameName = name != nil && $0.localizedName == name - let sameSize = Int($0.frame.width.rounded()) == width && Int($0.frame.height.rounded()) == height - return sameName && sameSize - } - } -} - -private final class ConsoleWindow: NSWindow { - override var canBecomeKey: Bool { true } -} - -extension NSScreen { - var displayID: CGDirectDisplayID { - (deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value ?? 0 - } - - var displayLabel: String { - let role = CGDisplayIsBuiltin(displayID) != 0 ? "Built-in" : "External" - return "\(localizedName) — \(Int(frame.width))×\(Int(frame.height)) (\(role))" - } -} diff --git a/Sources/DockTelemetry/LayoutEditor.swift b/Sources/DockTelemetry/LayoutEditor.swift deleted file mode 100644 index e5f9b09..0000000 --- a/Sources/DockTelemetry/LayoutEditor.swift +++ /dev/null @@ -1,446 +0,0 @@ -import SwiftUI - -struct ModuleFrame: Codable, Equatable { - var x: Double - var y: Double - var width: Double - var height: Double - var visible: Bool = true - - var rect: CGRect { - CGRect(x: x, y: y, width: width, height: height) - } -} - -struct SceneModule: Identifiable, Hashable { - let id: String - let name: String -} - -enum LayoutDefaults { - static func modules(for scene: ConsoleScene) -> [SceneModule] { - switch scene { - case .system: - [module("meters", "Load meters"), module("readouts", "Uptime / network"), module("history", "CPU history"), module("globe", "Wireframe globe"), module("globeStatus", "Globe status")] - case .radar: - [module("radar", "Radar"), module("weatherHeader", "Weather header"), module("weatherStats", "Weather conditions"), module("temperature", "Temperature graph"), module("precipitation", "Precipitation graph"), module("weatherStatus", "Weather status")] - case .signal: - [module("scope", "Signal scope"), module("signalHeader", "Channel header"), module("cpuTrace", "CPU trace"), module("memoryTrace", "Memory trace"), module("networkTrace", "Network trace"), module("ioReadout", "Network I/O")] - case .fullMetrics: - [module("metricCPU", "CPU tile"), module("metricMemory", "Memory tile"), module("metricDisk", "Disk tile"), module("metricNetwork", "Network tile"), module("graphCPU", "CPU graph"), module("graphMemory", "Memory graph"), module("graphNetwork", "Network graph"), module("statusUptime", "Uptime"), module("statusLoad", "Load averages"), module("statusTX", "Network TX")] - } - } - - static func frames(for scene: ConsoleScene) -> [String: ModuleFrame] { - switch scene { - case .system: - return [ - "meters": frame(39.9426, 62.6756, 554.5965, 174.6376), - "readouts": frame(42.2403, 255.7691, 553.0455, 56.1202), - "history": frame(40, 331, 557.7445, 158.3580), - "globe": frame(631.8957, 80.5168, 290.8042, 281.9945), - "globeStatus": frame(630, 374, 295.1988, 114.2289) - ] - case .radar: - return [ - "radar": frame(25, 55, 438.8523, 429.6496), "weatherHeader": frame(480, 58, 455, 60), - "weatherStats": frame(480, 130, 455, 62), "temperature": frame(480, 204, 455, 92), - "precipitation": frame(480, 307, 455.4481, 171.0326), - "weatherStatus": frame(480, 409, 457.5391, 38) - ] - case .signal: - return [ - "scope": frame(50, 78, 860, 320), "signalHeader": frame(62, 90, 836, 25), - "cpuTrace": frame(62, 418, 200, 78), "memoryTrace": frame(274, 418, 200, 78), - "networkTrace": frame(486, 418, 200, 78), "ioReadout": frame(698, 418, 217.7964, 77.9483) - ] - case .fullMetrics: - let tileW = 217.0 - return [ - "metricCPU": frame(28, 55, tileW, 116), "metricMemory": frame(257, 55, tileW, 116), - "metricDisk": frame(486, 55, tileW, 116), "metricNetwork": frame(715, 55, tileW, 116), - "graphCPU": frame(28, 183, 293, 200), "graphMemory": frame(333, 183, 293, 200), - "graphNetwork": frame(638, 183, 294, 200), - "statusUptime": frame(28, 395, 290.7309, 108.1884), - "statusLoad": frame(333, 394.7723, 292.7358, 107.8150), - "statusTX": frame(638, 395, 287.8994, 107.7403) - ] - } - } - - private static func module(_ id: String, _ name: String) -> SceneModule { SceneModule(id: id, name: name) } - private static func frame(_ x: Double, _ y: Double, _ width: Double, _ height: Double) -> ModuleFrame { - ModuleFrame(x: x, y: y, width: width, height: height) - } -} - -@MainActor -final class LayoutStore: ObservableObject { - static let shared = LayoutStore() - @Published private(set) var layouts: [String: [String: ModuleFrame]] = [:] - @Published var fontScale: Double { - didSet { UserDefaults.standard.set(fontScale, forKey: "DockTelemetry.fontScale") } - } - @Published var secondaryFontScale: Double { - didSet { UserDefaults.standard.set(secondaryFontScale, forKey: "DockTelemetry.secondaryFontScale") } - } - - private init() { - fontScale = UserDefaults.standard.object(forKey: "DockTelemetry.fontScale") as? Double ?? 1.45 - secondaryFontScale = UserDefaults.standard.object(forKey: "DockTelemetry.secondaryFontScale") as? Double ?? 1 - for scene in ConsoleScene.allCases { layouts[sceneKey(scene)] = load(scene) } - } - - func frame(_ scene: ConsoleScene, _ module: String) -> ModuleFrame { - layouts[sceneKey(scene)]?[module] ?? LayoutDefaults.frames(for: scene)[module] ?? ModuleFrame(x: 40, y: 80, width: 200, height: 100) - } - - func update(_ scene: ConsoleScene, module: String, frame: ModuleFrame) { - var sceneLayout = layouts[sceneKey(scene)] ?? LayoutDefaults.frames(for: scene) - sceneLayout[module] = constrained(frame) - layouts[sceneKey(scene)] = sceneLayout - save(scene, sceneLayout) - } - - func setVisible(_ visible: Bool, scene: ConsoleScene, module: String) { - var value = frame(scene, module) - value.visible = visible - update(scene, module: module, frame: value) - } - - func reset(_ scene: ConsoleScene) { - let defaults = LayoutDefaults.frames(for: scene) - layouts[sceneKey(scene)] = defaults - save(scene, defaults) - } - - private func constrained(_ value: ModuleFrame) -> ModuleFrame { - var result = value - result.width = min(930, max(70, result.width)) - result.height = min(470, max(38, result.height)) - result.x = min(945 - result.width, max(15, result.x)) - result.y = min(505 - result.height, max(45, result.y)) - return result - } - - private func sceneKey(_ scene: ConsoleScene) -> String { String(scene.rawValue) } - private func storageKey(_ scene: ConsoleScene) -> String { "DockTelemetry.layout.v3.\(scene.rawValue)" } - - private func load(_ scene: ConsoleScene) -> [String: ModuleFrame] { - guard let data = UserDefaults.standard.data(forKey: storageKey(scene)), - let saved = try? JSONDecoder().decode([String: ModuleFrame].self, from: data) else { - return LayoutDefaults.frames(for: scene) - } - return LayoutDefaults.frames(for: scene).merging(saved) { _, saved in saved } - } - - private func save(_ scene: ConsoleScene, _ layout: [String: ModuleFrame]) { - guard let data = try? JSONEncoder().encode(layout) else { return } - UserDefaults.standard.set(data, forKey: storageKey(scene)) - } -} - -enum FontRuntime { - nonisolated(unsafe) static var scale = 1.0 - nonisolated(unsafe) static var secondaryScale = 1.0 -} - -func consoleFont(_ size: Double, weight: Font.Weight = .regular) -> Font { - .system(size: size * FontRuntime.scale, weight: weight, design: .monospaced) -} - -func consoleSecondaryFont(_ size: Double, weight: Font.Weight = .regular) -> Font { - .system(size: size * FontRuntime.secondaryScale, weight: weight, design: .monospaced) -} - -struct LayoutModuleContainer: View { - @ObservedObject private var layouts = LayoutStore.shared - let scene: ConsoleScene - let module: String - @ViewBuilder let content: () -> Content - - var body: some View { - let value = layouts.frame(scene, module) - if value.visible { - content() - .frame(width: value.width, height: value.height) - .position(x: value.x + value.width / 2, y: value.y + value.height / 2) - .clipped() - } - } -} - -struct LayoutEditorView: View { - @ObservedObject private var layouts = LayoutStore.shared - @AppStorage("DockTelemetry.globeWidthCorrection") private var globeWidthCorrection = 1.10 - @AppStorage("DockTelemetry.globeHeightCorrection") private var globeHeightCorrection = 1.00 - @AppStorage("DockTelemetry.radarWidthCorrection") private var radarWidthCorrection = 1.10 - @AppStorage("DockTelemetry.radarHeightCorrection") private var radarHeightCorrection = 0.9254 - @State private var scene: ConsoleScene = .system - @State private var selection = "meters" - @State private var interactionModule: String? - @State private var interactionStart: ModuleFrame? - @State private var interactionKind: InteractionKind? - private let scale = 0.68 - - private enum InteractionKind { case move, resize } - - var body: some View { - FontRuntime.scale = layouts.fontScale - FontRuntime.secondaryScale = layouts.secondaryFontScale - return VStack(spacing: 12) { - HStack { - Picker("View", selection: $scene) { - ForEach(ConsoleScene.allCases, id: \.self) { Text($0.title).tag($0) } - } - .frame(width: 320) - .onChange(of: scene) { selection = LayoutDefaults.modules(for: scene).first?.id ?? "" } - Spacer(minLength: 20) - LabeledContent("Font size") { - Slider(value: $layouts.fontScale, in: 0.75...1.45).frame(width: 125) - } - Text("\(Int(layouts.fontScale * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Button("Reset this view") { layouts.reset(scene) } - } - - HStack { - LabeledContent("Secondary text") { - Slider(value: $layouts.secondaryFontScale, in: 0.65...1.45).frame(width: 125) - } - Text("\(Int(layouts.secondaryFontScale * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Text("Controls labels, headings, and supporting readouts.") - .font(.caption).foregroundStyle(.secondary) - Spacer() - } - - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 12) { - Text("Sphere width").frame(width: 92, alignment: .leading) - Text("NARROW").font(.caption2).foregroundStyle(.secondary) - Slider(value: $globeWidthCorrection, in: 0.70...1.35).frame(width: 260) - Text("WIDE").font(.caption2).foregroundStyle(.secondary) - Text("\(Int(globeWidthCorrection * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Spacer() - } - HStack(spacing: 12) { - Text("Sphere height").frame(width: 92, alignment: .leading) - Text("SHORT").font(.caption2).foregroundStyle(.secondary) - Slider(value: $globeHeightCorrection, in: 0.70...1.35).frame(width: 260) - Text("TALL").font(.caption2).foregroundStyle(.secondary) - Text("\(Int(globeHeightCorrection * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Spacer() - } - HStack(spacing: 12) { - Text("Radar width").frame(width: 92, alignment: .leading) - Text("NARROW").font(.caption2).foregroundStyle(.secondary) - Slider(value: $radarWidthCorrection, in: 0.70...1.35).frame(width: 260) - Text("WIDE").font(.caption2).foregroundStyle(.secondary) - Text("\(Int(radarWidthCorrection * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Spacer() - } - HStack(spacing: 12) { - Text("Radar height").frame(width: 92, alignment: .leading) - Text("SHORT").font(.caption2).foregroundStyle(.secondary) - Slider(value: $radarHeightCorrection, in: 0.70...1.35).frame(width: 260) - Text("TALL").font(.caption2).foregroundStyle(.secondary) - Text("\(Int(radarHeightCorrection * 100))%") - .monospacedDigit().frame(width: 42, alignment: .trailing) - Text("Adjust both while looking at the physical dock screen until the globe is circular.") - .font(.caption).foregroundStyle(.secondary) - Spacer() - } - } - - HStack(alignment: .top, spacing: 14) { - editorCanvas - ScrollView { - VStack(alignment: .leading, spacing: 8) { - Text("MODULES").font(.headline) - ForEach(LayoutDefaults.modules(for: scene)) { module in - let value = layouts.frame(scene, module.id) - HStack { - Toggle("", isOn: Binding( - get: { value.visible }, - set: { layouts.setVisible($0, scene: scene, module: module.id) } - )).labelsHidden() - Button(module.name) { selection = module.id } - .buttonStyle(.plain) - .foregroundStyle(selection == module.id ? Color.accentColor : Color.primary) - Spacer() - } - } - Divider() - Text("Drag inside the selected outline to move. Drag the yellow corner handle to resize.") - .font(.caption).foregroundStyle(.secondary) - if let module = LayoutDefaults.modules(for: scene).first(where: { $0.id == selection }) { - moduleControls(module) - } - } - } - .frame(width: 210, height: 367) - } - } - .padding(16) - } - - private var editorCanvas: some View { - ZStack(alignment: .topLeading) { - Color.black - staticScene - ForEach(LayoutDefaults.modules(for: scene)) { module in - moduleBox(module) - } - } - .foregroundStyle(Color(red: 0.34, green: 1, blue: 0.43)) - .font(.system(size: 8, weight: .bold, design: .monospaced)) - .frame(width: 960 * scale, height: 540 * scale) - .contentShape(Rectangle()) - .gesture(editorGesture) - .clipped() - .overlay(Rectangle().stroke(Color.green.opacity(0.7), lineWidth: 1)) - } - - @ViewBuilder - private var staticScene: some View { - let telemetry = TelemetrySnapshot( - cpu: 0.38, memory: 0.61, disk: 0.62, - networkIn: 240_000, networkOut: 82_000, - uptime: 213_420, load: (2.4, 3.1, 3.8) - ) - let cpu = (0..<96).map { 0.24 + sin(Double($0) * 0.22) * 0.11 } - let memory = (0..<96).map { 0.57 + sin(Double($0) * 0.06) * 0.025 } - let network = (0..<96).map { max(0.02, sin(Double($0) * 0.31) * 0.18 + 0.12) } - let weather = WeatherSnapshot( - location: "LOCAL PREVIEW", condition: "PARTLY CLOUDY", - temperature: 24, apparentTemperature: 25, humidity: 0.58, - windSpeed: 12, precipitation: 0, - temperatureForecast: [0.72, 0.68, 0.61, 0.55, 0.50, 0.45, 0.42, 0.40, 0.36, 0.34, 0.31, 0.29], - precipitationForecast: [0.08, 0.05, 0.04, 0.03, 0.04, 0.08, 0.12, 0.09, 0.06, 0.04, 0.03, 0.02], - status: "STATIC LAYOUT PREVIEW" - ) - Group { - switch scene { - case .system: - SystemScene(snapshot: telemetry, history: cpu, time: 10) - case .radar: - RadarScene(weather: weather, time: 10) - case .signal: - SignalScene(snapshot: telemetry, cpuHistory: cpu, memoryHistory: memory, networkHistory: network, time: 10) - case .fullMetrics: - FullMetricsScene(snapshot: telemetry, cpuHistory: cpu, memoryHistory: memory, networkHistory: network, time: 10) - } - } - .frame(width: 960, height: 540) - .scaleEffect(scale, anchor: .topLeading) - .frame(width: 960 * scale, height: 540 * scale, alignment: .topLeading) - .allowsHitTesting(false) - } - - private func moduleBox(_ module: SceneModule) -> some View { - let value = layouts.frame(scene, module.id) - let selected = selection == module.id - return ZStack(alignment: .bottomTrailing) { - RoundedRectangle(cornerRadius: 3) - .fill(value.visible ? Color.white.opacity(0.001) : Color.gray.opacity(0.12)) - RoundedRectangle(cornerRadius: 3) - .stroke( - selected ? Color.yellow : (value.visible ? Color.green.opacity(0.38) : Color.gray), - style: StrokeStyle(lineWidth: selected ? 2 : 1, dash: value.visible ? [] : [5, 4]) - ) - if selected { - Rectangle().fill(Color.yellow).frame(width: 14, height: 14) - } - } - .frame(width: value.width * scale, height: value.height * scale) - .position(x: (value.x + value.width / 2) * scale, y: (value.y + value.height / 2) * scale) - .zIndex(selected ? 20 : 0) - .opacity(value.visible ? 1 : 0.55) - .allowsHitTesting(false) - } - - private var editorGesture: some Gesture { - DragGesture(minimumDistance: 0, coordinateSpace: .local) - .onChanged { gesture in - if interactionModule == nil { - let point = CGPoint(x: gesture.startLocation.x / scale, y: gesture.startLocation.y / scale) - let selectedFrame = layouts.frame(scene, selection) - let handle = CGRect( - x: selectedFrame.x + selectedFrame.width - 24 / scale, - y: selectedFrame.y + selectedFrame.height - 24 / scale, - width: 24 / scale, - height: 24 / scale - ) - let resizing = handle.contains(point) - let module = resizing ? selection : hitTest(point) - guard !module.isEmpty else { return } - selection = module - interactionModule = module - interactionStart = layouts.frame(scene, module) - interactionKind = resizing ? .resize : .move - } - - guard let module = interactionModule, var updated = interactionStart else { return } - let dx = gesture.translation.width / scale - let dy = gesture.translation.height / scale - if interactionKind == .resize { - updated.width += dx - updated.height += dy - } else { - updated.x += dx - updated.y += dy - } - layouts.update(scene, module: module, frame: updated) - } - .onEnded { _ in - interactionModule = nil - interactionKind = nil - interactionStart = nil - } - } - - private func hitTest(_ point: CGPoint) -> String { - LayoutDefaults.modules(for: scene) - .filter { layouts.frame(scene, $0.id).rect.contains(point) } - .min { lhs, rhs in - let left = layouts.frame(scene, lhs.id) - let right = layouts.frame(scene, rhs.id) - return left.width * left.height < right.width * right.height - }?.id ?? "" - } - - @ViewBuilder - private func moduleControls(_ module: SceneModule) -> some View { - let value = layouts.frame(scene, module.id) - VStack(alignment: .leading, spacing: 5) { - Text(module.name).font(.caption).bold() - HStack { - Stepper("X \(Int(value.x))", value: frameBinding(module.id, \.x), in: 15...875, step: 1) - Stepper("Y \(Int(value.y))", value: frameBinding(module.id, \.y), in: 45...467, step: 1) - } - HStack { - Stepper("W \(Int(value.width))", value: frameBinding(module.id, \.width), in: 70...930, step: 1) - Stepper("H \(Int(value.height))", value: frameBinding(module.id, \.height), in: 38...470, step: 1) - } - Text("Changes save immediately.") - .font(.caption2).foregroundStyle(.secondary) - } - .padding(8) - .background(.quaternary, in: RoundedRectangle(cornerRadius: 6)) - } - - private func frameBinding(_ module: String, _ keyPath: WritableKeyPath) -> Binding { - Binding( - get: { layouts.frame(scene, module)[keyPath: keyPath] }, - set: { newValue in - var value = layouts.frame(scene, module) - value[keyPath: keyPath] = newValue - layouts.update(scene, module: module, frame: value) - } - ) - } -} diff --git a/Sources/DockTelemetry/Weather.swift b/Sources/DockTelemetry/Weather.swift deleted file mode 100644 index 6f7e44f..0000000 --- a/Sources/DockTelemetry/Weather.swift +++ /dev/null @@ -1,171 +0,0 @@ -import Foundation -import Combine -import CoreLocation - -struct WeatherSnapshot { - var location = "AWAITING LOCATION" - var condition = "WEATHER OFFLINE" - var temperature = 0.0 - var apparentTemperature = 0.0 - var humidity = 0.0 - var windSpeed = 0.0 - var precipitation = 0.0 - var temperatureForecast: [Double] = Array(repeating: 0, count: 12) - var precipitationForecast: [Double] = Array(repeating: 0, count: 12) - var updatedAt: Date? - var status = "LOCATION PERMISSION REQUIRED" -} - -@MainActor -final class WeatherModel: NSObject, ObservableObject, @preconcurrency CLLocationManagerDelegate { - @Published private(set) var snapshot = WeatherSnapshot() - - private let locationManager = CLLocationManager() - private var refreshTimer: Timer? - private var coordinate: CLLocationCoordinate2D? - - override init() { - super.init() - locationManager.delegate = self - locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers - requestLocation() - refreshTimer = Timer.scheduledTimer(withTimeInterval: 15 * 60, repeats: true) { [weak self] _ in - Task { @MainActor in self?.refresh() } - } - refreshTimer?.tolerance = 60 - } - - deinit { refreshTimer?.invalidate() } - - private func requestLocation() { - switch locationManager.authorizationStatus { - case .authorized, .authorizedAlways: - snapshot.status = "LOCATING" - locationManager.requestLocation() - case .notDetermined: - snapshot.status = "REQUESTING LOCATION" - locationManager.requestWhenInUseAuthorization() - case .denied, .restricted: - snapshot.status = "ENABLE LOCATION IN SYSTEM SETTINGS" - @unknown default: - snapshot.status = "LOCATION UNAVAILABLE" - } - } - - func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { - requestLocation() - } - - func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { - guard let location = locations.last else { return } - coordinate = location.coordinate - snapshot.location = String(format: "LOCAL %.2f° %.2f°", location.coordinate.latitude, location.coordinate.longitude) - refresh() - } - - func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { - snapshot.status = "LOCATION UNAVAILABLE" - } - - private func refresh() { - guard let coordinate else { - requestLocation() - return - } - snapshot.status = "UPDATING FORECAST" - - var components = URLComponents(string: "https://api.open-meteo.com/v1/forecast")! - components.queryItems = [ - URLQueryItem(name: "latitude", value: String(coordinate.latitude)), - URLQueryItem(name: "longitude", value: String(coordinate.longitude)), - URLQueryItem(name: "current", value: "temperature_2m,apparent_temperature,relative_humidity_2m,precipitation,weather_code,wind_speed_10m"), - URLQueryItem(name: "hourly", value: "temperature_2m,precipitation_probability"), - URLQueryItem(name: "forecast_hours", value: "12"), - URLQueryItem(name: "timezone", value: "auto") - ] - guard let url = components.url else { return } - - Task { - do { - let (data, response) = try await URLSession.shared.data(from: url) - guard (response as? HTTPURLResponse)?.statusCode == 200 else { - throw URLError(.badServerResponse) - } - let payload = try JSONDecoder().decode(OpenMeteoResponse.self, from: data) - apply(payload) - } catch { - snapshot.status = "WEATHER FEED UNAVAILABLE" - } - } - } - - private func apply(_ payload: OpenMeteoResponse) { - let temperatures = Array(payload.hourly.temperature2m.prefix(12)) - let precipitation = Array(payload.hourly.precipitationProbability.prefix(12)) - snapshot.condition = weatherCondition(payload.current.weatherCode) - snapshot.temperature = payload.current.temperature2m - snapshot.apparentTemperature = payload.current.apparentTemperature - snapshot.humidity = payload.current.relativeHumidity2m / 100 - snapshot.windSpeed = payload.current.windSpeed10m - snapshot.precipitation = payload.current.precipitation - snapshot.temperatureForecast = normalized(temperatures) - snapshot.precipitationForecast = precipitation.map { min(1, max(0, $0 / 100)) } - snapshot.updatedAt = Date() - snapshot.status = "LIVE // OPEN-METEO" - } - - private func normalized(_ values: [Double]) -> [Double] { - guard let low = values.min(), let high = values.max() else { return [] } - let span = max(2, high - low) - return values.map { 0.12 + (($0 - low) / span) * 0.76 } - } - - private func weatherCondition(_ code: Int) -> String { - switch code { - case 0: "CLEAR SKY" - case 1, 2: "PARTLY CLOUDY" - case 3: "OVERCAST" - case 45, 48: "FOG" - case 51...57: "DRIZZLE" - case 61...67: "RAIN" - case 71...77: "SNOW" - case 80...82: "RAIN SHOWERS" - case 85, 86: "SNOW SHOWERS" - case 95...99: "THUNDERSTORM" - default: "MIXED CONDITIONS" - } - } -} - -private struct OpenMeteoResponse: Decodable { - let current: Current - let hourly: Hourly - - struct Current: Decodable { - let temperature2m: Double - let apparentTemperature: Double - let relativeHumidity2m: Double - let precipitation: Double - let weatherCode: Int - let windSpeed10m: Double - - enum CodingKeys: String, CodingKey { - case temperature2m = "temperature_2m" - case apparentTemperature = "apparent_temperature" - case relativeHumidity2m = "relative_humidity_2m" - case precipitation - case weatherCode = "weather_code" - case windSpeed10m = "wind_speed_10m" - } - } - - struct Hourly: Decodable { - let temperature2m: [Double] - let precipitationProbability: [Double] - - enum CodingKeys: String, CodingKey { - case temperature2m = "temperature_2m" - case precipitationProbability = "precipitation_probability" - } - } -} diff --git a/Sources/Retrolemetry/AppUpdater.swift b/Sources/Retrolemetry/AppUpdater.swift new file mode 100644 index 0000000..59a9df1 --- /dev/null +++ b/Sources/Retrolemetry/AppUpdater.swift @@ -0,0 +1,78 @@ +import AppKit +import Sparkle + +/// Sparkle owns download, verification, installation and relaunch. Never implement +/// a second installer, trust override, or credential store here. +@MainActor +final class AppUpdater: NSObject, ObservableObject, SPUUpdaterDelegate { + static let shared = AppUpdater() + lazy var controller = SPUStandardUpdaterController( + startingUpdater: false, updaterDelegate: self, userDriverDelegate: nil + ) + @Published private(set) var available = false + @Published private(set) var canCheck = false + @Published private(set) var lastError: NSError? + private var checkObservation: NSKeyValueObservation? + private var automaticObservation: NSKeyValueObservation? + private let bundleIdentifier: String + + init(bundleIdentifier: String = UpdateConfiguration.bundleIdentifier) { + self.bundleIdentifier = bundleIdentifier + super.init() + } + + func start() { + // A source-run executable or unit test is not an updatable .app bundle. + guard Bundle.main.bundleURL.pathExtension == "app", + Bundle.main.bundleIdentifier == bundleIdentifier, + UpdateConfiguration.isValid(Bundle.main.infoDictionary ?? [:]) else { return } + guard !available else { return } + checkObservation = controller.updater.observe(\.canCheckForUpdates, options: [.initial, .new]) { [weak self] _, _ in + guard let owner = self else { return } + Task { @MainActor in + owner.canCheck = owner.controller.updater.canCheckForUpdates + } + } + automaticObservation = controller.updater.observe(\.automaticallyChecksForUpdates) { [weak self] _, _ in + guard let owner = self else { return } + Task { @MainActor in owner.objectWillChange.send() } + } + controller.startUpdater() + available = true + } + + var automaticallyChecks: Bool { + get { controller.updater.automaticallyChecksForUpdates } + set { + controller.updater.automaticallyChecksForUpdates = newValue + objectWillChange.send() + } + } + + func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) { + // Layouts and display settings already use the existing defaults domain. + // Flush pending edits before Sparkle replaces the app, without resetting it. + UserDefaults.standard.synchronize() + } + + func updater(_ updater: SPUUpdater, didAbortWithError error: Error) { + lastError = error as NSError + } + + func allowedSystemProfileKeys(for updater: SPUUpdater) -> [String]? { [] } +} + +enum UpdateConfiguration { + static let bundleIdentifier = "io.github.SamSpring.Retrolemetry" + static let feedURL = "https://samspring.github.io/Retrolemetry/appcast.xml" + + static func isValid(_ info: [String: Any]) -> Bool { + guard info["SUFeedURL"] as? String == feedURL, + let key = info["SUPublicEDKey"] as? String, + Data(base64Encoded: key)?.count == 32, + info["SUVerifyUpdateBeforeExtraction"] as? Bool == true, + info["SURequireSignedFeed"] as? Bool == true, + (info["SUSignedFeedFailureExpirationInterval"] as? NSNumber)?.doubleValue == 0 else { return false } + return true + } +} diff --git a/Sources/Retrolemetry/CRTDisplay.swift b/Sources/Retrolemetry/CRTDisplay.swift new file mode 100644 index 0000000..99bfc53 --- /dev/null +++ b/Sources/Retrolemetry/CRTDisplay.swift @@ -0,0 +1,130 @@ +import AppKit +import MetalKit +import SwiftUI + +/// One small GPU pass for the moving CRT overlay. Its clock never invalidates the +/// SwiftUI scene underneath, and no full-screen grain images are retained. +struct CRTDisplay: NSViewRepresentable { + let scanlines: Double + let noise: Double + let tracking: Bool + let firstThickness: Double + let secondThickness: Double + let tubeStrength: Double + let color: Color + let paused: Bool + let frameRate: Double + + static var isAvailable: Bool { CRTGPU.shared != nil } + + func makeCoordinator() -> Renderer { Renderer() } + + func makeNSView(context: Context) -> MTKView { + let view = CRTMetalView(frame: .zero, device: CRTGPU.shared?.device) + view.colorPixelFormat = .bgra8Unorm + view.clearColor = MTLClearColorMake(0, 0, 0, 0) + view.framebufferOnly = true + view.autoResizeDrawable = false + // Effects are specified in the console's 960x540 coordinates, including + // on Retina/4K monitors. Avoid a wasteful full-resolution noise buffer. + view.drawableSize = CGSize(width: 960, height: 540) + view.layer?.isOpaque = false + view.delegate = context.coordinator + updateNSView(view, context: context) + return view + } + + func updateNSView(_ view: MTKView, context: Context) { + let rgb = NSColor(color).usingColorSpace(.sRGB) ?? .green + let parameters = CRTParameters( + color: SIMD4(Float(rgb.redComponent), Float(rgb.greenComponent), Float(rgb.blueComponent), 1), + effects: SIMD4(Float(scanlines), Float(noise), tracking ? 1 : 0, Float(tubeStrength)), + motion: SIMD4(0, Float(firstThickness), Float(secondThickness), 0) + ) + let changed = parameters != context.coordinator.parameters + context.coordinator.parameters = parameters + let fps = tracking ? max(15, min(60, Int(frameRate))) : 14 + if view.preferredFramesPerSecond != fps { view.preferredFramesPerSecond = fps } + let shouldPause = paused || (!tracking && noise <= 0.001) + if view.isPaused != shouldPause { view.isPaused = shouldPause } + if shouldPause && (changed || !context.coordinator.hasDrawn) { view.draw() } + } + + static func dismantleNSView(_ view: MTKView, coordinator: Renderer) { + view.isPaused = true + view.delegate = nil + } + + final class Renderer: NSObject, MTKViewDelegate { + var parameters = CRTParameters() + private(set) var hasDrawn = false + // Prevent building a queue of obsolete frames when the Mac is busy. + private let inFlight = DispatchSemaphore(value: 2) + private let epoch = ProcessInfo.processInfo.systemUptime + + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} + + func draw(in view: MTKView) { + guard let gpu = CRTGPU.shared, inFlight.wait(timeout: .now()) == .success else { return } + guard let pass = view.currentRenderPassDescriptor, + let drawable = view.currentDrawable, + let command = gpu.queue.makeCommandBuffer(), + let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { + inFlight.signal() + return + } + var uniforms = parameters + // A short relative clock avoids precision loss from large timestamps. + uniforms.motion.x = Float((ProcessInfo.processInfo.systemUptime - epoch).truncatingRemainder(dividingBy: 4096)) + encoder.setRenderPipelineState(gpu.pipeline) + encoder.setFragmentBytes(&uniforms, length: MemoryLayout.stride, index: 0) + encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) + encoder.endEncoding() + command.present(drawable) + let semaphore = inFlight + command.addCompletedHandler { _ in semaphore.signal() } + command.commit() + hasDrawn = true + } + } +} + +private final class CRTMetalView: MTKView { + override func layout() { + super.layout() + if isPaused, bounds.width > 0, bounds.height > 0 { draw() } + } + override var isOpaque: Bool { false } + override func hitTest(_ point: NSPoint) -> NSView? { nil } +} + +struct CRTParameters: Equatable { + var color = SIMD4(0.34, 1, 0.43, 1) + var effects = SIMD4(0, 0, 0, 0) + var motion = SIMD4(0, 1.5, 8, 0) +} + +private final class CRTGPU { + static let shared: CRTGPU? = { + guard let device = MTLCreateSystemDefaultDevice(), + let url = ConsoleMetalLibrary.url, + let library = try? device.makeLibrary(URL: url), + let vertex = library.makeFunction(name: "crtOverlayVertex"), + let fragment = library.makeFunction(name: "crtOverlayFragment"), + let queue = device.makeCommandQueue() else { return nil } + let descriptor = MTLRenderPipelineDescriptor() + descriptor.vertexFunction = vertex + descriptor.fragmentFunction = fragment + descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm + guard let pipeline = try? device.makeRenderPipelineState(descriptor: descriptor) else { return nil } + return CRTGPU(device: device, queue: queue, pipeline: pipeline) + }() + let device: MTLDevice + let queue: MTLCommandQueue + let pipeline: MTLRenderPipelineState + private init(device: MTLDevice, queue: MTLCommandQueue, pipeline: MTLRenderPipelineState) { + self.device = device + self.queue = queue + self.pipeline = pipeline + } +} diff --git a/Sources/Retrolemetry/ConsoleView.swift b/Sources/Retrolemetry/ConsoleView.swift new file mode 100644 index 0000000..6542894 --- /dev/null +++ b/Sources/Retrolemetry/ConsoleView.swift @@ -0,0 +1,2312 @@ +import AppKit +import SwiftUI +import Combine + +enum SceneTransitionStyle: String, CaseIterable, Identifiable { + case pan + case wipe + case syncRoll + + var id: String { rawValue } + + var title: String { + switch self { + case .pan: "Pan" + case .wipe: "Diagonal Wipe" + case .syncRoll: "Sync Roll" + } + } + + var duration: Double { + switch self { + case .pan: 0.78 + case .wipe: 0.92 + case .syncRoll: 0.84 + } + } +} + +enum SignalGridMetric: String, CaseIterable, Identifiable { + case cpu, network, disk + case gpu = "gpuProxy" // Preserve the saved picker value, now backed by actual GPU counters. + + var id: String { rawValue } + var title: String { + switch self { + case .cpu: "CPU" + case .gpu: "GPU" + case .network: "NETWORK" + case .disk: "DISK USED" + } + } + var shortTitle: String { + switch self { + case .cpu: "CPU" + case .gpu: "GPU" + case .network: "NET" + case .disk: "DSK" + } + } +} + +enum SignalGridPattern: String, CaseIterable, Identifiable { + case recede, terrainPulse, signalSweep + + var id: String { rawValue } + var title: String { + switch self { + case .recede: "Recede" + case .terrainPulse: "Terrain Pulse" + case .signalSweep: "Signal Sweep" + } + } +} + +enum SignalDisplayMode: String, CaseIterable, Identifiable { + case spinning + case gpuHorizon = "memoryHorizon" // Existing horizon selections survive the data-source change. + var id: String { rawValue } + var title: String { + switch self { + case .spinning: "Spinning signal" + case .gpuHorizon: "GPU at the horizon" + } + } +} + +enum SignalGridResponse: String, CaseIterable, Identifiable { + case low, medium, high + + var id: String { rawValue } + var title: String { rawValue.uppercased() } + var multiplier: Double { + switch self { + case .low: 0.55 + case .medium: 1.0 + case .high: 1.65 + } + } + var smoothingRate: Double { + switch self { + case .low: 0.8 + case .medium: 2.0 + case .high: 5.0 + } + } +} + +enum ConsoleScene: Int, CaseIterable { + case system, radar, signal, fullMetrics + + var title: String { + switch self { + case .system: "MARKET WATCH" + case .radar: "SECTOR SCAN" + case .signal: "SIGNAL ANALYSIS" + case .fullMetrics: "LIVE SYSTEM METRICS" + } + } + + var tabTitle: String { + switch self { + case .system: "Market" + case .radar: "Weather" + case .signal: "Signal" + case .fullMetrics: "Metrics" + } + } +} + +enum SceneOrder { + static let defaultValue = "0,1,2,3" + + static func parse(_ value: String) -> [ConsoleScene] { + var seen = Set() + var result = value + .split(separator: ",") + .compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } + .compactMap(ConsoleScene.init(rawValue:)) + .filter { seen.insert($0).inserted } + for scene in ConsoleScene.allCases where seen.insert(scene).inserted { + result.append(scene) + } + return result + } + + static func encode(_ scenes: [ConsoleScene]) -> String { + scenes.map { String($0.rawValue) }.joined(separator: ",") + } +} + +struct ConsoleView: View { + @ObservedObject var renderState: ConsoleRenderState + @StateObject private var telemetry = TelemetryModel() + @StateObject private var weather = WeatherModel() + @StateObject private var market = MarketModel() + @AppStorage("DockTelemetry.cycleDuration") private var cycleDuration = 30.0 + @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true + @AppStorage("DockTelemetry.sceneOrder") private var sceneOrderRaw = SceneOrder.defaultValue + @AppStorage("DockTelemetry.crtEnabled") private var crtEnabled = true + @AppStorage("DockTelemetry.bloomStrength") private var bloomStrength = 0.72 + @AppStorage("DockTelemetry.scanlineStrength") private var scanlineStrength = 0.22 + @AppStorage("DockTelemetry.noiseStrength") private var noiseStrength = 0.32 + @AppStorage("DockTelemetry.vhsTrackingEnabled") private var vhsTrackingEnabled = true + @AppStorage("DockTelemetry.trackingLine1Thickness") private var trackingLine1Thickness = 1.5 + @AppStorage("DockTelemetry.trackingLine2Thickness") private var trackingLine2Thickness = 8.0 + @AppStorage("DockTelemetry.phosphorBackgroundTint") private var phosphorBackgroundTint = 0.12 + @AppStorage("DockTelemetry.visualStyle") private var visualStyleRaw = ConsoleStyle.phosphor.rawValue + @AppStorage("DockTelemetry.sceneTransitionStyle") private var transitionStyleRaw = SceneTransitionStyle.pan.rawValue + @AppStorage("DockTelemetry.radarTargetMode") private var radarTargetModeRaw = RadarTargetMode.precipitation.rawValue + @AppStorage("DockTelemetry.animationFrameRate") private var animationFrameRate = 30.0 + @AppStorage("DockTelemetry.crtTubeEnabled") private var crtTubeEnabled = false + @AppStorage("DockTelemetry.crtTubeStrength") private var crtTubeStrength = 0.35 + @ObservedObject private var layouts = LayoutStore.shared + @State private var activeScene: ConsoleScene = .system + @State private var previousScene: ConsoleScene? + @State private var transitionProgress: CGFloat = 1 + @State private var transitionDirection = 1 + @State private var transitionGeneration = 0 + @State private var transitionStarted = 0.0 + @State private var nextSwitch = Date().addingTimeInterval(24) + @State private var marketTimeframe: MarketTimeframe = .today + private let sceneClock = Timer.publish(every: 0.25, on: .main, in: .common).autoconnect() + + init(renderState: ConsoleRenderState, preview: Bool = false, initialScene: ConsoleScene = .system) { + self.renderState = renderState + _activeScene = State(initialValue: initialScene) + _market = StateObject(wrappedValue: MarketModel(preview: preview)) + _weather = StateObject(wrappedValue: WeatherModel(preview: preview)) + } + + var body: some View { + let style = ConsoleStyle(rawValue: visualStyleRaw) ?? .phosphor + ThemeRuntime.palette = style.palette + let gpuVectors = VectorDisplay.isAvailable + return ZStack { + if renderState.isRendering { + ZStack { + ConsoleBackground(style: style, phosphorTintStrength: phosphorBackgroundTint) + .modifier(CRTTubeEffect(enabled: crtTubeEnabled, strength: crtTubeStrength)) + ConsoleTransitionSurface(progress: transitionProgress) { progress in + ZStack { + if gpuVectors { + ForEach(renderedScenes, id: \.self) { scene in + if scene != .fullMetrics { + VectorDisplay(configuration: vectorConfiguration(scene, progress: progress), paused: !renderState.isRendering, frameRate: animationFrameRate) + .allowsHitTesting(false) + } + } + } + transitioningScenes(time: 0, progress: progress) + .environment(\.consoleGPUVectors, gpuVectors) + .compositingGroup() + .shadow( + color: crtEnabled ? phosphor.opacity(0.24 * bloomStrength) : .clear, + radius: 2.5 + 3.5 * bloomStrength + ) + .modifier(CRTTubeEffect(enabled: crtTubeEnabled, strength: crtTubeStrength, opaqueBackground: false)) + } + } + } + if crtEnabled { + CRTOverlay( + scanlineStrength: scanlineStrength, + noiseStrength: noiseStrength, + vhsTrackingEnabled: vhsTrackingEnabled, + trackingLine1Thickness: trackingLine1Thickness, + trackingLine2Thickness: trackingLine2Thickness, + time: 0, + tubeStrength: crtTubeEnabled ? crtTubeStrength : 0 + ) + } + HorizontalScrollCapture(onDoubleClick: { + automaticCycleEnabled.toggle() + nextSwitch = Date().addingTimeInterval(cycleDuration) + }) { direction in + moveScene(direction) + } onClick: { point in + let point = CRTTubeGeometry.sourcePoint( + for: point, size: CGSize(width: 960, height: 540), + strength: crtTubeEnabled && CRTTubeEffect.isAvailable ? crtTubeStrength : 0 + ) + switch activeScene { + case .system: + for (module, offset) in [("marketTickerA", 0), ("marketTickerB", 5)] { + let frame = layouts.frame(.system, module) + if frame.visible, let row = MarketTickerGeometry.row(at: point, frame: frame, typography: layouts.typography(for: .system)), + offset + row < market.symbols.count { + market.focus(market.symbols[offset + row]) + return + } + } + let focus = layouts.frame(.system, "marketFocus") + guard focus.visible, focus.rect.contains(point) else { return } + marketTimeframe = marketTimeframe.next + case .radar: + let radar = layouts.frame(.radar, "radar") + guard radar.visible, radar.rect.contains(point) else { return } + let current = RadarTargetMode(rawValue: radarTargetModeRaw) ?? .precipitation + radarTargetModeRaw = current.next.rawValue + case .signal, .fullMetrics: + return + } + } + .frame(width: 960, height: 540) + } else { + Color.black + } + } + .frame(width: 960, height: 540) + .foregroundStyle(phosphor) + .consoleFont(14, role: .secondary, weight: .medium, fallback: .other) + .clipped() + .focusable() + .onKeyPress { press in + switch press.characters { + case "1": select(.system) + case "2": select(.radar) + case "3": select(.signal) + case "4": select(.fullMetrics) + case "0", "a", "A": + if automaticCycleEnabled { + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + default: return .ignored + } + return .handled + } + .environment(\.consoleAnimationEnabled, true) + .environment(\.consoleAnimationPaused, !renderState.isRendering) + .environment(\.consoleFrameRate, animationFrameRate) + .onAppear { + market.start() + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + .onDisappear { market.stop() } + .onReceive(sceneClock) { now in + guard renderState.isRendering, automaticCycleEnabled, now >= nextSwitch else { return } + let next = adjacentScene(from: activeScene, direction: 1) + changeScene(to: next, direction: 1) + nextSwitch = now.addingTimeInterval(cycleDuration) + } + .onChange(of: cycleDuration) { + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + .onChange(of: automaticCycleEnabled) { + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + .onChange(of: renderState.isRendering) { + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + } + + private func select(_ scene: ConsoleScene) { + let order = SceneOrder.parse(sceneOrderRaw) + let direction = (order.firstIndex(of: scene) ?? 0) >= (order.firstIndex(of: activeScene) ?? 0) ? 1 : -1 + changeScene(to: scene, direction: direction) + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + + private func moveScene(_ direction: Int) { + changeScene(to: adjacentScene(from: activeScene, direction: direction), direction: direction) + nextSwitch = Date().addingTimeInterval(cycleDuration) + } + + private func adjacentScene(from scene: ConsoleScene, direction: Int) -> ConsoleScene { + let order = SceneOrder.parse(sceneOrderRaw) + guard !order.isEmpty else { return .system } + let current = order.firstIndex(of: scene) ?? 0 + let next = (current + (direction >= 0 ? 1 : -1) + order.count) % order.count + return order[next] + } + + private func changeScene(to scene: ConsoleScene, direction: Int) { + guard scene != activeScene, previousScene == nil else { return } + let style = SceneTransitionStyle(rawValue: transitionStyleRaw) ?? .pan + transitionGeneration += 1 + let generation = transitionGeneration + transitionStarted = ProcessInfo.processInfo.systemUptime + previousScene = activeScene + activeScene = scene + transitionDirection = direction >= 0 ? 1 : -1 + transitionProgress = 0 + + DispatchQueue.main.async { + transitionStarted = ProcessInfo.processInfo.systemUptime + withAnimation(.timingCurve(0.30, 0.02, 0.18, 1.0, duration: style.duration)) { + transitionProgress = 1 + } + } + DispatchQueue.main.asyncAfter(deadline: .now() + style.duration + 0.08) { + guard transitionGeneration == generation else { return } + previousScene = nil + transitionProgress = 1 + } + } + + private var renderedScenes: [ConsoleScene] { + previousScene.map { [$0, activeScene] } ?? [activeScene] + } + private func vectorConfiguration(_ scene: ConsoleScene, progress: CGFloat) -> VectorConfiguration { + var configuration = VectorConfiguration(scene: scene, layouts: layouts, + snapshot: telemetry.snapshot, gpuHistory: telemetry.gpuHistory, weather: weather.snapshot, + tubeStrength: crtTubeEnabled ? crtTubeStrength : 0, bloom: crtEnabled ? bloomStrength : 0, + location: weather.snapshot.coordinate) + if previousScene != nil { + let style = SceneTransitionStyle(rawValue: transitionStyleRaw) ?? .pan + configuration.transition = ConsoleTransitionMotion(start: transitionStarted, duration: style.duration, + style: style, direction: transitionDirection, incoming: scene == activeScene) + configuration.transitionProgress = Float(progress) + } + return configuration + } + + @ViewBuilder + private func transitioningScenes(time: Double, progress: CGFloat) -> some View { + let style = SceneTransitionStyle(rawValue: transitionStyleRaw) ?? .pan + ZStack { + if let previousScene { + transitionedScene(previousScene, time: time, incoming: false, style: style, progress: progress) + } + if previousScene == nil { + sceneView(activeScene, time: time) + } else { + transitionedScene(activeScene, time: time, incoming: true, style: style, progress: progress) + } + if previousScene != nil { + transitionOverlay(style: style, progress: progress) + } + } + .frame(width: 960, height: 540) + .clipped() + } + + @ViewBuilder + private func transitionedScene(_ scene: ConsoleScene, time: Double, incoming: Bool, style: SceneTransitionStyle, progress: CGFloat) -> some View { + switch style { + case .pan: + sceneView(scene, time: time) + .offset(x: incoming + ? CGFloat(transitionDirection) * 960 * (1 - progress) + : -CGFloat(transitionDirection) * 960 * progress) + case .wipe: + if incoming { + sceneView(scene, time: time) + .mask(DiagonalWipeMask(progress: progress, direction: transitionDirection)) + } else { + sceneView(scene, time: time) + .mask(DiagonalWipeMask(progress: progress, direction: transitionDirection, inverted: true).fill(style: FillStyle(eoFill: true))) + } + case .syncRoll: + let halfProgress = incoming + ? max(0, min(1, (progress - 0.48) / 0.52)) + : max(0, min(1, progress / 0.52)) + let verticalScale = incoming + ? max(0.018, halfProgress) + : max(0.018, 1 - halfProgress) + sceneView(scene, time: time) + .scaleEffect(x: 1 + (1 - verticalScale) * 0.018, y: verticalScale, anchor: .center) + .offset(x: CGFloat(sin(Double(progress) * .pi * 15)) * (1 - verticalScale) * 11) + .opacity(incoming ? (progress >= 0.48 ? 1 : 0) : (progress < 0.52 ? 1 : 0)) + } + } + + private var sceneBackground: some View { + ConsoleBackground( + style: ConsoleStyle(rawValue: visualStyleRaw) ?? .phosphor, + phosphorTintStrength: phosphorBackgroundTint + ) + } + + @ViewBuilder + private func transitionOverlay(style: SceneTransitionStyle, progress: CGFloat) -> some View { + switch style { + case .pan: + EmptyView() + case .wipe: + DiagonalWipeEdge(progress: progress, direction: transitionDirection) + .foregroundStyle(phosphor) + case .syncRoll: + SyncRollBand(progress: progress) + } + } + + @ViewBuilder + private func sceneView(_ scene: ConsoleScene, time: Double) -> some View { + Group { switch scene { + case .system: + SystemScene(market: market, time: time, timeframe: marketTimeframe, location: weather.snapshot.coordinate) + case .radar: + RadarScene( + weather: weather.snapshot, + time: time + ) + case .signal: + SignalScene( + snapshot: telemetry.snapshot, + cpuHistory: telemetry.cpuHistory, + memoryHistory: telemetry.memoryHistory, + networkHistory: telemetry.networkHistory, + gpuHistory: telemetry.gpuHistory, + time: time + ) + case .fullMetrics: + FullMetricsScene( + snapshot: telemetry.snapshot, + cpuHistory: telemetry.cpuHistory, + memoryHistory: telemetry.memoryHistory, + networkReceiveHistory: telemetry.networkReceiveHistory, + networkTransmitHistory: telemetry.networkTransmitHistory, + gpuHistory: telemetry.gpuHistory, + time: time + ) + } } + .consoleFont(14, role: .secondary, weight: .medium, fallback: .other) + .environment(\.consoleTypography, layouts.typography(for: scene)) + } +} + +private struct DiagonalWipeMask: Shape { + var progress: CGFloat + let direction: Int + var inverted = false + + var animatableData: CGFloat { + get { progress } + set { progress = newValue } + } + + func path(in rect: CGRect) -> Path { + let slant: CGFloat = 94 + let top = progress * (rect.width + slant) - slant + let bottom = progress * (rect.width + slant) + var path = Path() + if direction >= 0 { + path.move(to: CGPoint(x: 0, y: 0)) + path.addLine(to: CGPoint(x: min(rect.width, max(0, top)), y: 0)) + path.addLine(to: CGPoint(x: min(rect.width, max(0, bottom)), y: rect.height)) + path.addLine(to: CGPoint(x: 0, y: rect.height)) + } else { + path.move(to: CGPoint(x: rect.width, y: 0)) + path.addLine(to: CGPoint(x: rect.width - min(rect.width, max(0, top)), y: 0)) + path.addLine(to: CGPoint(x: rect.width - min(rect.width, max(0, bottom)), y: rect.height)) + path.addLine(to: CGPoint(x: rect.width, y: rect.height)) + } + path.closeSubpath() + if inverted { + var inverse = Path(rect) + inverse.addPath(path) + return inverse + } + return path + } +} + +private struct DiagonalWipeEdge: View { + let progress: CGFloat + let direction: Int + + var body: some View { + Canvas { context, size in + let slant: CGFloat = 94 + let top = progress * (size.width + slant) - slant + let bottom = progress * (size.width + slant) + let topX = direction >= 0 ? top : size.width - top + let bottomX = direction >= 0 ? bottom : size.width - bottom + guard max(topX, bottomX) >= -12, min(topX, bottomX) <= size.width + 12 else { return } + var glow = Path() + glow.move(to: CGPoint(x: topX, y: 0)) + glow.addLine(to: CGPoint(x: bottomX, y: size.height)) + context.stroke(glow, with: .color(phosphor.opacity(0.22)), lineWidth: 14) + context.stroke(glow, with: .color(phosphor.opacity(0.95)), lineWidth: 2.2) + } + .allowsHitTesting(false) + } +} + +private struct SyncRollBand: View { + let progress: CGFloat + + var body: some View { + Canvas { context, size in + let y = size.height / 2 + let intensity = max(0, 1 - abs(progress - 0.5) * 2) + let bandHeight = 8 + intensity * 48 + context.fill( + Path(CGRect(x: 0, y: y - bandHeight / 2, width: size.width, height: bandHeight)), + with: .linearGradient( + Gradient(colors: [.clear, .black.opacity(0.82), phosphor.opacity(0.18), .black.opacity(0.72), .clear]), + startPoint: CGPoint(x: 0, y: y - bandHeight / 2), + endPoint: CGPoint(x: 0, y: y + bandHeight / 2) + ) + ) + for index in 0..<14 { + let start = CGFloat((index * 83 + Int(progress * 720)) % 900) + let length = CGFloat(22 + (index * 31) % 128) + let offset = CGFloat(index % 7) - 3 + context.fill( + Path(CGRect(x: start, y: y + offset * 3.1, width: length, height: index.isMultiple(of: 4) ? 2 : 1)), + with: .color((index.isMultiple(of: 3) ? Color.white : phosphor).opacity(0.10 + intensity * 0.34)) + ) + } + var edge = Path() + edge.move(to: CGPoint(x: 0, y: y)) + edge.addLine(to: CGPoint(x: size.width, y: y)) + context.stroke(edge, with: .color(phosphor.opacity(0.18 + intensity * 0.82)), lineWidth: 1.5 + intensity * 2.5) + } + .allowsHitTesting(false) + } +} + +struct HorizontalScrollCapture: NSViewRepresentable { + var onDoubleClick: () -> Void = {} + let onScroll: (Int) -> Void + let onClick: (CGPoint) -> Void + + func makeNSView(context: Context) -> HorizontalScrollView { + let view = HorizontalScrollView() + view.onScroll = onScroll + view.onClick = onClick + view.onDoubleClick = onDoubleClick + return view + } + + func updateNSView(_ nsView: HorizontalScrollView, context: Context) { + nsView.onScroll = onScroll + nsView.onClick = onClick + nsView.onDoubleClick = onDoubleClick + } +} + +final class HorizontalScrollView: NSView { + var onScroll: ((Int) -> Void)? + var onClick: ((CGPoint) -> Void)? + var onDoubleClick: (() -> Void)? + private var pendingClick: DispatchWorkItem? + private var accumulated: CGFloat = 0 + private var gestureTriggered = false + private var lastDirectEvent = Date.distantPast + private let preciseThreshold: CGFloat = 26 + private let gestureIdleTimeout: TimeInterval = 0.18 + + override var acceptsFirstResponder: Bool { false } + + override func mouseDown(with event: NSEvent) { + pendingClick?.cancel() + pendingClick = nil + if event.clickCount == 2 { + onDoubleClick?() + return + } + guard event.clickCount == 1 else { return } + let local = convert(event.locationInWindow, from: nil) + let point = CGPoint(x: local.x, y: isFlipped ? local.y : bounds.height - local.y) + let click = DispatchWorkItem { [weak self] in self?.onClick?(point) } + pendingClick = click + DispatchQueue.main.asyncAfter(deadline: .now() + NSEvent.doubleClickInterval, execute: click) + } + + deinit { pendingClick?.cancel() } + + override func scrollWheel(with event: NSEvent) { + pendingClick?.cancel() + pendingClick = nil + let now = Date() + + // Trackpad and Magic Mouse momentum often reverses slightly while settling. Treat + // momentum as part of the completed gesture instead of allowing it to change scenes. + guard event.momentumPhase.isEmpty else { return } + + if event.phase.contains(.began) || event.phase.contains(.mayBegin) || + (event.phase.isEmpty && now.timeIntervalSince(lastDirectEvent) > gestureIdleTimeout) { + resetScrollGesture() + } + if event.phase.contains(.cancelled) { + resetScrollGesture() + return + } + lastDirectEvent = now + + let horizontal = event.scrollingDeltaX + let vertical = event.scrollingDeltaY + guard abs(horizontal) > 0.01, abs(horizontal) >= abs(vertical) * 0.72 else { + if event.phase.contains(.ended) { resetScrollGesture() } + super.scrollWheel(with: event) + return + } + + guard !gestureTriggered else { + if event.phase.contains(.ended) { resetScrollGesture() } + return + } + + accumulated += horizontal + let threshold = event.hasPreciseScrollingDeltas ? preciseThreshold : 1 + guard abs(accumulated) >= threshold else { + if event.phase.contains(.ended) { resetScrollGesture() } + return + } + + let direction = accumulated < 0 ? 1 : -1 + gestureTriggered = true + onScroll?(direction) + + if event.phase.contains(.ended) { resetScrollGesture() } + } + + private func resetScrollGesture() { + accumulated = 0 + gestureTriggered = false + } +} + +struct FrameChrome: View { + let title: String + let section: String + let time: Double + @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true + + var body: some View { + ZStack { + Rectangle().stroke(phosphor.opacity(0.72), lineWidth: 1) + .padding(.horizontal, 14) + .padding(.vertical, 2) + VStack(spacing: 0) { + HStack { + Text("CG//DOCK NODE 01") + Spacer() + Text(title) + Spacer() + ConsoleTimeline(time: time, interval: 0.5) { tick in + Text("LINK \(Int(tick * 2).isMultiple(of: 2) ? "●" : "○") ACTIVE") + } + } + .consoleFont(13, role: .frameHeader, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.4) + .padding(.horizontal, 26) + .frame(height: 42) + Rectangle().fill(phosphor.opacity(0.6)).frame(height: 1).padding(.horizontal, 14) + Spacer() + HStack { + Text("MODE \(section)") + Spacer() + Text(automaticCycleEnabled + ? "AUTO CYCLE // 1–4 SELECT // 0 AUTO" + : "AUTO OFF // 1–4 SELECT // H-SCROLL") + } + .consoleFont(11, role: .frameFooter, weight: .semibold) + .lineLimit(1).minimumScaleFactor(0.4) + .padding(.horizontal, 26) + .frame(height: 30) + } + } + .allowsHitTesting(false) + } +} + +struct SystemScene: View { + @ObservedObject var market: MarketModel + let time: Double + var timeframe: MarketTimeframe = .today + var location: GlobeCoordinate? = nil + @Environment(\.consoleGPUVectors) private var gpuVectors + + var body: some View { + ZStack { + FrameChrome(title: "MARKET WATCH", section: "MKT", time: time) + LayoutModuleContainer(scene: .system, module: "globe") { + ZStack(alignment: .bottom) { + if !gpuVectors { + ConsoleTimeline(time: time) { tick in WireGlobe(time: tick, location: location) } + } + ConsoleTimeline(time: time, interval: 1) { _ in GlobeLegend(hasLocation: location != nil) } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + LayoutModuleContainer(scene: .system, module: "marketFocus") { + ConsoleTimeline(time: time, interval: 1) { tick in + MarketFocusPanel(market: market, time: tick, timeframe: timeframe) + } + } + LayoutModuleContainer(scene: .system, module: "marketClocks") { + ConsoleTimeline(time: time, interval: 1) { tick in MarketWorldClocks(time: tick) } + } + LayoutModuleContainer(scene: .system, module: "marketTickerA") { + MarketTickerList(market: market, startIndex: 0, title: "PORTFOLIO // A") + } + LayoutModuleContainer(scene: .system, module: "marketTickerB") { + MarketTickerList(market: market, startIndex: 5, title: "PORTFOLIO // B") + } + LayoutModuleContainer(scene: .system, module: "fxGraph") { + FXRatePanel(market: market) + } + } + } + +} + +struct FullMetricsScene: View { + let snapshot: TelemetrySnapshot + let cpuHistory: [Double] + let memoryHistory: [Double] + let networkReceiveHistory: [Double] + let networkTransmitHistory: [Double] + var gpuHistory: [Double?] = [] + let time: Double + + var body: some View { + ZStack { + FrameChrome(title: "LIVE SYSTEM METRICS", section: "DAT", time: time) + LayoutModuleContainer(scene: .fullMetrics, module: "metricCPU") { LargeMetricTile(label: "CPU LOAD", value: percent(snapshot.cpu), level: snapshot.cpu) } + LayoutModuleContainer(scene: .fullMetrics, module: "metricMemory") { + LargeMetricTile(label: "MEMORY", value: percent(snapshot.memory), level: snapshot.memory, + showsCapacity: true, capacity: snapshot.memoryCapacity) + .help("Used RAM is active + wired + compressed memory. Free is the remaining physical RAM, including cached/reclaimable memory. Amounts use decimal GB.") + } + LayoutModuleContainer(scene: .fullMetrics, module: "metricDisk") { + LargeMetricTile(label: "DISK USED", value: percent(snapshot.disk), level: snapshot.disk, + showsCapacity: true, capacity: snapshot.diskCapacity) + .help("Used and free capacity reported by macOS for the startup filesystem. Amounts use decimal GB/TB; refreshed every 30 seconds.") + } + LayoutModuleContainer(scene: .fullMetrics, module: "metricNetwork") { LargeMetricTile(label: "NETWORK RX", value: byteRate(snapshot.networkIn), level: min(1, snapshot.networkIn / 12_000_000)) } + LayoutModuleContainer(scene: .fullMetrics, module: "metricGPU") { + LargeMetricTile(label: "GPU BUSY", value: snapshot.gpu.map(percent) ?? "N/A", level: snapshot.gpu) + .help("Utilization reported by the busiest exposed GPU; N/A means the driver does not expose a reading.") + } + LayoutModuleContainer(scene: .fullMetrics, module: "metricPower") { PowerVoltageTile(reading: snapshot.power) } + LayoutModuleContainer(scene: .fullMetrics, module: "graphCPU") { LargeDataGraph(label: "CPU // 96 SEC", value: percent(snapshot.cpu), values: cpuHistory) } + LayoutModuleContainer(scene: .fullMetrics, module: "graphMemory") { LargeDataGraph(label: "MEMORY // 96 SEC", value: percent(snapshot.memory), values: memoryHistory) } + LayoutModuleContainer(scene: .fullMetrics, module: "graphNetwork") { + NetworkTrafficPanel(transmit: snapshot.networkOut, receiveHistory: networkReceiveHistory, + transmitHistory: networkTransmitHistory) + } + LayoutModuleContainer(scene: .fullMetrics, module: "graphGPU") { + LargeDataGraph(label: "GPU // 96 SEC", value: snapshot.gpu.map(percent) ?? "N/A", optionalValues: gpuHistory) + } + LayoutModuleContainer(scene: .fullMetrics, module: "statusUptime") { LargeStatusReadout(label: "UPTIME", value: snapshot.uptime.compactUptime) } + LayoutModuleContainer(scene: .fullMetrics, module: "statusLoad") { LargeStatusReadout(label: "LOAD 1 / 5 / 15", value: String(format: "%.1f %.1f %.1f", snapshot.load.0, snapshot.load.1, snapshot.load.2)) } + // Retain the saved module ID so existing custom layouts do not move or reset. + LayoutModuleContainer(scene: .fullMetrics, module: "statusTX") { LargeStatusReadout(label: "NETWORK RX", value: byteRate(snapshot.networkIn)) } + } + } + + private func percent(_ value: Double) -> String { + String(format: "%03.0f%%", value * 100) + } +} + +struct LargeMetricTile: View { + @Environment(\.consoleTypography) private var typography + let label: String + let value: String + let level: Double? + var showsCapacity = false + var capacity: CapacityReading? = nil + + var body: some View { + GeometryReader { geometry in + let valueSize = value.count > 7 ? 23.0 : 31.0 + // Capacity readouts use the spare horizontal space, not an extra row; + // keep the original label/percentage fit instead of shrinking them. + let requiredHeight = 13 * typography.secondary + valueSize * typography.primary + 29 + let fit = min(1, max(0.35, (geometry.size.height - 24) / requiredHeight)) + let capacityFit = min(fit, max(0.2, (geometry.size.height - 24 - 21 * fit) / (33 * typography.scale(.dark) + 8))) + VStack(alignment: .leading, spacing: 8 * fit) { + if showsCapacity { + CapacityMetricContents(label: label, value: value, capacity: capacity, fit: fit, capacityFit: capacityFit) + } else { + Text(label) + .consoleFont(13 * fit, role: .secondary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.55) + Text(value) + .consoleFont(valueSize * fit, role: .primary, weight: .bold) + .lineLimit(1) + .minimumScaleFactor(0.45) + } + HStack(spacing: 3) { + ForEach(0..<12, id: \.self) { index in + Rectangle() + .fill(Double(index) / 12 < (level ?? 0) ? phosphor : dimPhosphor) + } + } + .frame(height: 13 * fit) + } + .padding(12) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.2)) + } +} + +struct PowerVoltageTile: View { + @Environment(\.consoleTypography) private var typography + let reading: PowerReading + + var body: some View { + GeometryReader { geometry in + let requiredHeight = 11 * typography.secondary + 42 * typography.primary + 8 * typography.scale(.dark, fallback: .other) + 12 + let fit = min(1, max(0.35, (geometry.size.height - 20) / requiredHeight)) + VStack(alignment: .leading, spacing: 4 * fit) { + Text("POWER / VOLTAGE") + .consoleFont(11 * fit, role: .secondary, weight: .bold) + Text(reading.watts.map { String(format: "%.1f W", $0) } ?? "N/A W") + .consoleFont(23 * fit, role: .primary, weight: .bold) + Text(reading.voltage.map { String(format: "%.2f V", $0) } ?? "N/A V") + .consoleFont(19 * fit, role: .primary, weight: .bold) + Text(reading.status) + .consoleFont(8 * fit, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + } + .lineLimit(1).minimumScaleFactor(0.45) + .padding(10) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.2)) + .help("Battery electrical flow (voltage × current), not total Mac or CPU/GPU power. Sensors are optional on each Mac.") + } +} + +struct LargeDataGraph: View { + let label: String + let value: String + var values: [Double] = [] + var optionalValues: [Double?]? = nil + + var body: some View { + VStack(spacing: 0) { + DataGraphHeader(label: label, value: value) + + if let optionalValues { + LineGraph(optionalValues: optionalValues, showsBorder: false) + .overlay { + if !optionalValues.contains(where: { $0 != nil }) { + Text("GPU DATA UNAVAILABLE") + .consoleFont(10, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.55) + .padding(8) + } + } + } else { + LineGraph(values: values, showsBorder: false) + } + } + .overlay(Rectangle().stroke(dimPhosphor, lineWidth: 1)) + .clipped() + } +} + +struct LargeStatusReadout: View { + @Environment(\.consoleTypography) private var typography + let label: String + let value: String + + var body: some View { + GeometryReader { geometry in + let fit = min(1, max(0.25, (geometry.size.height - 16) / (11 * typography.scale(.secondary, dimmed: true) + 20 * typography.primary + 5))) + VStack(alignment: .leading, spacing: 5) { + Text(label) + .consoleFont(11 * fit, role: .secondary, weight: .bold) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.3) + Text(value) + .consoleFont(20 * fit, role: .primary, weight: .bold) + .lineLimit(1) + .minimumScaleFactor(0.5) + } + .padding(.horizontal, 12) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.2)) + } +} + +struct SegmentedMeter: View { + let label: String + let value: Double + let detail: String + + var body: some View { + HStack(spacing: 8) { + Text(label).frame(width: 34, alignment: .leading) + HStack(spacing: 3) { + ForEach(0..<20, id: \.self) { index in + Rectangle() + .fill(Double(index) / 20 < value ? phosphor : dimPhosphor) + .frame(width: 17, height: 17) + } + } + Text(detail).frame(width: 76, alignment: .trailing) + } + .consoleFont(12, role: .secondary, weight: .bold) + } +} + +struct Readout: View { + @Environment(\.consoleTypography) private var typography + let label: String + let value: String + + var body: some View { + GeometryReader { geometry in + let fit = min(1, max(0.2, (geometry.size.height - 18) / (9 * typography.scale(.secondary, dimmed: true) + 15 * typography.primary + 4))) + VStack(alignment: .leading, spacing: 4) { + Text(label).consoleFont(9 * fit, role: .secondary).consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.5) + Text(value).consoleFont(15 * fit, role: .primary, weight: .semibold) + .lineLimit(1).minimumScaleFactor(0.25) + } + .padding(9) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + .overlay(Rectangle().stroke(dimPhosphor, lineWidth: 1)) + } +} + +struct PulseIndicator: View { + let label: String + let active: Bool + let time: Double + + var body: some View { + HStack(spacing: 5) { + Circle().fill(active && sin(time * 4) > -0.2 ? phosphor : dimPhosphor).frame(width: 7, height: 7) + Text(label).consoleFont(9, role: .secondary, fallback: .other) + } + } +} + +struct LineGraph: View { + let values: [Double?] + var showsBorder = true + + init(values: [Double], showsBorder: Bool = true) { + self.values = values.map { $0 } + self.showsBorder = showsBorder + } + + init(optionalValues: [Double?], showsBorder: Bool = true) { + values = optionalValues + self.showsBorder = showsBorder + } + + var body: some View { + Canvas { context, size in + drawGrid(context: &context, size: size, columns: 12, rows: 4) + guard values.count > 1 else { return } + let plot = CGRect(x: 0, y: 6, width: size.width, height: max(0, size.height - 12)) + for segment in UsageHistoryGeometry.segments(values, in: plot) { + var path = Path() + for (index, point) in segment.enumerated() { + index == 0 ? path.move(to: point) : path.addLine(to: point) + } + if segment.count == 1, let point = segment.first { + context.fill(Path(ellipseIn: CGRect(x: point.x - 1.5, y: point.y - 1.5, width: 3, height: 3)), with: .color(phosphor)) + } else { + context.stroke(path, with: .color(phosphor), lineWidth: 2.2) + } + } + } + .overlay { + if showsBorder { + Rectangle().stroke(dimPhosphor, lineWidth: 1) + } + } + } +} + +struct WireGlobe: View { + let time: Double + var location: GlobeCoordinate? = nil + @AppStorage("DockTelemetry.globeWidthCorrection") private var widthCorrection = 1.10 + @AppStorage("DockTelemetry.globeHeightCorrection") private var heightCorrection = 0.9254 + + var body: some View { + Canvas { context, size in + let center = CGPoint(x: size.width / 2, y: size.height / 2) + let radius = min(size.width, size.height) * 0.41 + let rotation = time * 0.48 + let activity = TradingRegionActivity(at: Date()) + func screen(_ p: SIMD3) -> CGPoint { + CGPoint(x: center.x + p.x * radius, y: center.y + p.y * radius) + } + context.stroke(Path(ellipseIn: CGRect(x: center.x-radius, y: center.y-radius, width: radius*2, height: radius*2)), with: .color(phosphor), lineWidth: 1.4) + for latitude in stride(from: -60.0, through: 60.0, by: 20) { + let scale = cos(latitude * .pi / 180) + let y = center.y - sin(latitude * .pi / 180) * radius + context.stroke(Path(ellipseIn: CGRect(x: center.x-radius*scale, y: y-radius*0.1*scale, width: radius*scale*2, height: radius*0.2*scale)), with: .color(dimPhosphor), lineWidth: 1) + } + for index in 0..= 0 ? 0.92 : 0.46)), lineWidth: cos(longitude) >= 0 ? 1.05 : 0.7) + } + for edge in GlobeCoastlines.degrees { + let a = GlobeGeometry.project(latitude: Double(edge.y), longitude: Double(edge.x), rotation: rotation) + let b = GlobeGeometry.project(latitude: Double(edge.w), longitude: Double(edge.z), rotation: rotation) + let region = GlobeGeometry.region(longitude: Double(edge.x+edge.z)/2, latitude: Double(edge.y+edge.w)/2) + var line = Path(); line.move(to: screen(a)); line.addLine(to: screen(b)) + let active = activity[region] + context.stroke(line, with: .color((active ? phosphor : dimPhosphor).opacity(a.z >= 0 && b.z >= 0 ? (active ? 1 : 0.88) : 0.14)), lineWidth: active ? 1.7 : 1.05) + } + let markers: [(GlobeCoordinate?, Bool, Bool)] = [ + (location, true, true), + (GlobeCoordinate(latitude: 40.713, longitude: -74.006), activity.us, false), + (GlobeCoordinate(latitude: 51.507, longitude: -0.128), activity.europe, false), + (GlobeCoordinate(latitude: 35.690, longitude: 139.692), activity.asia, false) + ] + for (coordinate, active, local) in markers { + guard let coordinate else { continue } + let p = GlobeGeometry.project(latitude: coordinate.latitude, longitude: coordinate.longitude, rotation: rotation) + guard p.z >= 0 else { continue } + let point = screen(p) + let pulse = local ? 0.80 + (sin(time*3)+1)*0.25 : 1 + let color = active ? phosphor : dimPhosphor + context.fill(Path(ellipseIn: CGRect(x: point.x-2.3*pulse, y: point.y-2.3*pulse, width: 4.6*pulse, height: 4.6*pulse)), with: .color(color)) + context.stroke(Path(ellipseIn: CGRect(x: point.x-4.6*pulse, y: point.y-4.6*pulse, width: 9.2*pulse, height: 9.2*pulse)), with: .color(color.opacity(0.45)), lineWidth: 0.9) + } + var axis = Path(); axis.move(to: CGPoint(x: center.x,y: center.y-radius-9)); axis.addLine(to: CGPoint(x: center.x,y: center.y+radius+9)) + context.stroke(axis, with: .color(phosphor.opacity(0.5)), style: StrokeStyle(lineWidth: 1, dash: [4,5])) + } + .scaleEffect(x: widthCorrection, y: heightCorrection) + } +} + +struct GlobeLegend: View { + let hasLocation: Bool + var body: some View { + let activity = TradingRegionActivity(at: Date()) + HStack(spacing: 7) { + if hasLocation { Text("◎ LOCAL") } + Text("US \(activity.us ? "●" : "○")") + Text("EU \(activity.europe ? "●" : "○")") + Text("AS \(activity.asia ? "●" : "○")") + } + .consoleFont(7, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.6) + .padding(.bottom, 3) + .help("Region lights follow regular weekday sessions in New York, London/Frankfurt and Tokyo/Hong Kong. Holidays, early closes and extended trading are not included. The pulsing location uses the existing approximate weather location and stays on this Mac.") + } +} + +struct MarketFocusPanel: View { + @ObservedObject var market: MarketModel + @Environment(\.consoleTypography) private var typography + let time: Double + let timeframe: MarketTimeframe + + var body: some View { + let symbol = activeSymbol + GeometryReader { geometry in + let textHeight = (9 * typography.scale(.secondary, dimmed: true) + + max(17 * typography.scale(.secondary, fallback: .primary), 28 * typography.primary) + + max(13 * typography.primary, 8 * typography.scale(.dark, fallback: .other)) + + 8 * typography.scale(.secondary, fallback: .other)) * 1.2 + let fit = min(1, max(0.25, (geometry.size.height - 50 - max(24, geometry.size.height * 0.23)) / textHeight)) + VStack(alignment: .leading, spacing: 7) { + HStack { + Text("MARKET FEED // \(timeframe.label)") + Spacer() + Text("\(market.state.label) // CLICK") + } + .consoleFont(9 * fit, role: .secondary, weight: .bold) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.3) + + if let symbol, let quote = market.quotes[symbol] { + HStack(alignment: .firstTextBaseline) { + Text(symbol) + .consoleFont(17 * fit, role: .secondary, weight: .bold, fallback: .primary) + Spacer() + Text(marketPrice(quote.price)) + .consoleFont(28 * fit, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.3) + } + HStack { + Text(String(format: "%+.2f %+.2f%%", quote.change, quote.percentChange)) + .consoleFont(13 * fit, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.3) + Spacer() + Text("LAST \(marketTime(quote.tradeTime))") + .consoleFont(8 * fit, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.3) + } + let chartValues = market.chartValues(for: symbol, timeframe: timeframe) + MarketTrace(values: chartValues, quote: quote, includeDayRange: timeframe == .today) + .frame(maxHeight: .infinity) + .overlay(alignment: .topTrailing) { + if market.isLoadingChart(for: symbol, timeframe: timeframe) { + Text("LOADING \(timeframe.label)") + .consoleFont(7, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + .padding(4) + } else if market.isChartUnavailable(for: symbol, timeframe: timeframe), chartValues.isEmpty { + Text("RANGE UNAVAILABLE") + .consoleFont(7, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + .padding(4) + } + } + HStack { + Text(timeframe == .today + ? "O \(marketPrice(quote.open))" + : "START \(marketPrice(chartValues.first ?? quote.previousClose))") + Spacer() + Text(timeframe == .today + ? "L \(marketPrice(quote.low))" + : "LOW \(marketPrice(chartValues.min() ?? quote.low))") + Spacer() + Text(timeframe == .today + ? "H \(marketPrice(quote.high))" + : "HIGH \(marketPrice(chartValues.max() ?? quote.high))") + } + .consoleFont(8 * fit, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.3) + } else { + VStack(alignment: .leading, spacing: 8) { + Text(market.state == .needsAPIKey ? "FINNHUB KEY REQUIRED" : "AWAITING QUOTE DATA") + .consoleFont(15, role: .secondary, weight: .bold) + Text(market.state == .needsAPIKey + ? "OPEN SETTINGS // LIVE MARKET DATA" + : "CONNECTING TO LIVE US MARKET FEED") + .consoleFont(9, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) + } + } + .padding(11) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.1)) + .task(id: "\(symbol ?? "none"):\(timeframe.rawValue)") { + guard let symbol else { return } + while !Task.isCancelled { + await market.loadChart(for: symbol, timeframe: timeframe) + try? await Task.sleep(for: .seconds(timeframe.refreshInterval)) + } + } + } + + private var activeSymbol: String? { + if let focused = market.focusedSymbol, market.symbols.contains(focused) { return focused } + guard !market.symbols.isEmpty else { return nil } + return market.symbols[Int(time / 7) % market.symbols.count] + } +} + +struct MarketTrace: View { + let values: [Double] + let quote: MarketQuote + var includeDayRange = true + + var body: some View { + Canvas { context, size in + drawGrid(context: &context, size: size, columns: 6, rows: 3, strength: 0.48) + let samples = values.count > 1 ? values : [quote.previousClose, quote.price] + let low = includeDayRange ? min(samples.min() ?? quote.low, quote.low) : (samples.min() ?? quote.low) + let high = includeDayRange ? max(samples.max() ?? quote.high, quote.high) : (samples.max() ?? quote.high) + let span = max(0.0001, high - low) + var path = Path() + for (index, value) in samples.enumerated() { + let x = size.width * CGFloat(index) / CGFloat(max(1, samples.count - 1)) + let normalized = (value - low) / span + let y = size.height - 7 - CGFloat(normalized) * max(1, size.height - 14) + index == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + context.stroke(path, with: .color(phosphor), lineWidth: 1.8) + } + } +} + +struct MarketWorldClocks: View { + let time: Double + @AppStorage("DockTelemetry.marketClock1") private var clock1 = "America/New_York" + @AppStorage("DockTelemetry.marketClock2") private var clock2 = "America/Los_Angeles" + @AppStorage("DockTelemetry.marketClock3") private var clock3 = "Europe/London" + + var body: some View { + HStack(spacing: 10) { + clock(clock1) + clock(clock2) + clock(clock3) + } + .padding(10) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.1)) + } + + private func clock(_ identifier: String) -> some View { + let option = MarketClockZone.option(for: identifier) + let date = Date(timeIntervalSinceReferenceDate: time) + return VStack(spacing: 3) { + Text(option.shortTitle) + .consoleFont(8, role: .secondary, weight: .bold, fallback: .other) + .consoleDimmed() + .lineLimit(1) + .minimumScaleFactor(0.65) + Text(clockTime(date, identifier: option.id)) + .consoleFont(14, role: .primary, weight: .bold) + .monospacedDigit() + .lineLimit(1).minimumScaleFactor(0.3) + } + .frame(maxWidth: .infinity) + } +} + +struct MarketTickerList: View { + @Environment(\.consoleTypography) private var typography + @ObservedObject var market: MarketModel + let startIndex: Int + let title: String + + var body: some View { + VStack(spacing: 3) { + HStack { + Text(title) + Spacer() + Text("LAST").frame(width: 58, alignment: .trailing) + Text("CHANGE").frame(width: 56, alignment: .trailing) + } + .consoleFont(9, role: .secondary, weight: .bold) + .frame(height: MarketTickerGeometry.headerHeight(typography)) + .lineLimit(1).minimumScaleFactor(0.6) + .consoleDimmed() + Rectangle().fill(dimPhosphor.opacity(0.65)).frame(height: 1) + ForEach(0..<5, id: \.self) { row in + let index = startIndex + row + let symbol = index < market.symbols.count ? market.symbols[index] : nil + HStack(spacing: 5) { + Circle() + .fill(symbol.flatMap { market.quotes[$0] } == nil ? dimPhosphor : phosphor) + .frame(width: 6, height: 6) + Text(symbol ?? "AVAILABLE") + .consoleFont(9, role: .secondary, weight: .bold, fallback: .primary) + .consoleDimmed(symbol == nil) + .frame(width: 66, alignment: .leading) + Spacer() + if let symbol, let quote = market.quotes[symbol] { + Text(marketPrice(quote.price)).frame(width: 58, alignment: .trailing) + Text(String(format: "%+.2f%%", quote.percentChange)).frame(width: 56, alignment: .trailing) + } else { + Text("--").frame(width: 119, alignment: .trailing) + } + } + .consoleFont(9, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.6) + .frame(maxHeight: .infinity) + .background(symbol != nil && symbol == market.focusedSymbol ? phosphor.opacity(0.10) : .clear) + } + } + .padding(.horizontal, 9) + .padding(.vertical, 7) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.1)) + } +} + +struct FXRatePanel: View { + @ObservedObject var market: MarketModel + + var body: some View { + let points = market.usdIlsHistory + VStack(alignment: .leading, spacing: 4) { + HStack(alignment: .firstTextBaseline) { + Text("USD→ILS // DAILY REF") + .consoleFont(9, role: .secondary, weight: .bold) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.25) + Spacer() + if let latest = points.last { + Text(String(format: "%.4f", latest.rate)) + .consoleFont(14, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.25) + } else { + Text("LOADING") + .consoleFont(9, role: .secondary, weight: .bold, fallback: .other) + } + } + Canvas { context, size in + drawGrid(context: &context, size: size, columns: 6, rows: 3, strength: 0.35) + guard points.count > 1 else { return } + let values = points.map(\.rate) + let low = values.min() ?? 0 + let high = values.max() ?? 1 + let span = max(0.0001, high - low) + var path = Path() + for (index, point) in points.enumerated() { + let x = size.width * CGFloat(index) / CGFloat(points.count - 1) + let y = size.height - 5 - CGFloat((point.rate - low) / span) * max(1, size.height - 10) + index == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + context.stroke(path, with: .color(phosphor), lineWidth: 1.6) + } + .frame(maxHeight: .infinity) + if let first = points.first, let last = points.last { + HStack { + Text("24 SESSIONS") + Spacer() + Text(String(format: "%+.2f%%", ((last.rate / first.rate) - 1) * 100)) + } + .consoleFont(8, role: .dark, weight: .bold, fallback: .other) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.25) + } + } + .padding(8) + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.95), lineWidth: 1.1)) + } +} + +private func marketPrice(_ value: Double) -> String { + value < 1 ? String(format: "%.3f", value) : String(format: "%.2f", value) +} + +private func marketTime(_ date: Date) -> String { + date.formatted(date: .omitted, time: .standard) +} + +private func clockTime(_ date: Date, identifier: String) -> String { + var style = Date.FormatStyle(date: .omitted, time: .shortened) + style.timeZone = TimeZone(identifier: identifier) ?? .gmt + return date.formatted(style) +} + +enum RadarTargetMode: String, CaseIterable, Identifiable { + case precipitation, temperature, wind, decorative + + var id: String { rawValue } + var next: RadarTargetMode { + let values = Self.allCases + let index = values.firstIndex(of: self) ?? 0 + return values[(index + 1) % values.count] + } + var title: String { + switch self { + case .precipitation: "RAIN CHANCE // CURRENT HOUR" + case .temperature: "TEMPERATURE // REGIONAL" + case .wind: "WIND // SPEED + DIRECTION" + case .decorative: "DECORATIVE CONTACTS" + } + } + var shortTitle: String { + switch self { + case .precipitation: "RAIN CHANCE" + case .temperature: "TEMP NODES" + case .wind: "WIND FIELD" + case .decorative: "CONTACTS" + } + } +} + +struct RadarTargetSample { + let angle: Double + let radius: Double + let intensity: Double + var mapPosition: SIMD2 = .zero + var heading = 0.0 +} + +func radarTargets(for weather: WeatherSnapshot, mode: RadarTargetMode) -> [RadarTargetSample] { + if mode == .decorative { + return (0..<7).map { index in + RadarTargetSample( + angle: Double(index * 53), + radius: 0.25 + Double((index * 37) % 65) / 100, + intensity: 0.82 + ) + } + } + guard let update = weather.radarUpdatedAt, Date().timeIntervalSince(update) < 3600 else { return [] } + return weather.radarWeather.compactMap { sample in + guard let value = sample.value(for: mode), mode != .wind || sample.windDirection != nil else { return nil } + let intensity: Double + switch mode { + case .precipitation: intensity = value + case .temperature: intensity = (value + 5) / 45 + case .wind: intensity = value / 50 + case .decorative: intensity = 0 + } + return RadarTargetSample(angle: 0, radius: 0, intensity: min(1, max(0, intensity)), + mapPosition: RadarMapGeometry.position(latitude: sample.site.latitude, longitude: sample.site.longitude, region: weather.radarRegion ?? .israel), + heading: (sample.windDirection ?? 0) + 90) + } +} + +struct RadarScene: View { + let weather: WeatherSnapshot + let time: Double + @Environment(\.consoleTypography) private var typography + @Environment(\.consoleGPUVectors) private var gpuVectors + @AppStorage("DockTelemetry.weatherForecastDays") private var weatherForecastDays = 5 + @AppStorage("DockTelemetry.radarWidthCorrection") private var radarWidthCorrection = 1.10 + @AppStorage("DockTelemetry.radarHeightCorrection") private var radarHeightCorrection = 0.9254 + @AppStorage("DockTelemetry.radarTargetMode") private var radarTargetModeRaw = RadarTargetMode.precipitation.rawValue + @AppStorage("DockTelemetry.radarTargetPulse") private var radarTargetPulse = true + + private var radarTargetMode: RadarTargetMode { + RadarTargetMode(rawValue: radarTargetModeRaw) ?? .precipitation + } + + var body: some View { + ZStack { + FrameChrome(title: "WEATHER // \(weather.radarRegion?.screenTitle ?? "REGION") SCAN", section: "WX", time: time) + LayoutModuleContainer(scene: .radar, module: "radar") { + ZStack(alignment: .topLeading) { + if !gpuVectors { + ConsoleTimeline(time: time) { time in + Canvas { context, size in + let center = CGPoint(x: size.width / 2, y: size.height / 2) + let radius = min(size.width, size.height) * 0.47 + for ring in 1...4 { + let r = radius * CGFloat(ring) / 4 + context.stroke(Path(ellipseIn: CGRect(x: center.x-r, y: center.y-r, width: r*2, height: r*2)), with: .color(dimPhosphor.opacity(0.35)), lineWidth: 1.1) + } + for angle in stride(from: 0.0, to: 360.0, by: 30) { + let p = point(center: center, radius: radius, angle: angle) + var line = Path(); line.move(to: center); line.addLine(to: p) + context.stroke(line, with: .color(dimPhosphor.opacity(0.35)), lineWidth: 1.1) + } + let sweep = time * 42 + for trail in 0..<16 { + let angle = sweep - Double(trail) * 2.3 + var line = Path(); line.move(to: center); line.addLine(to: point(center: center, radius: radius, angle: angle)) + context.stroke(line, with: .color(phosphor.opacity(0.25 * (1 - Double(trail)/16))), lineWidth: 2) + } + let mapCenter = CGPoint(x: center.x + size.width * 0.10, y: center.y) + let mapEdges = weather.radarRegion.map { RadarMapGeometry.segments(for: $0) } ?? [] + for (index, edge) in mapEdges.enumerated() { + var path = Path() + path.move(to: CGPoint(x: mapCenter.x + CGFloat(edge.x)*radius, y: mapCenter.y + CGFloat(edge.y)*radius)) + path.addLine(to: CGPoint(x: mapCenter.x + CGFloat(edge.z)*radius, y: mapCenter.y + CGFloat(edge.w)*radius)) + let city = index >= (weather.radarRegion.map { RadarMapGeometry.countrySegmentCount(for: $0) } ?? 0) + context.stroke(path, with: .color(city ? dimPhosphor.opacity(1) : phosphor.opacity(0.92)), lineWidth: city ? 1.6 : 1.2) + } + let targets = radarTargets(for: weather, mode: radarTargetMode) + for (index, target) in targets.enumerated() { + let drift = radarTargetMode == .decorative ? sin(time * 0.15 + Double(index)) * 15 : 0 + let p = radarTargetMode == .decorative + ? point(center: center, radius: radius * target.radius, angle: target.angle + drift) + : CGPoint(x: mapCenter.x + CGFloat(target.mapPosition.x)*radius, y: mapCenter.y + CGFloat(target.mapPosition.y)*radius) + let pulse = radarTargetPulse ? 0.76 + (sin(time * 3.1 + Double(index) * 0.78) + 1) * 0.25 : 1 + let targetRadius = (2.1 + target.intensity * 5.6) * pulse + let opacity = 0.20 + target.intensity * 0.80 + if radarTargetPulse { + let haloRadius = targetRadius * 1.9 + context.stroke( + Path(ellipseIn: CGRect(x: p.x-haloRadius, y: p.y-haloRadius, width: haloRadius*2, height: haloRadius*2)), + with: .color(phosphor.opacity(opacity * 0.32)), + lineWidth: 0.8 + ) + } + switch radarTargetMode { + case .precipitation, .decorative: + context.fill( + Path(ellipseIn: CGRect(x: p.x-targetRadius, y: p.y-targetRadius, width: targetRadius*2, height: targetRadius*2)), + with: .color(phosphor.opacity(opacity)) + ) + case .temperature: + var diamond = Path() + diamond.move(to: CGPoint(x: p.x, y: p.y-targetRadius)) + diamond.addLine(to: CGPoint(x: p.x+targetRadius, y: p.y)) + diamond.addLine(to: CGPoint(x: p.x, y: p.y+targetRadius)) + diamond.addLine(to: CGPoint(x: p.x-targetRadius, y: p.y)) + diamond.closeSubpath() + context.stroke(diamond, with: .color(phosphor.opacity(opacity)), lineWidth: 1.4) + case .wind: + let heading = target.heading * .pi / 180 + let dx = cos(heading) * targetRadius * 1.8 + let dy = sin(heading) * targetRadius * 1.8 + var streak = Path() + streak.move(to: CGPoint(x: p.x-dx, y: p.y-dy)) + streak.addLine(to: CGPoint(x: p.x+dx, y: p.y+dy)) + let tip = CGPoint(x: p.x+dx, y: p.y+dy) + for offset in [-0.55, 0.55] { + streak.move(to: tip) + streak.addLine(to: CGPoint(x: tip.x - cos(heading+offset)*targetRadius, y: tip.y - sin(heading+offset)*targetRadius)) + } + context.stroke(streak, with: .color(phosphor.opacity(opacity)), lineWidth: 1.8) + } + } + } + .scaleEffect(x: radarWidthCorrection, y: radarHeightCorrection, anchor: .center) + } + } + RadarForecastLegend(weather: weather, mode: radarTargetMode) + } + } + LayoutModuleContainer(scene: .radar, module: "weatherHeader") { + GeometryReader { geometry in + let leftFit = min(1, max(0.2, (geometry.size.height - 4) / (11 * typography.scale(.dark, fallback: .secondary) + 18 * typography.scale(.secondary, fallback: .primary) + 3))) + let valueFit = min(1, max(0.2, (geometry.size.height - 4) / (40 * typography.primary))) + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 3) { + Text(weather.location) + .consoleFont(11 * leftFit, role: .dark, weight: .bold, fallback: .secondary) + .consoleDimmed() + Text(weather.localForecastIsAvailable ? weather.condition : "LOCAL FORECAST OFFLINE") + .consoleFont(18 * leftFit, role: .secondary, weight: .bold, fallback: .primary) + } + Spacer() + Text(weather.localForecastIsAvailable ? String(format: "%.0f°C", weather.temperature) : "N/A") + .consoleFont(40 * valueFit, role: .primary, weight: .bold) + } + .lineLimit(1).minimumScaleFactor(0.25) + .frame(maxHeight: .infinity, alignment: .center) + } + } + LayoutModuleContainer(scene: .radar, module: "weatherStats") { + HStack(spacing: 8) { + WeatherReadout(label: "FEELS", value: weather.localForecastIsAvailable ? String(format: "%.0f°C", weather.apparentTemperature) : "N/A") + WeatherReadout(label: "HUMID", value: weather.localForecastIsAvailable ? String(format: "%.0f%%", weather.humidity * 100) : "N/A") + WeatherReadout(label: "WIND", value: weather.localForecastIsAvailable ? String(format: "%.0f KM/H", weather.windSpeed) : "N/A") + WeatherReadout(label: "RAIN", value: weather.localForecastIsAvailable ? String(format: "%.1f MM", weather.precipitation) : "N/A") + } + } + LayoutModuleContainer(scene: .radar, module: "temperature") { + HourlyForecastPanel(weather: weather) + } + LayoutModuleContainer(scene: .radar, module: "precipitation") { + DailyForecastPanel(days: Array(weather.dailyForecast.prefix(weatherForecastDays))) + } + LayoutModuleContainer(scene: .radar, module: "weatherStatus") { + HStack { + Text(weather.radarStatus) + Spacer() + Text("FORECAST // CLICK RADAR") + } + .consoleFont(10, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.4) + } + } + } +} + +struct RadarForecastLegend: View { + let weather: WeatherSnapshot + let mode: RadarTargetMode + + var body: some View { + GeometryReader { size in + VStack(alignment: .leading, spacing: 5) { + Text(mode == .decorative ? "DEMO CONTACTS" : "\(weather.radarRegion?.screenTitle ?? "REGION") FORECAST") + .consoleFont(9, role: .secondary, weight: .bold) + Text(mode.shortTitle) + .consoleFont(10, role: .secondary, weight: .bold) + Spacer(minLength: 4) + if weather.radarRegion == nil { + Text("ALLOW LOCATION\nOR SELECT MAP\nIN SETTINGS") + .consoleFont(9, role: .secondary, weight: .bold) + .lineLimit(3) + } + if mode != .decorative { + ForEach(Array((weather.radarRegion?.sites ?? []).enumerated()), id: \.offset) { _, site in + VStack(alignment: .leading, spacing: 1) { + Text(site.name).consoleFont(8, role: .dark, weight: .bold, fallback: .secondary).consoleDimmed() + Text(readout(site)).consoleFont(13, role: .primary, weight: .bold) + } + .frame(maxHeight: .infinity, alignment: .center) + } + } + Spacer(minLength: 4) + Text(weather.radarRegion == .israel ? "TEL AVIV OUTLINED" : "REGIONAL POINTS") + .consoleFont(8, role: .dark, weight: .bold, fallback: .other).consoleDimmed() + Text(mode == .decorative ? "DECORATIVE" : "MODEL • NOT RADAR") + .consoleFont(7, role: .secondary, fallback: .other) + Text(weather.radarRegion == .israel ? "© OSM • Natural Earth" : "Natural Earth") + .consoleFont(6, role: .dark, fallback: .other).consoleDimmed() + } + .lineLimit(1).minimumScaleFactor(0.33) + .padding(7) + .frame(width: max(70, size.size.width * 0.27), height: size.size.height, alignment: .leading) + } + .allowsHitTesting(false) + } + + private func readout(_ site: RadarWeatherSite) -> String { + guard let updated = weather.radarUpdatedAt, Date().timeIntervalSince(updated) < 3600, + let sample = weather.radarWeather.first(where: { $0.site == site }) else { return "N/A" } + return sample.readout(for: mode) + } +} + +struct WeatherReadout: View { + @Environment(\.consoleTypography) private var typography + let label: String + let value: String + + var body: some View { + GeometryReader { geometry in + let fit = min(1, max(0.25, (geometry.size.height - 16) / (10 * typography.scale(.secondary, dimmed: true) + 15 * typography.primary + 4))) + VStack(alignment: .leading, spacing: 4) { + Text(label) + .consoleFont(10 * fit, role: .secondary, weight: .bold) + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.35) + Text(value) + .consoleFont(15 * fit, role: .primary, weight: .bold) + .lineLimit(1) + .minimumScaleFactor(0.35) + } + .padding(8) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1)) + } +} + +struct HourlyForecastPanel: View { + let weather: WeatherSnapshot + + var body: some View { + let points = weather.hourlyForecast + VStack(spacing: 0) { + HStack { + Text("HOURLY // NEXT 12").consoleFont(9, role: .secondary, weight: .bold) + Spacer(minLength: 3) + if let first = points.first, let last = points.last { + Text(String(format: "%.0f° → %.0f°", first.temperature, last.temperature)) + .consoleFont(9, role: .primary, weight: .bold) + } + } + .lineLimit(1).minimumScaleFactor(0.35) + .padding(.horizontal, 6).padding(.vertical, 5) + Canvas { context, size in + drawGrid(context: &context, size: size, columns: 6, rows: 3, strength: 0.42) + guard points.count > 1 else { return } + let temperatures = points.map(\.temperature) + let low = temperatures.min() ?? 0 + let high = temperatures.max() ?? 1 + let span = max(2, high - low) + var temperaturePath = Path() + for (index, point) in points.enumerated() { + let x = size.width * CGFloat(index) / CGFloat(points.count - 1) + let normalized = (point.temperature - low) / span + let y = 3 + max(0, size.height - 6) * (1 - CGFloat(normalized)) + index == 0 ? temperaturePath.move(to: CGPoint(x: x, y: y)) : temperaturePath.addLine(to: CGPoint(x: x, y: y)) + let rainHeight = CGFloat(point.precipitationChance) * min(24, size.height * 0.28) + let bar = CGRect(x: max(0, x - 2), y: max(0, size.height - rainHeight), width: 4, height: rainHeight) + context.fill(Path(bar), with: .color(dimPhosphor.opacity(0.85))) + } + context.stroke(temperaturePath, with: .color(phosphor), lineWidth: 1.7) + } + .clipped() + HStack { + ForEach(hourMarkers, id: \.time) { point in + Text(hourLabel(point.time)) + if point.time != hourMarkers.last?.time { Spacer() } + } + } + .consoleFont(7, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.35) + .consoleDimmed() + .padding(.horizontal, 6) + .padding(.bottom, 3) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1.2)) + } + + private var hourMarkers: [HourlyWeatherPoint] { + let points = weather.hourlyForecast + guard !points.isEmpty else { return [] } + return stride(from: 0, to: points.count, by: 3).map { points[$0] } + } +} + +struct DailyForecastPanel: View { + @Environment(\.consoleTypography) private var typography + let days: [DailyWeatherPoint] + + var body: some View { + GeometryReader { geometry in + let rowHeight = max(1, (geometry.size.height - 18 - 9 * typography.scale(.secondary, dimmed: true)) / Double(max(1, days.count))) + let fit = min(1, max(0.2, (rowHeight - 3) / max(13 * typography.primary, 8.5 * typography.scale(.secondary, fallback: .other)))) + VStack(spacing: 2) { + HStack(spacing: 6) { + Text("DAILY OUTLOOK // \(days.count) DAYS") + Spacer() + Text("LOW").frame(width: 52, alignment: .trailing) + Text("HIGH").frame(width: 52, alignment: .trailing) + Text("RAIN").frame(width: 68, alignment: .trailing) + } + .consoleFont(9, role: .secondary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.25) + .consoleDimmed() + .padding(.bottom, 2) + + if days.isEmpty { + Text("AWAITING DAILY FORECAST") + .consoleFont(9, role: .secondary, weight: .bold, fallback: .other) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + ForEach(Array(days.enumerated()), id: \.offset) { index, day in + HStack(spacing: 6) { + Text(index == 0 ? "TODAY" : dayLabel(day.date)) + .frame(width: 45, alignment: .leading) + Text(day.condition) + .consoleFont(8.5 * fit, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1) + .minimumScaleFactor(0.35) + Spacer(minLength: 3) + Text(String(format: "%.0f°", day.low)) + .consoleFont(13 * fit, role: .primary, weight: .bold) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.35) + .frame(width: 52, alignment: .trailing) + Text(String(format: "%.0f°", day.high)) + .consoleFont(13 * fit, role: .primary, weight: .bold) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.35) + .frame(width: 52, alignment: .trailing) + HStack(spacing: 2) { + ForEach(0..<5, id: \.self) { segment in + Rectangle() + .fill(Double(segment) / 5 < day.precipitationChance ? phosphor : dimPhosphor) + .frame(width: 7, height: 7) + } + } + Text(String(format: "%2.0f", day.precipitationChance * 100)) + .consoleFont(8.5 * fit, role: .primary, weight: .bold, fallback: .other) + .frame(width: 23, alignment: .trailing) + } + .consoleFont(8.5 * fit, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.35) + .frame(maxHeight: .infinity) + if index < days.count - 1 { + Rectangle().fill(dimPhosphor.opacity(0.35)).frame(height: 0.5) + } + } + } + } + .padding(7) + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1.2)) + } +} + +private func hourLabel(_ date: Date) -> String { + date.formatted(.dateTime.hour(.defaultDigits(amPM: .abbreviated))) +} + +private func dayLabel(_ date: Date) -> String { + date.formatted(.dateTime.weekday(.abbreviated)).uppercased() +} + +struct SignalScene: View { + @Environment(\.consoleTypography) private var typography + let snapshot: TelemetrySnapshot + let cpuHistory: [Double] + let memoryHistory: [Double] + let networkHistory: [Double] + var gpuHistory: [Double?] = [] + let time: Double + @Environment(\.consoleGPUVectors) private var gpuVectors + @AppStorage("DockTelemetry.signalGridMetric") private var gridMetricRaw = SignalGridMetric.cpu.rawValue + @AppStorage("DockTelemetry.signalDisplayMode") private var signalDisplayModeRaw = SignalDisplayMode.spinning.rawValue + @AppStorage("DockTelemetry.signalSynthwaveGrid") private var synthwaveGrid = false + @AppStorage("DockTelemetry.signalGridAnimationEnabled") private var gridAnimationEnabled = true + + private var gridMetricValue: Double { + switch SignalGridMetric(rawValue: gridMetricRaw) ?? .cpu { + case .cpu: + snapshot.cpu + case .gpu: + snapshot.gpu ?? 0 + case .network: + min(1, (snapshot.networkIn + snapshot.networkOut) / 12_000_000) + case .disk: + snapshot.disk + } + } + + private var gridMetricLabel: String { + let metric = SignalGridMetric(rawValue: gridMetricRaw) ?? .cpu + switch metric { + case .gpu where snapshot.gpu == nil: + return "GRID GPU N/A" + case .network: + return "GRID \(metric.shortTitle) \(byteRate(snapshot.networkIn + snapshot.networkOut))" + default: + return String(format: "GRID %@ %03.0f%%", metric.shortTitle, gridMetricValue * 100) + } + } + + var body: some View { + ZStack { + FrameChrome(title: "SIGNAL ANALYSIS", section: "SIG", time: time) + LayoutModuleContainer(scene: .signal, module: "scope") { + if gpuVectors { + GeometryReader { proxy in + Rectangle().stroke(dimPhosphor, lineWidth: 1) + if signalDisplayModeRaw == SignalDisplayMode.gpuHorizon.rawValue && !gpuHistory.contains(where: { $0 != nil }) { + let height = min(proxy.size.height * 0.26, proxy.size.height * 0.32 - min(proxy.size.height * 0.30, max(42, 13 * max(typography.primary, typography.secondary) + 26))) + Text("GPU DATA UNAVAILABLE") + .consoleFont(11, role: .secondary, weight: .bold, fallback: .other) + .position(x: proxy.size.width / 2, y: proxy.size.height * 0.32 - max(0, height) / 2) + } + } + } else { + ConsoleTimeline( + time: time, + interval: signalDisplayModeRaw == SignalDisplayMode.gpuHorizon.rawValue && !(synthwaveGrid && gridAnimationEnabled) ? 1 : nil + ) { tick in + SignalScope(time: tick, metricValue: gridMetricValue, gpuHistory: gpuHistory) + } + } + } + LayoutModuleContainer(scene: .signal, module: "signalHeader") { + HStack { + SignalChannelField(label: "GRID", value: gridMetricLabel.replacingOccurrences(of: "GRID ", with: "")) + Spacer() + SignalChannelField(label: "CH B", value: snapshot.gpu.map { String(format: "GPU %03.0f%%", $0 * 100) } ?? "GPU N/A") + Spacer() + if signalDisplayModeRaw == SignalDisplayMode.gpuHorizon.rawValue { + Text("GPU // 96 SEC") + } else { + ConsoleTimeline(time: time, interval: 0.25) { tick in + Text("PHASE \(Int(tick*22)%360)°") + } + } + } + .consoleFont(13, role: .secondary, weight: .bold, fallback: .other) + .lineLimit(1).minimumScaleFactor(0.6) + } + LayoutModuleContainer(scene: .signal, module: "cpuTrace") { MiniTrace(label: "CPU", values: cpuHistory, value: String(format: "%.0f%%", snapshot.cpu * 100)) } + LayoutModuleContainer(scene: .signal, module: "memoryTrace") { MiniTrace(label: "MEMORY", values: memoryHistory, value: String(format: "%.0f%%", snapshot.memory * 100)) } + LayoutModuleContainer(scene: .signal, module: "networkTrace") { MiniTrace(label: "NETWORK", values: networkHistory) } + LayoutModuleContainer(scene: .signal, module: "ioReadout") { Readout(label: "I/O RX / TX", value: "\(byteRate(snapshot.networkIn)) / \(byteRate(snapshot.networkOut))") } + } + } +} + +private struct SignalChannelField: View { + let label: String + let value: String + var body: some View { + HStack(spacing: 7) { + Text(label).consoleFont(13, role: .secondary, weight: .bold) + Text(value).consoleFont(13, role: .primary, weight: .bold) + } + } +} + +/// Own the fast-moving grid state inside the scope so it cannot invalidate data modules. +private struct SignalScope: View { + @Environment(\.consoleTypography) private var typography + let time: Double + let metricValue: Double + let gpuHistory: [Double?] + @AppStorage("DockTelemetry.signalDisplayMode") private var signalDisplayModeRaw = SignalDisplayMode.spinning.rawValue + @AppStorage("DockTelemetry.signalSynthwaveGrid") private var synthwaveGrid = false + @AppStorage("DockTelemetry.signalGridAnimationEnabled") private var gridAnimationEnabled = true + @AppStorage("DockTelemetry.signalGridPattern") private var gridPatternRaw = SignalGridPattern.recede.rawValue + @AppStorage("DockTelemetry.signalGridResponse") private var gridResponseRaw = SignalGridResponse.medium.rawValue + @State private var motion = SignalGridMotion() + @Environment(\.consoleAnimationPaused) private var paused + + var body: some View { + let frame = motion.sample(at: time) + Canvas { context, size in + let rect = CGRect(origin: .zero, size: size) + context.stroke(Path(rect), with: .color(dimPhosphor), lineWidth: 1) + if synthwaveGrid { + drawSynthwaveGrid( + context: &context, rect: rect, + travelPhase: frame.travel, wavePhase: frame.wave, + metricValue: frame.metric, + pattern: SignalGridPattern(rawValue: gridPatternRaw) ?? .recede, + responseGain: (SignalGridResponse(rawValue: gridResponseRaw) ?? .medium).multiplier + ) + } else { + drawGrid(context: &context, size: rect.size, columns: 16, rows: 8, origin: rect.origin, strength: 0.72) + } + if signalDisplayModeRaw == SignalDisplayMode.gpuHorizon.rawValue { + drawGPUHorizon(context: &context, rect: rect, history: gpuHistory, typography: typography) + } else { + let amplitude = 108 + sin(time * 0.19) * 7 + let continuousPhase = sin(time * 0.16) * 0.72 + for echo in stride(from: 3, through: 0, by: -1) { + var path = Path() + let lag = Double(echo) * 0.025 + for i in 0...360 { + let t = Double(i) / 360 * Double.pi * 2 + let x = rect.midX + CGFloat(sin(t * 3.04 + time * 0.82 - lag)) * amplitude * 2.05 + let y = rect.midY + CGFloat(sin(t * 4.07 + time * 0.61 + continuousPhase - lag)) * amplitude + i == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + let opacity = echo == 0 ? 1.0 : 0.11 + Double(3 - echo) * 0.075 + context.stroke(path, with: .color(phosphor.opacity(opacity)), lineWidth: echo == 0 ? 1.5 : 0.8) + } + } + } + .onAppear { + motion = SignalGridMotion(time: time, metric: metricValue, response: response, animated: gridAnimationEnabled && !paused) + } + .onChange(of: metricValue) { + updateMotion() + } + .onChange(of: gridResponseRaw) { updateMotion() } + .onChange(of: gridAnimationEnabled) { updateMotion() } + .onChange(of: paused) { updateMotion() } + } + + private var response: SignalGridResponse { SignalGridResponse(rawValue: gridResponseRaw) ?? .medium } + private func updateMotion() { + motion.retarget(at: time, metric: metricValue, response: response, animated: gridAnimationEnabled && !paused) + } +} + +private func drawGPUHorizon(context: inout GraphicsContext, rect: CGRect, history: [Double?], typography: ConsoleTypography) { + let horizon = rect.minY + rect.height * 0.32 + // Keep full-load peaks below the channel header, including large typography. + let topInset = min(rect.height * 0.30, max(42, 13 * max(typography.primary, typography.secondary) + 26)) + let height = max(0, min(rect.height * 0.26, horizon - rect.minY - topInset)) + let plot = CGRect(x: rect.minX, y: horizon - height, width: rect.width, height: height) + let segments = UsageHistoryGeometry.segments(history, in: plot) + for segment in segments { + guard let first = segment.first, let last = segment.last else { continue } + var trace = Path() + for (index, point) in segment.enumerated() { + index == 0 ? trace.move(to: point) : trace.addLine(to: point) + } + var fill = trace + fill.addLine(to: CGPoint(x: last.x, y: horizon)) + fill.addLine(to: CGPoint(x: first.x, y: horizon)) + fill.closeSubpath() + context.fill(fill, with: .linearGradient( + Gradient(colors: [phosphor.opacity(0.30), dimPhosphor.opacity(0.04)]), + startPoint: CGPoint(x: rect.midX, y: horizon - height), + endPoint: CGPoint(x: rect.midX, y: horizon) + )) + if segment.count == 1 { + context.fill(Path(ellipseIn: CGRect(x: first.x - 2, y: first.y - 2, width: 4, height: 4)), with: .color(phosphor)) + } else { + context.stroke(trace, with: .color(phosphor.opacity(0.14)), lineWidth: 6) + context.stroke(trace, with: .color(phosphor), lineWidth: 1.8) + } + } + if segments.isEmpty { + context.draw(Text("GPU DATA UNAVAILABLE").font(typography.font(11, role: .secondary, weight: .bold, fallback: .other)).foregroundStyle(phosphor), at: CGPoint(x: rect.midX, y: horizon - height / 2)) + } + var base = Path() + base.move(to: CGPoint(x: rect.minX, y: horizon)) + base.addLine(to: CGPoint(x: rect.maxX, y: horizon)) + context.stroke(base, with: .color(dimPhosphor), lineWidth: 1.3) +} + +private func drawSynthwaveGrid( + context: inout GraphicsContext, + rect: CGRect, + travelPhase: Double, + wavePhase: Double, + metricValue: Double, + pattern: SignalGridPattern, + responseGain: Double +) { + let horizon = rect.minY + rect.height * 0.32 + let bottom = rect.maxY + let centerX = rect.midX + let normalizedMetric = min(1, max(0, metricValue)) + let metricEnergy = pow(normalizedMetric, 0.72) * (0.72 + responseGain * 0.52) + let pulse = sin(wavePhase * 1.6) + + var longitudinal = Path() + for index in -10...10 { + let bottomX = centerX + CGFloat(index) * rect.width / 7.5 + var path = Path() + for step in 0...64 { + let depth = CGFloat(step) / 64 + let perspective = pow(depth, 1.58) + let x = centerX + (bottomX - centerX) * perspective + let xPhase = Double(index) * 0.43 + let phase: Double + let amplitude: Double + switch pattern { + case .recede: + phase = Double(depth) * 6.2 + xPhase + wavePhase * 0.16 + amplitude = 8.0 + metricEnergy * 24.0 + case .terrainPulse: + phase = Double(depth) * 7.4 + xPhase - wavePhase * 1.10 + amplitude = 10.0 + metricEnergy * (18.0 + (pulse + 1) * 18.0) + case .signalSweep: + phase = Double(depth) * 10.0 + xPhase - wavePhase * 1.35 + amplitude = 9.0 + metricEnergy * 34.0 + } + let terrain = sin(phase) * amplitude * Double(0.16 + perspective * 0.84) + let y = horizon + (bottom - horizon) * perspective + CGFloat(terrain) + step == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + longitudinal.addPath(path) + } + context.stroke(longitudinal, with: .color(dimPhosphor.opacity(0.78)), lineWidth: 0.9) + + for row in 0..<16 { + let patternTravel: Double + switch pattern { + case .recede: patternTravel = travelPhase + case .terrainPulse: patternTravel = sin(wavePhase * 0.7) * 0.025 + case .signalSweep: patternTravel = travelPhase * 0.45 + } + let rawDepth = Double(row) / 16 - patternTravel + let wrappedDepth = rawDepth - floor(rawDepth) + let depth = CGFloat(wrappedDepth) + let perspective = pow(depth, 1.82) + let yBase = horizon + (bottom - horizon) * perspective + var path = Path() + for step in 0...80 { + let xProgress = CGFloat(step) / 80 + let normalizedX = xProgress * 2 - 1 + let horizontalSpread = 0.16 + perspective * 1.18 + let x = centerX + normalizedX * rect.width * horizontalSpread + let phase: Double + let amplitude: Double + switch pattern { + case .recede: + phase = Double(normalizedX) * .pi * 2.2 + Double(depth) * 6.2 + wavePhase * 0.16 + amplitude = 8.0 + metricEnergy * 24.0 + case .terrainPulse: + phase = Double(normalizedX) * .pi * 2.6 + Double(depth) * 7.4 - wavePhase * 1.10 + amplitude = 10.0 + metricEnergy * (18.0 + (pulse + 1) * 18.0) + case .signalSweep: + phase = Double(normalizedX) * .pi * 3.0 + Double(depth) * 10.0 - wavePhase * 1.35 + amplitude = 9.0 + metricEnergy * 34.0 + } + let y = yBase + CGFloat(sin(phase) * amplitude) * (0.18 + perspective * 0.82) + step == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + context.stroke(path, with: .color(phosphor.opacity(0.38 + Double(perspective) * 0.56)), lineWidth: 0.8 + perspective * 1.0) + } + + var horizonPath = Path() + horizonPath.move(to: CGPoint(x: rect.minX, y: horizon)) + horizonPath.addLine(to: CGPoint(x: rect.maxX, y: horizon)) + context.stroke(horizonPath, with: .color(dimPhosphor.opacity(0.98)), lineWidth: 1.45) +} + +struct CompactMeter: View { + let label: String + let value: Double + + var body: some View { + HStack(spacing: 5) { + Text(label).frame(width: 38, alignment: .leading) + HStack(spacing: 2) { + ForEach(0..<10, id: \.self) { index in + Rectangle() + .fill(Double(index) / 10 < value ? phosphor : dimPhosphor) + .frame(height: 12) + } + } + Text(String(format: "%02.0f", value * 100)).frame(width: 30, alignment: .trailing) + } + .consoleFont(12, role: .secondary, weight: .bold, fallback: .other) + } +} + +struct MiniTrace: View { + let label: String + let values: [Double] + var value: String? = nil + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 4) { + Text(label) + .consoleFont(11, role: .secondary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.45) + Spacer(minLength: 0) + if let value { + Text(value) + .consoleFont(12, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.45) + } + } + .padding(.horizontal, 6).padding(.vertical, 4) + Canvas { context, size in + guard values.count > 1 else { return } + var path = Path() + for (index, value) in values.enumerated() { + let x = size.width * CGFloat(index) / CGFloat(values.count - 1) + let y = size.height - CGFloat(value) * (size.height - 14) - 3 + index == 0 ? path.move(to: CGPoint(x: x, y: y)) : path.addLine(to: CGPoint(x: x, y: y)) + } + context.stroke(path, with: .color(phosphor), lineWidth: 1.5) + } + } + .overlay(Rectangle().stroke(dimPhosphor.opacity(0.9), lineWidth: 1.2)) + .clipped() + } +} + +struct CRTOverlay: View { + let scanlineStrength: Double + let noiseStrength: Double + let vhsTrackingEnabled: Bool + let trackingLine1Thickness: Double + let trackingLine2Thickness: Double + let time: Double + var tubeStrength: Double = 0 + @Environment(\.consoleAnimationEnabled) private var animated + @Environment(\.consoleAnimationPaused) private var paused + @Environment(\.consoleFrameRate) private var frameRate + + @ViewBuilder + var body: some View { + if CRTDisplay.isAvailable { + CRTDisplay( + scanlines: scanlineStrength, noise: noiseStrength, + tracking: vhsTrackingEnabled, + firstThickness: trackingLine1Thickness, secondThickness: trackingLine2Thickness, + tubeStrength: tubeStrength, color: phosphor, paused: paused || !animated, frameRate: frameRate + ) + .allowsHitTesting(false) + } else { + staticOverlay + .modifier(CRTTubeEffect(enabled: tubeStrength > 0.001, strength: tubeStrength, opaqueBackground: false)) + } + } + + private var staticOverlay: some View { + ZStack { + if scanlineStrength > 0.001 { + Canvas { context, size in + let darkOpacity = 0.12 + scanlineStrength * 0.60 + let highlightOpacity = 0.025 + scanlineStrength * 0.14 + var darkLines = Path() + var highlights = Path() + for y in stride(from: 1.0, through: size.height, by: 4) { + darkLines.move(to: CGPoint(x: 0, y: y)) + darkLines.addLine(to: CGPoint(x: size.width, y: y)) + highlights.move(to: CGPoint(x: 0, y: y + 1.35)) + highlights.addLine(to: CGPoint(x: size.width, y: y + 1.35)) + } + context.stroke(darkLines, with: .color(.black.opacity(darkOpacity)), lineWidth: 1.15) + context.stroke(highlights, with: .color(phosphor.opacity(highlightOpacity)), lineWidth: 0.55) + } + } + if noiseStrength > 0.001 { + ConsoleTimeline(time: time, interval: 1.0 / 14.0) { tick in + Canvas { context, size in + let frames = CRTNoiseTextures.frames + guard !frames.isEmpty else { return } + let frame = frames[abs(Int(tick * 14)) % frames.count] + context.opacity = 0.035 + noiseStrength * 0.26 + let rect = CGRect(origin: .zero, size: size) + var grain = context.resolve(Image(decorative: frame.phosphor, scale: 1)) + grain.shading = .color(phosphor) + context.draw(grain, in: rect) + context.draw(Image(decorative: frame.white, scale: 1), in: rect) + } + } + } + if vhsTrackingEnabled { + ConsoleTimeline(time: time) { time in + Canvas { context, size in + let firstTravel = (time * 72).truncatingRemainder(dividingBy: size.height + 100) + drawTrackingBand( + context: &context, + size: size, + y: CGFloat(firstTravel) - 50, + thickness: trackingLine1Thickness, + strength: 0.78, + segmentFrame: Int(time * 9) + ) + + let secondTravel = (time * 43 + Double(size.height) * 0.53) + .truncatingRemainder(dividingBy: Double(size.height) + 150) + drawTrackingBand( + context: &context, + size: size, + y: CGFloat(secondTravel) - 75, + thickness: trackingLine2Thickness, + strength: 1.0, + segmentFrame: Int(time * 6) + 117 + ) + } + } + } + RadialGradient( + colors: [.clear, .clear, .black.opacity(0.30)], + center: .center, + startRadius: 180, + endRadius: 590 + ) + } + .allowsHitTesting(false) + } +} + +private func drawTrackingBand( + context: inout GraphicsContext, + size: CGSize, + y: CGFloat, + thickness: Double, + strength: Double, + segmentFrame: Int +) { + let lineWidth = max(0.5, CGFloat(thickness)) + let bandHeight = max(18, lineWidth * 4.2) + let band = CGRect(x: 0, y: y - bandHeight / 2, width: size.width, height: bandHeight) + context.fill( + Path(band), + with: .linearGradient( + Gradient(colors: [ + .clear, + .black.opacity(0.12 * strength), + phosphor.opacity(0.075 * strength), + .clear + ]), + startPoint: CGPoint(x: 0, y: band.minY), + endPoint: CGPoint(x: 0, y: band.maxY) + ) + ) + + var edge = Path() + edge.move(to: CGPoint(x: 0, y: y)) + edge.addLine(to: CGPoint(x: size.width, y: y)) + context.stroke(edge, with: .color(phosphor.opacity(0.34 * strength)), lineWidth: lineWidth) + + for index in 0..<13 { + let start = CGFloat((index * 137 + segmentFrame * 29) % 900) + let length = CGFloat(18 + (index * 23) % 96) + let offset = CGFloat((index % 5) - 2) * max(2.5, lineWidth * 0.65) + context.fill( + Path(CGRect(x: start, y: y + offset, width: length, height: max(1, lineWidth * 0.22))), + with: .color(Color.white.opacity((0.10 + Double(index % 3) * 0.035) * strength)) + ) + } +} + +func drawGrid( + context: inout GraphicsContext, + size: CGSize, + columns: Int, + rows: Int, + origin: CGPoint = .zero, + strength: Double = 0.62 +) { + var grid = Path() + for column in 0...columns { + let x = origin.x + size.width * CGFloat(column) / CGFloat(columns) + grid.move(to: CGPoint(x: x, y: origin.y)) + grid.addLine(to: CGPoint(x: x, y: origin.y + size.height)) + } + for row in 0...rows { + let y = origin.y + size.height * CGFloat(row) / CGFloat(rows) + grid.move(to: CGPoint(x: origin.x, y: y)) + grid.addLine(to: CGPoint(x: origin.x + size.width, y: y)) + } + context.stroke(grid, with: .color(dimPhosphor.opacity(strength)), lineWidth: 0.8) +} + +private func point(center: CGPoint, radius: CGFloat, angle: Double) -> CGPoint { + let radians = angle * .pi / 180 + return CGPoint(x: center.x + CGFloat(cos(radians)) * radius, y: center.y + CGFloat(sin(radians)) * radius) +} diff --git a/Sources/Retrolemetry/Globe.swift b/Sources/Retrolemetry/Globe.swift new file mode 100644 index 0000000..7b350d3 --- /dev/null +++ b/Sources/Retrolemetry/Globe.swift @@ -0,0 +1,64 @@ +import Foundation + +struct GlobeCoordinate: Equatable { + let latitude: Double + let longitude: Double + init?(latitude: Double, longitude: Double) { + guard latitude.isFinite, longitude.isFinite, (-90...90).contains(latitude), (-180...180).contains(longitude) else { return nil } + self.latitude = latitude; self.longitude = longitude + } +} + +enum GlobeGeometry { + static func project(latitude: Double, longitude: Double, rotation: Double) -> SIMD3 { + let lat = latitude * .pi / 180, lon = longitude * .pi / 180 + rotation + return SIMD3(cos(lat) * sin(lon), -sin(lat), cos(lat) * cos(lon)) + } + /// 16 complete pole-to-pole meridians, spread around all 360 degrees. + static let meridianCount = 16 + static func longitude(_ index: Int, rotation: Double) -> Double { Double(index) * 2 * .pi / Double(meridianCount) + rotation } + static func region(longitude: Double, latitude: Double) -> Int { + if (-130 ... -60).contains(longitude), (24...51).contains(latitude) { return 1 } + if (-20...45).contains(longitude), (34...72).contains(latitude) { return 2 } + if (60...155).contains(longitude), (-10...58).contains(latitude) { return 3 } + return 0 + } + /// Two float4 endpoints per edge; the first endpoint carries its region tag. + static let coastlines: [SIMD4] = GlobeCoastlines.degrees.flatMap { edge in + let region = region(longitude: Double(edge.x + edge.z) / 2, latitude: Double(edge.y + edge.w) / 2) + return [SIMD4(edge.x * .pi / 180, edge.y * .pi / 180, Float(region), 0), SIMD4(edge.z * .pi / 180, edge.w * .pi / 180, 0, 0)] + } +} + +struct TradingSession { + let zone: String + let ranges: [Range] + func isScheduledOpen(at date: Date) -> Bool { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: zone)! + let parts = calendar.dateComponents([.weekday, .hour, .minute], from: date) + guard let weekday = parts.weekday, (2...6).contains(weekday) else { return false } + let minute = (parts.hour ?? 0) * 60 + (parts.minute ?? 0) + return ranges.contains { $0.contains(minute) } + } +} + +/// Regular weekday sessions only: DST and lunch breaks, but no holiday/early-close feed. +struct TradingRegionActivity { + var us: Bool + var europe: Bool + var asia: Bool + static let newYork = TradingSession(zone: "America/New_York", ranges: [570..<960]) + static let london = TradingSession(zone: "Europe/London", ranges: [480..<990]) + static let frankfurt = TradingSession(zone: "Europe/Berlin", ranges: [540..<1050]) + static let tokyo = TradingSession(zone: "Asia/Tokyo", ranges: [540..<690, 750..<930]) + static let hongKong = TradingSession(zone: "Asia/Hong_Kong", ranges: [570..<720, 780..<960]) + init(at date: Date) { + us = Self.newYork.isScheduledOpen(at: date) + europe = Self.london.isScheduledOpen(at: date) || Self.frankfurt.isScheduledOpen(at: date) + asia = Self.tokyo.isScheduledOpen(at: date) || Self.hongKong.isScheduledOpen(at: date) + } + subscript(_ region: Int) -> Bool { + switch region { case 1: us; case 2: europe; case 3: asia; default: false } + } +} diff --git a/Sources/Retrolemetry/GlobeCoastlines.swift b/Sources/Retrolemetry/GlobeCoastlines.swift new file mode 100644 index 0000000..4fd8beb --- /dev/null +++ b/Sources/Retrolemetry/GlobeCoastlines.swift @@ -0,0 +1,918 @@ +// Made with Natural Earth. Public-domain 110m land data, simplified to 0.75 degrees. +// https://www.naturalearthdata.com/about/terms-of-use/ +// Regenerate using scripts/prepare_globe_data.mjs with ne_110m_land.geojson. +enum GlobeCoastlines { + static let degrees: [SIMD4] = [ + SIMD4(-45.155, -78.047, -43.333, -80.026), + SIMD4(-43.333, -80.026, -50.482, -81.025), + SIMD4(-50.482, -81.025, -53.988, -80.222), + SIMD4(-53.988, -80.222, -48.661, -78.047), + SIMD4(-48.661, -78.047, -45.155, -78.047), + SIMD4(-68.451, -70.956, -68.784, -72.171), + SIMD4(-68.784, -72.171, -71.076, -72.504), + SIMD4(-71.076, -72.504, -74.954, -72.073), + SIMD4(-74.954, -72.073, -73.916, -71.269), + SIMD4(-73.916, -71.269, -72.075, -71.191), + SIMD4(-72.075, -71.191, -71.742, -69.506), + SIMD4(-71.742, -69.506, -70.253, -68.879), + SIMD4(-70.253, -68.879, -68.451, -70.956), + SIMD4(-58.614, -64.152, -62.022, -64.799), + SIMD4(-62.022, -64.799, -62.12, -66.19), + SIMD4(-62.12, -66.19, -65.665, -67.954), + SIMD4(-65.665, -67.954, -61.807, -70.717), + SIMD4(-61.807, -70.717, -60.827, -73.695), + SIMD4(-60.827, -73.695, -70.601, -76.634), + SIMD4(-70.601, -76.634, -77.24, -76.713), + SIMD4(-77.24, -76.713, -73.656, -77.908), + SIMD4(-73.656, -77.908, -78.024, -79.182), + SIMD4(-78.024, -79.182, -58.222, -83.218), + SIMD4(-58.222, -83.218, -28.55, -80.338), + SIMD4(-28.55, -80.338, -29.686, -79.26), + SIMD4(-29.686, -79.26, -35.64, -79.456), + SIMD4(-35.64, -79.456, -35.777, -78.339), + SIMD4(-35.777, -78.339, -17.523, -75.126), + SIMD4(-17.523, -75.126, -15.701, -74.499), + SIMD4(-15.701, -74.499, -16.465, -73.872), + SIMD4(-16.465, -73.872, -15.447, -73.147), + SIMD4(-15.447, -73.147, -6.868, -70.932), + SIMD4(-6.868, -70.932, -0.229, -71.638), + SIMD4(-0.229, -71.638, 7.743, -69.894), + SIMD4(7.743, -69.894, 10.818, -70.834), + SIMD4(10.818, -70.834, 13.423, -69.972), + SIMD4(13.423, -69.972, 27.094, -70.462), + SIMD4(27.094, -70.462, 33.87, -68.503), + SIMD4(33.87, -68.503, 38.649, -69.776), + SIMD4(38.649, -69.776, 54.534, -65.818), + SIMD4(54.534, -65.818, 61.428, -67.954), + SIMD4(61.428, -67.954, 68.89, -67.934), + SIMD4(68.89, -67.934, 69.673, -69.228), + SIMD4(69.673, -69.228, 67.813, -70.305), + SIMD4(67.813, -70.305, 69.066, -70.678), + SIMD4(69.066, -70.678, 67.95, -71.853), + SIMD4(67.95, -71.853, 69.869, -72.265), + SIMD4(69.869, -72.265, 73.865, -69.874), + SIMD4(73.865, -69.874, 87.986, -66.21), + SIMD4(87.986, -66.21, 89.671, -67.15), + SIMD4(89.671, -67.15, 99.718, -67.249), + SIMD4(99.718, -67.249, 102.832, -65.563), + SIMD4(102.832, -65.563, 106.182, -66.935), + SIMD4(106.182, -66.935, 113.605, -65.877), + SIMD4(113.605, -65.877, 117.385, -66.915), + SIMD4(117.385, -66.915, 132.936, -66.386), + SIMD4(132.936, -66.386, 135.071, -65.309), + SIMD4(135.071, -65.309, 137.46, -66.955), + SIMD4(137.46, -66.955, 145.49, -66.915), + SIMD4(145.49, -66.915, 148.84, -68.385), + SIMD4(148.84, -68.385, 170.502, -71.403), + SIMD4(170.502, -71.403, 171.089, -72.088), + SIMD4(171.089, -72.088, 169.287, -73.656), + SIMD4(169.287, -73.656, 163.568, -76.243), + SIMD4(163.568, -76.243, 164.743, -78.183), + SIMD4(164.743, -78.183, 166.996, -78.751), + SIMD4(166.996, -78.751, 161.766, -79.162), + SIMD4(161.766, -79.162, 159.788, -80.945), + SIMD4(159.788, -80.945, 169.405, -83.826), + SIMD4(169.405, -83.826, 180, -84.713), + SIMD4(180, -84.713, 180, -90), + SIMD4(-180, -90, -180, -84.713), + SIMD4(-180, -84.713, -179.059, -84.139), + SIMD4(-179.059, -84.139, -143.108, -85.041), + SIMD4(-143.108, -85.041, -153.586, -83.689), + SIMD4(-153.586, -83.689, -152.862, -82.043), + SIMD4(-152.862, -82.043, -156.837, -81.102), + SIMD4(-156.837, -81.102, -146.418, -80.338), + SIMD4(-146.418, -80.338, -155.329, -79.064), + SIMD4(-155.329, -79.064, -158.365, -76.889), + SIMD4(-158.365, -76.889, -151.334, -77.399), + SIMD4(-151.334, -77.399, -146.104, -76.478), + SIMD4(-146.104, -76.478, -146.202, -75.38), + SIMD4(-146.202, -75.38, -135.215, -74.303), + SIMD4(-135.215, -74.303, -113.944, -73.715), + SIMD4(-113.944, -73.715, -107.559, -75.184), + SIMD4(-107.559, -75.184, -100.117, -74.871), + SIMD4(-100.117, -74.871, -103.681, -72.618), + SIMD4(-103.681, -72.618, -74.89, -73.872), + SIMD4(-74.89, -73.872, -67.369, -72.48), + SIMD4(-67.369, -72.48, -68.544, -69.717), + SIMD4(-68.544, -69.717, -67.741, -67.327), + SIMD4(-67.741, -67.327, -63.001, -64.642), + SIMD4(-63.001, -64.642, -57.224, -63.525), + SIMD4(-57.224, -63.525, -58.614, -64.152), + SIMD4(-67.75, -53.85, -65.05, -54.7), + SIMD4(-65.05, -54.7, -68.149, -55.612), + SIMD4(-68.149, -55.612, -73.285, -53.958), + SIMD4(-73.285, -53.958, -74.663, -52.837), + SIMD4(-74.663, -52.837, -71.108, -54.074), + SIMD4(-71.108, -54.074, -69.346, -52.518), + SIMD4(-69.346, -52.518, -67.75, -53.85), + SIMD4(145.398, -40.793, 148.289, -40.875), + SIMD4(148.289, -40.875, 147.565, -42.938), + SIMD4(147.565, -42.938, 146.048, -43.55), + SIMD4(146.048, -43.55, 145.398, -40.793), + SIMD4(173.02, -40.919, 174.248, -41.349), + SIMD4(174.248, -41.349, 173.08, -43.853), + SIMD4(173.08, -43.853, 168.411, -46.62), + SIMD4(168.411, -46.62, 166.509, -45.853), + SIMD4(166.509, -45.853, 173.02, -40.919), + SIMD4(174.612, -36.156, 176.763, -37.881), + SIMD4(176.763, -37.881, 178.517, -37.695), + SIMD4(178.517, -37.695, 175.068, -41.426), + SIMD4(175.068, -41.426, 173.824, -39.509), + SIMD4(173.824, -39.509, 174.697, -37.381), + SIMD4(174.697, -37.381, 172.636, -34.529), + SIMD4(172.636, -34.529, 174.612, -36.156), + SIMD4(50.057, -13.556, 50.377, -15.706), + SIMD4(50.377, -15.706, 47.096, -24.942), + SIMD4(47.096, -24.942, 44.04, -24.988), + SIMD4(44.04, -24.988, 43.433, -21.336), + SIMD4(43.433, -21.336, 44.447, -16.216), + SIMD4(44.447, -16.216, 47.705, -14.594), + SIMD4(47.705, -14.594, 49.195, -12.041), + SIMD4(49.195, -12.041, 50.057, -13.556), + SIMD4(143.562, -13.764, 145.375, -14.985), + SIMD4(145.375, -14.985, 146.387, -18.958), + SIMD4(146.387, -18.958, 148.848, -20.391), + SIMD4(148.848, -20.391, 153.136, -26.071), + SIMD4(153.136, -26.071, 152.892, -31.64), + SIMD4(152.892, -31.64, 149.424, -37.773), + SIMD4(149.424, -37.773, 146.318, -39.036), + SIMD4(146.318, -39.036, 145.032, -37.896), + SIMD4(145.032, -37.896, 143.61, -38.809), + SIMD4(143.61, -38.809, 140.639, -38.019), + SIMD4(140.639, -38.019, 138.121, -35.612), + SIMD4(138.121, -35.612, 138.208, -34.385), + SIMD4(138.208, -34.385, 136.829, -35.261), + SIMD4(136.829, -35.261, 137.81, -32.9), + SIMD4(137.81, -32.9, 135.989, -34.89), + SIMD4(135.989, -34.89, 134.274, -32.617), + SIMD4(134.274, -32.617, 131.326, -31.496), + SIMD4(131.326, -31.496, 116.625, -35.025), + SIMD4(116.625, -35.025, 115.027, -34.197), + SIMD4(115.027, -34.197, 115.802, -32.205), + SIMD4(115.802, -32.205, 114.616, -28.516), + SIMD4(114.616, -28.516, 113.339, -26.117), + SIMD4(113.339, -26.117, 114.233, -26.298), + SIMD4(114.233, -26.298, 113.394, -24.385), + SIMD4(113.394, -24.385, 114.15, -21.756), + SIMD4(114.15, -21.756, 114.225, -22.517), + SIMD4(114.225, -22.517, 120.856, -19.684), + SIMD4(120.856, -19.684, 125.686, -14.231), + SIMD4(125.686, -14.231, 129.621, -14.97), + SIMD4(129.621, -14.97, 132.357, -11.129), + SIMD4(132.357, -11.129, 136.492, -11.857), + SIMD4(136.492, -11.857, 135.5, -14.998), + SIMD4(135.5, -14.998, 140.215, -17.711), + SIMD4(140.215, -17.711, 142.515, -10.668), + SIMD4(142.515, -10.668, 143.562, -13.764), + SIMD4(108.623, -6.778, 110.76, -6.465), + SIMD4(110.76, -6.465, 115.706, -8.371), + SIMD4(115.706, -8.371, 110.586, -8.123), + SIMD4(110.586, -8.123, 105.365, -6.851), + SIMD4(105.365, -6.851, 106.052, -5.896), + SIMD4(106.052, -5.896, 108.623, -6.778), + SIMD4(134.143, -1.152, 135.458, -3.368), + SIMD4(135.458, -3.368, 138.33, -1.703), + SIMD4(138.33, -1.703, 144.584, -3.861), + SIMD4(144.584, -3.861, 147.648, -6.084), + SIMD4(147.648, -6.084, 147.192, -7.388), + SIMD4(147.192, -7.388, 150.691, -10.583), + SIMD4(150.691, -10.583, 147.913, -10.13), + SIMD4(147.913, -10.13, 144.744, -7.63), + SIMD4(144.744, -7.63, 142.628, -9.327), + SIMD4(142.628, -9.327, 137.614, -8.412), + SIMD4(137.614, -8.412, 138.669, -7.32), + SIMD4(138.669, -7.32, 137.928, -5.393), + SIMD4(137.928, -5.393, 132.984, -4.113), + SIMD4(132.984, -4.113, 131.99, -2.821), + SIMD4(131.99, -2.821, 133.696, -2.215), + SIMD4(133.696, -2.215, 130.52, -0.938), + SIMD4(130.52, -0.938, 134.143, -1.152), + SIMD4(125.241, 1.42, 123.686, 0.236), + SIMD4(123.686, 0.236, 120.183, 0.237), + SIMD4(120.183, 0.237, 120.936, -1.409), + SIMD4(120.936, -1.409, 123.341, -0.616), + SIMD4(123.341, -0.616, 121.508, -1.904), + SIMD4(121.508, -1.904, 123.162, -5.341), + SIMD4(123.162, -5.341, 121.489, -4.575), + SIMD4(121.489, -4.575, 120.972, -2.628), + SIMD4(120.972, -2.628, 120.431, -5.528), + SIMD4(120.431, -5.528, 119.367, -5.38), + SIMD4(119.367, -5.38, 118.768, -2.802), + SIMD4(118.768, -2.802, 120.036, 0.566), + SIMD4(120.036, 0.566, 125.241, 1.42), + SIMD4(105.818, -5.852, 102.584, -4.22), + SIMD4(102.584, -4.22, 95.293, 5.48), + SIMD4(95.293, 5.48, 97.485, 5.246), + SIMD4(97.485, 5.246, 103.838, 0.105), + SIMD4(103.838, 0.105, 103.438, -0.712), + SIMD4(103.438, -0.712, 106.109, -3.062), + SIMD4(106.109, -3.062, 105.818, -5.852), + SIMD4(117.876, 1.828, 118.997, 0.902), + SIMD4(118.997, 0.902, 117.812, 0.784), + SIMD4(117.812, 0.784, 116.148, -4.013), + SIMD4(116.148, -4.013, 114.865, -4.107), + SIMD4(114.865, -4.107, 110.224, -2.934), + SIMD4(110.224, -2.934, 108.953, 0.415), + SIMD4(108.953, 0.415, 110.396, 1.664), + SIMD4(110.396, 1.664, 116.725, 6.925), + SIMD4(116.725, 6.925, 119.182, 5.408), + SIMD4(119.182, 5.408, 117.313, 3.234), + SIMD4(117.313, 3.234, 117.876, 1.828), + SIMD4(126.377, 8.415, 125.397, 5.581), + SIMD4(125.397, 5.581, 123.61, 7.834), + SIMD4(123.61, 7.834, 122.826, 7.457), + SIMD4(122.826, 7.457, 121.92, 7.192), + SIMD4(121.92, 7.192, 125.412, 9.76), + SIMD4(125.412, 9.76, 126.377, 8.415), + SIMD4(121.321, 18.504, 122.516, 17.094), + SIMD4(122.516, 17.094, 121.729, 14.328), + SIMD4(121.729, 14.328, 123.95, 13.782), + SIMD4(123.95, 13.782, 124.077, 12.537), + SIMD4(124.077, 12.537, 123.298, 13.028), + SIMD4(123.298, 13.028, 120.07, 14.971), + SIMD4(120.07, 14.971, 121.321, 18.504), + SIMD4(-72.58, 19.872, -68.318, 18.612), + SIMD4(-68.318, 18.612, -71, 18.283), + SIMD4(-71, 18.283, -74.458, 18.343), + SIMD4(-74.458, 18.343, -72.335, 18.668), + SIMD4(-72.335, 18.668, -73.415, 19.64), + SIMD4(-73.415, 19.64, -72.58, 19.872), + SIMD4(-79.68, 22.765, -74.178, 20.285), + SIMD4(-74.178, 20.285, -77.755, 19.855), + SIMD4(-77.755, 19.855, -77.085, 20.413), + SIMD4(-77.085, 20.413, -79.285, 21.559), + SIMD4(-79.285, 21.559, -81.795, 22.637), + SIMD4(-81.795, 22.637, -84.975, 21.896), + SIMD4(-84.975, 21.896, -82.268, 23.189), + SIMD4(-82.268, 23.189, -79.68, 22.765), + SIMD4(140.976, 37.142, 140.253, 35.138), + SIMD4(140.253, 35.138, 135.793, 33.465), + SIMD4(135.793, 33.465, 135.079, 34.597), + SIMD4(135.079, 34.597, 130.986, 33.886), + SIMD4(130.986, 33.886, 132, 33.15), + SIMD4(132, 33.15, 130.686, 31.03), + SIMD4(130.686, 31.03, 129.408, 33.296), + SIMD4(129.408, 33.296, 132.618, 35.433), + SIMD4(132.618, 35.433, 135.678, 35.527), + SIMD4(135.678, 35.527, 136.724, 37.305), + SIMD4(136.724, 37.305, 139.426, 38.216), + SIMD4(139.426, 38.216, 139.883, 40.563), + SIMD4(139.883, 40.563, 141.369, 41.379), + SIMD4(141.369, 41.379, 140.976, 37.142), + SIMD4(143.91, 44.174, 145.321, 44.385), + SIMD4(145.321, 44.385, 145.543, 43.262), + SIMD4(145.543, 43.262, 139.955, 41.57), + SIMD4(139.955, 41.57, 141.968, 45.551), + SIMD4(141.968, 45.551, 143.91, 44.174), + SIMD4(-56.134, 50.687, -56.796, 49.812), + SIMD4(-56.796, 49.812, -53.477, 49.249), + SIMD4(-53.477, 49.249, -52.648, 47.536), + SIMD4(-52.648, 47.536, -53.521, 46.618), + SIMD4(-53.521, 46.618, -54.24, 47.752), + SIMD4(-54.24, 47.752, -55.401, 46.885), + SIMD4(-55.401, 46.885, -59.266, 47.603), + SIMD4(-59.266, 47.603, -57.359, 50.718), + SIMD4(-57.359, 50.718, -55.407, 51.588), + SIMD4(-55.407, 51.588, -56.134, 50.687), + SIMD4(143.648, 50.748, 144.654, 48.976), + SIMD4(144.654, 48.976, 143.174, 49.307), + SIMD4(143.174, 49.307, 142.559, 47.862), + SIMD4(142.559, 47.862, 143.505, 46.138), + SIMD4(143.505, 46.138, 142.092, 45.967), + SIMD4(142.092, 45.967, 142.136, 49.615), + SIMD4(142.136, 49.615, 142.21, 54.225), + SIMD4(142.21, 54.225, 143.648, 50.748), + SIMD4(-6.789, 52.26, -9.977, 51.82), + SIMD4(-9.977, 51.82, -9.689, 53.881), + SIMD4(-9.689, 53.881, -7.572, 55.132), + SIMD4(-7.572, 55.132, -5.662, 54.555), + SIMD4(-5.662, 54.555, -6.789, 52.26), + SIMD4(-3.005, 58.635, -4.074, 57.553), + SIMD4(-4.074, 57.553, -1.959, 57.685), + SIMD4(-1.959, 57.685, -3.119, 55.974), + SIMD4(-3.119, 55.974, 1.682, 52.74), + SIMD4(1.682, 52.74, 1.45, 51.289), + SIMD4(1.45, 51.289, -5.777, 50.16), + SIMD4(-5.777, 50.16, -3.415, 51.426), + SIMD4(-3.415, 51.426, -5.267, 51.991), + SIMD4(-5.267, 51.991, -2.945, 53.985), + SIMD4(-2.945, 53.985, -6.15, 56.785), + SIMD4(-6.15, 56.785, -5.01, 58.63), + SIMD4(-5.01, 58.63, -3.005, 58.635), + SIMD4(-85.161, 65.657, -80.103, 63.726), + SIMD4(-80.103, 63.726, -82.547, 63.652), + SIMD4(-82.547, 63.652, -87.222, 63.541), + SIMD4(-87.222, 63.541, -85.161, 65.657), + SIMD4(-14.509, 66.456, -13.61, 65.127), + SIMD4(-13.61, 65.127, -18.656, 63.496), + SIMD4(-18.656, 63.496, -23.955, 64.891), + SIMD4(-23.955, 64.891, -22.184, 65.085), + SIMD4(-22.184, 65.085, -24.326, 65.611), + SIMD4(-24.326, 65.611, -14.509, 66.456), + SIMD4(-175.014, 66.584, -169.9, 65.977), + SIMD4(-169.9, 65.977, -172.53, 65.438), + SIMD4(-172.53, 65.438, -172.955, 64.253), + SIMD4(-172.955, 64.253, -176.207, 65.357), + SIMD4(-176.207, 65.357, -178.686, 66.112), + SIMD4(-178.686, 66.112, -180, 64.98), + SIMD4(-180, 64.98, -180, 68.964), + SIMD4(-180, 68.964, -175.014, 66.584), + SIMD4(-90.547, 69.498, -90.552, 68.475), + SIMD4(-90.552, 68.475, -89.215, 69.259), + SIMD4(-89.215, 69.259, -87.35, 67.199), + SIMD4(-87.35, 67.199, -85.522, 69.882), + SIMD4(-85.522, 69.882, -82.622, 69.658), + SIMD4(-82.622, 69.658, -81.28, 69.162), + SIMD4(-81.28, 69.162, -81.259, 67.597), + SIMD4(-81.259, 67.597, -85.769, 66.558), + SIMD4(-85.769, 66.558, -93.157, 62.025), + SIMD4(-93.157, 62.025, -94.685, 58.949), + SIMD4(-94.685, 58.949, -93.215, 58.782), + SIMD4(-93.215, 58.782, -92.297, 57.087), + SIMD4(-92.297, 57.087, -82.273, 55.148), + SIMD4(-82.273, 55.148, -82.125, 53.277), + SIMD4(-82.125, 53.277, -79.913, 51.208), + SIMD4(-79.913, 51.208, -78.602, 52.562), + SIMD4(-78.602, 52.562, -79.83, 54.668), + SIMD4(-79.83, 54.668, -76.541, 56.534), + SIMD4(-76.541, 56.534, -78.517, 58.805), + SIMD4(-78.517, 58.805, -77.337, 59.853), + SIMD4(-77.337, 59.853, -78.107, 62.32), + SIMD4(-78.107, 62.32, -73.84, 62.444), + SIMD4(-73.84, 62.444, -69.59, 61.062), + SIMD4(-69.59, 61.062, -69.288, 58.957), + SIMD4(-69.288, 58.957, -67.65, 58.212), + SIMD4(-67.65, 58.212, -64.583, 60.336), + SIMD4(-64.583, 60.336, -61.799, 56.339), + SIMD4(-61.799, 56.339, -57.333, 54.627), + SIMD4(-57.333, 54.627, -55.683, 52.147), + SIMD4(-55.683, 52.147, -60.033, 50.243), + SIMD4(-60.033, 50.243, -66.399, 50.229), + SIMD4(-66.399, 50.229, -71.104, 46.822), + SIMD4(-71.104, 46.822, -65.056, 49.233), + SIMD4(-65.056, 49.233, -64.171, 48.742), + SIMD4(-64.171, 48.742, -65.115, 48.071), + SIMD4(-65.115, 48.071, -64.472, 46.239), + SIMD4(-64.472, 46.239, -61.521, 45.884), + SIMD4(-61.521, 45.884, -60.518, 47.008), + SIMD4(-60.518, 47.008, -59.803, 45.92), + SIMD4(-59.803, 45.92, -65.364, 43.545), + SIMD4(-65.364, 43.545, -66.162, 44.465), + SIMD4(-66.162, 44.465, -64.425, 45.292), + SIMD4(-64.425, 45.292, -67.137, 45.138), + SIMD4(-67.137, 45.138, -70.69, 43.03), + SIMD4(-70.69, 43.03, -69.965, 41.637), + SIMD4(-69.965, 41.637, -75.528, 39.498), + SIMD4(-75.528, 39.498, -75.94, 37.217), + SIMD4(-75.94, 37.217, -76.35, 39.15), + SIMD4(-76.35, 39.15, -76.96, 38.233), + SIMD4(-76.96, 38.233, -75.727, 35.551), + SIMD4(-75.727, 35.551, -81.336, 31.44), + SIMD4(-81.336, 31.44, -80.381, 25.206), + SIMD4(-80.381, 25.206, -84.1, 30.09), + SIMD4(-84.1, 30.09, -93.848, 29.714), + SIMD4(-93.848, 29.714, -96.594, 28.307), + SIMD4(-96.594, 28.307, -97.872, 22.444), + SIMD4(-97.872, 22.444, -96.292, 19.32), + SIMD4(-96.292, 19.32, -94.426, 18.144), + SIMD4(-94.426, 18.144, -92.037, 18.705), + SIMD4(-92.037, 18.705, -90.279, 21), + SIMD4(-90.279, 21, -87.052, 21.544), + SIMD4(-87.052, 21.544, -88.931, 15.887), + SIMD4(-88.931, 15.887, -83.41, 15.271), + SIMD4(-83.41, 15.271, -83.809, 11.103), + SIMD4(-83.809, 11.103, -81.439, 8.786), + SIMD4(-81.439, 8.786, -79.573, 9.612), + SIMD4(-79.573, 9.612, -76.837, 8.639), + SIMD4(-76.837, 8.639, -74.907, 11.083), + SIMD4(-74.907, 11.083, -71.754, 12.437), + SIMD4(-71.754, 12.437, -71.696, 9.072), + SIMD4(-71.696, 9.072, -69.943, 12.162), + SIMD4(-69.943, 12.162, -68.194, 10.555), + SIMD4(-68.194, 10.555, -61.881, 10.716), + SIMD4(-61.881, 10.716, -62.388, 9.948), + SIMD4(-62.388, 9.948, -57.147, 5.973), + SIMD4(-57.147, 5.973, -51.317, 4.203), + SIMD4(-51.317, 4.203, -49.974, 1.737), + SIMD4(-49.974, 1.737, -50.388, -0.078), + SIMD4(-50.388, -0.078, -44.906, -1.552), + SIMD4(-44.906, -1.552, -44.582, -2.691), + SIMD4(-44.582, -2.691, -39.979, -2.873), + SIMD4(-39.979, -2.873, -35.598, -5.149), + SIMD4(-35.598, -5.149, -34.73, -7.343), + SIMD4(-34.73, -7.343, -38.674, -13.058), + SIMD4(-38.674, -13.058, -40.945, -21.937), + SIMD4(-40.945, -21.937, -47.649, -24.885), + SIMD4(-47.649, -24.885, -48.888, -28.674), + SIMD4(-48.888, -28.674, -53.806, -34.397), + SIMD4(-53.806, -34.397, -58.427, -33.909), + SIMD4(-58.427, -33.909, -56.788, -36.901), + SIMD4(-56.788, -36.901, -59.232, -38.72), + SIMD4(-59.232, -38.72, -62.336, -38.828), + SIMD4(-62.336, -38.828, -62.746, -41.029), + SIMD4(-62.746, -41.029, -65.118, -41.064), + SIMD4(-65.118, -41.064, -63.458, -42.563), + SIMD4(-63.458, -42.563, -67.294, -45.552), + SIMD4(-67.294, -45.552, -65.641, -47.236), + SIMD4(-65.641, -47.236, -69.138, -50.732), + SIMD4(-69.138, -50.732, -68.15, -52.35), + SIMD4(-68.15, -52.35, -71.43, -53.856), + SIMD4(-71.43, -53.856, -74.947, -52.263), + SIMD4(-74.947, -52.263, -75.608, -48.674), + SIMD4(-75.608, -48.674, -74.127, -46.939), + SIMD4(-74.127, -46.939, -75.644, -46.648), + SIMD4(-75.644, -46.648, -72.718, -42.383), + SIMD4(-72.718, -42.383, -74.332, -43.225), + SIMD4(-74.332, -43.225, -73.588, -37.156), + SIMD4(-73.588, -37.156, -71.438, -32.419), + SIMD4(-71.438, -32.419, -70.164, -19.756), + SIMD4(-70.164, -19.756, -71.462, -17.363), + SIMD4(-71.462, -17.363, -76.009, -14.649), + SIMD4(-76.009, -14.649, -81.25, -6.137), + SIMD4(-81.25, -6.137, -79.77, -2.657), + SIMD4(-79.77, -2.657, -80.934, -1.057), + SIMD4(-80.934, -1.057, -77.128, 3.85), + SIMD4(-77.128, 3.85, -78.182, 8.319), + SIMD4(-78.182, 8.319, -79.558, 8.932), + SIMD4(-79.558, 8.932, -80.886, 7.221), + SIMD4(-80.886, 7.221, -85.661, 9.933), + SIMD4(-85.661, 9.933, -87.489, 13.297), + SIMD4(-87.489, 13.297, -103.501, 18.292), + SIMD4(-103.501, 18.292, -105.493, 19.947), + SIMD4(-105.493, 19.947, -106.029, 22.774), + SIMD4(-106.029, 22.774, -114.776, 31.8), + SIMD4(-114.776, 31.8, -114.674, 30.163), + SIMD4(-114.674, 30.163, -109.433, 23.186), + SIMD4(-109.433, 23.186, -112.182, 24.739), + SIMD4(-112.182, 24.739, -112.301, 26.012), + SIMD4(-112.301, 26.012, -115.055, 27.723), + SIMD4(-115.055, 27.723, -114.162, 28.566), + SIMD4(-114.162, 28.566, -117.296, 33.046), + SIMD4(-117.296, 33.046, -120.623, 34.609), + SIMD4(-120.623, 34.609, -124.398, 40.313), + SIMD4(-124.398, 40.313, -124.687, 48.185), + SIMD4(-124.687, 48.185, -122.587, 47.096), + SIMD4(-122.587, 47.096, -122.84, 49), + SIMD4(-122.84, 49, -127.436, 50.831), + SIMD4(-127.436, 50.831, -134.078, 58.123), + SIMD4(-134.078, 58.123, -147.114, 60.885), + SIMD4(-147.114, 60.885, -151.716, 59.156), + SIMD4(-151.716, 59.156, -150.621, 61.284), + SIMD4(-150.621, 61.284, -158.433, 55.994), + SIMD4(-158.433, 55.994, -164.786, 54.404), + SIMD4(-164.786, 54.404, -157.723, 57.57), + SIMD4(-157.723, 57.57, -157.042, 58.919), + SIMD4(-157.042, 58.919, -161.969, 58.672), + SIMD4(-161.969, 58.672, -161.874, 59.634), + SIMD4(-161.874, 59.634, -166.121, 61.5), + SIMD4(-166.121, 61.5, -164.563, 63.146), + SIMD4(-164.563, 63.146, -160.773, 63.766), + SIMD4(-160.773, 63.766, -160.778, 64.789), + SIMD4(-160.778, 64.789, -164.961, 64.447), + SIMD4(-164.961, 64.447, -168.11, 65.67), + SIMD4(-168.11, 65.67, -161.678, 66.116), + SIMD4(-161.678, 66.116, -166.764, 68.359), + SIMD4(-166.764, 68.359, -156.581, 71.358), + SIMD4(-156.581, 71.358, -136.504, 68.898), + SIMD4(-136.504, 68.898, -128.138, 70.484), + SIMD4(-128.138, 70.484, -108.88, 67.382), + SIMD4(-108.88, 67.382, -108.167, 68.654), + SIMD4(-108.167, 68.654, -106.15, 68.8), + SIMD4(-106.15, 68.8, -101.454, 67.647), + SIMD4(-101.454, 67.647, -97.669, 68.579), + SIMD4(-97.669, 68.579, -96.126, 67.294), + SIMD4(-96.126, 67.294, -94.233, 69.069), + SIMD4(-94.233, 69.069, -96.471, 70.09), + SIMD4(-96.471, 70.09, -95.209, 71.92), + SIMD4(-95.209, 71.92, -90.547, 69.498), + SIMD4(-114.167, 73.121, -109.92, 72.961), + SIMD4(-109.92, 72.961, -108.188, 71.651), + SIMD4(-108.188, 71.651, -108.396, 73.09), + SIMD4(-108.396, 73.09, -106.523, 73.076), + SIMD4(-106.523, 73.076, -104.465, 70.993), + SIMD4(-104.465, 70.993, -100.981, 70.024), + SIMD4(-100.981, 70.024, -102.731, 69.504), + SIMD4(-102.731, 69.504, -102.43, 68.753), + SIMD4(-102.43, 68.753, -107.123, 69.119), + SIMD4(-107.123, 69.119, -113.313, 68.536), + SIMD4(-113.313, 68.536, -117.34, 69.96), + SIMD4(-117.34, 69.96, -112.416, 70.366), + SIMD4(-112.416, 70.366, -117.905, 70.541), + SIMD4(-117.905, 70.541, -116.113, 71.309), + SIMD4(-116.113, 71.309, -119.402, 71.559), + SIMD4(-119.402, 71.559, -114.167, 73.121), + SIMD4(-86.562, 73.157, -82.316, 73.751), + SIMD4(-82.316, 73.751, -80.749, 72.062), + SIMD4(-80.749, 72.062, -77.825, 72.75), + SIMD4(-77.825, 72.75, -72.242, 71.557), + SIMD4(-72.242, 71.557, -66.969, 69.186), + SIMD4(-66.969, 69.186, -68.805, 68.72), + SIMD4(-68.805, 68.72, -61.852, 66.862), + SIMD4(-61.852, 66.862, -63.918, 64.999), + SIMD4(-63.918, 64.999, -68.015, 66.263), + SIMD4(-68.015, 66.263, -64.669, 63.393), + SIMD4(-64.669, 63.393, -68.783, 63.746), + SIMD4(-68.783, 63.746, -66.166, 61.931), + SIMD4(-66.166, 61.931, -74.834, 64.679), + SIMD4(-74.834, 64.679, -78.556, 64.573), + SIMD4(-78.556, 64.573, -73.96, 65.455), + SIMD4(-73.96, 65.455, -72.651, 67.285), + SIMD4(-72.651, 67.285, -77.287, 69.77), + SIMD4(-77.287, 69.77, -89.888, 71.223), + SIMD4(-89.888, 71.223, -89.437, 73.129), + SIMD4(-89.437, 73.129, -85.826, 73.804), + SIMD4(-85.826, 73.804, -86.562, 73.157), + SIMD4(-100.356, 73.844, -97.12, 73.47), + SIMD4(-97.12, 73.47, -98.054, 72.991), + SIMD4(-98.054, 72.991, -96.54, 72.56), + SIMD4(-96.54, 72.56, -96.72, 71.66), + SIMD4(-96.72, 71.66, -98.36, 71.273), + SIMD4(-98.36, 71.273, -102.5, 72.51), + SIMD4(-102.5, 72.51, -100.438, 72.706), + SIMD4(-100.438, 72.706, -101.54, 73.36), + SIMD4(-101.54, 73.36, -100.356, 73.844), + SIMD4(-93.196, 72.772, -95.41, 72.062), + SIMD4(-95.41, 72.062, -95.496, 73.862), + SIMD4(-95.496, 73.862, -90.51, 73.857), + SIMD4(-90.51, 73.857, -93.196, 72.772), + SIMD4(-120.46, 71.4, -125.929, 71.869), + SIMD4(-125.929, 71.869, -123.94, 73.68), + SIMD4(-123.94, 73.68, -124.918, 74.293), + SIMD4(-124.918, 74.293, -121.538, 74.449), + SIMD4(-121.538, 74.449, -115.511, 73.475), + SIMD4(-115.511, 73.475, -120.46, 71.4), + SIMD4(145.086, 75.563, 136.974, 75.262), + SIMD4(136.974, 75.262, 138.831, 76.137), + SIMD4(138.831, 76.137, 145.086, 75.563), + SIMD4(-98.5, 76.72, -98.16, 75), + SIMD4(-98.16, 75, -100.863, 75.641), + SIMD4(-100.863, 75.641, -102.566, 76.337), + SIMD4(-102.566, 76.337, -98.5, 76.72), + SIMD4(-108.211, 76.202, -105.705, 75.48), + SIMD4(-105.705, 75.48, -112.223, 74.417), + SIMD4(-112.223, 74.417, -113.871, 74.72), + SIMD4(-113.871, 74.72, -111.794, 75.162), + SIMD4(-111.794, 75.162, -116.312, 75.043), + SIMD4(-116.312, 75.043, -117.71, 75.222), + SIMD4(-117.71, 75.222, -115.405, 76.479), + SIMD4(-115.405, 76.479, -109.067, 75.473), + SIMD4(-109.067, 75.473, -110.497, 76.43), + SIMD4(-110.497, 76.43, -108.211, 76.202), + SIMD4(57.536, 70.72, 53.677, 70.763), + SIMD4(53.677, 70.763, 51.456, 72.015), + SIMD4(51.456, 72.015, 55.632, 75.081), + SIMD4(55.632, 75.081, 61.17, 76.252), + SIMD4(61.17, 76.252, 68.852, 76.545), + SIMD4(68.852, 76.545, 58.477, 74.309), + SIMD4(58.477, 74.309, 55.419, 72.371), + SIMD4(55.419, 72.371, 57.536, 70.72), + SIMD4(-94.684, 77.098, -89.187, 75.61), + SIMD4(-89.187, 75.61, -81.129, 75.714), + SIMD4(-81.129, 75.714, -80.458, 74.657), + SIMD4(-80.458, 74.657, -92.422, 74.838), + SIMD4(-92.422, 74.838, -93.894, 76.319), + SIMD4(-93.894, 76.319, -97.121, 76.751), + SIMD4(-97.121, 76.751, -94.684, 77.098), + SIMD4(-116.199, 77.645, -117.106, 76.53), + SIMD4(-117.106, 76.53, -122.855, 76.117), + SIMD4(-122.855, 76.117, -116.199, 77.645), + SIMD4(106.97, 76.974, 114.134, 75.848), + SIMD4(114.134, 75.848, 109.4, 74.18), + SIMD4(109.4, 74.18, 126.977, 73.565), + SIMD4(126.977, 73.565, 131.289, 70.787), + SIMD4(131.289, 70.787, 132.253, 71.836), + SIMD4(132.253, 71.836, 139.87, 71.488), + SIMD4(139.87, 71.488, 139.148, 72.416), + SIMD4(139.148, 72.416, 140.468, 72.849), + SIMD4(140.468, 72.849, 169.578, 68.694), + SIMD4(169.578, 68.694, 170.817, 69.014), + SIMD4(170.817, 69.014, 170.453, 70.097), + SIMD4(170.453, 70.097, 175.724, 69.877), + SIMD4(175.724, 69.877, 180, 68.964), + SIMD4(180, 68.964, 180, 64.98), + SIMD4(180, 64.98, 177.411, 64.608), + SIMD4(177.411, 64.608, 179.228, 62.304), + SIMD4(179.228, 62.304, 173.68, 61.653), + SIMD4(173.68, 61.653, 170.331, 59.882), + SIMD4(170.331, 59.882, 163.539, 59.869), + SIMD4(163.539, 59.869, 162.017, 58.243), + SIMD4(162.017, 58.243, 163.192, 57.615), + SIMD4(163.192, 57.615, 162.117, 54.855), + SIMD4(162.117, 54.855, 156.79, 51.011), + SIMD4(156.79, 51.011, 155.914, 56.768), + SIMD4(155.914, 56.768, 164.474, 62.551), + SIMD4(164.474, 62.551, 160.122, 60.544), + SIMD4(160.122, 60.544, 159.302, 61.774), + SIMD4(159.302, 61.774, 156.721, 61.435), + SIMD4(156.721, 61.435, 154.218, 59.758), + SIMD4(154.218, 59.758, 155.044, 59.145), + SIMD4(155.044, 59.145, 142.198, 59.04), + SIMD4(142.198, 59.04, 135.126, 54.73), + SIMD4(135.126, 54.73, 139.901, 54.19), + SIMD4(139.901, 54.19, 141.379, 52.239), + SIMD4(141.379, 52.239, 138.22, 46.308), + SIMD4(138.22, 46.308, 127.534, 39.757), + SIMD4(127.534, 39.757, 129.461, 36.784), + SIMD4(129.461, 36.784, 129.091, 35.083), + SIMD4(129.091, 35.083, 126.486, 34.39), + SIMD4(126.486, 34.39, 126.86, 36.894), + SIMD4(126.86, 36.894, 124.712, 38.108), + SIMD4(124.712, 38.108, 125.321, 39.552), + SIMD4(125.321, 39.552, 121.055, 38.898), + SIMD4(121.055, 38.898, 121.641, 40.946), + SIMD4(121.641, 40.946, 118.043, 39.204), + SIMD4(118.043, 39.204, 118.912, 37.448), + SIMD4(118.912, 37.448, 122.358, 37.455), + SIMD4(122.358, 37.455, 119.151, 34.91), + SIMD4(119.151, 34.91, 121.908, 31.692), + SIMD4(121.908, 31.692, 121.685, 28.226), + SIMD4(121.685, 28.226, 115.891, 22.783), + SIMD4(115.891, 22.783, 110.786, 21.397), + SIMD4(110.786, 21.397, 110.444, 20.341), + SIMD4(110.444, 20.341, 108.523, 21.715), + SIMD4(108.523, 21.715, 105.882, 19.752), + SIMD4(105.882, 19.752, 109.335, 13.426), + SIMD4(109.335, 13.426, 109.2, 11.667), + SIMD4(109.2, 11.667, 105.158, 8.6), + SIMD4(105.158, 8.6, 105.076, 9.919), + SIMD4(105.076, 9.919, 100.098, 13.407), + SIMD4(100.098, 13.407, 99.222, 9.239), + SIMD4(99.222, 9.239, 102.962, 5.524), + SIMD4(102.962, 5.524, 104.229, 1.293), + SIMD4(104.229, 1.293, 101.391, 2.761), + SIMD4(101.391, 2.761, 100.086, 6.464), + SIMD4(100.086, 6.464, 98.34, 7.794), + SIMD4(98.34, 7.794, 98.765, 11.441), + SIMD4(98.765, 11.441, 97.165, 16.929), + SIMD4(97.165, 16.929, 94.189, 16.038), + SIMD4(94.189, 16.038, 94.325, 18.214), + SIMD4(94.325, 18.214, 91.417, 22.765), + SIMD4(91.417, 22.765, 86.976, 21.495), + SIMD4(86.976, 21.495, 80.325, 15.899), + SIMD4(80.325, 15.899, 79.858, 10.357), + SIMD4(79.858, 10.357, 77.54, 7.966), + SIMD4(77.54, 7.966, 73.534, 15.991), + SIMD4(73.534, 15.991, 72.631, 21.356), + SIMD4(72.631, 21.356, 70.471, 20.877), + SIMD4(70.471, 20.877, 66.373, 25.425), + SIMD4(66.373, 25.425, 57.397, 25.74), + SIMD4(57.397, 25.74, 56.492, 27.143), + SIMD4(56.492, 27.143, 54.715, 26.481), + SIMD4(54.715, 26.481, 51.521, 27.866), + SIMD4(51.521, 27.866, 50.115, 30.148), + SIMD4(50.115, 30.148, 47.974, 29.976), + SIMD4(47.974, 29.976, 50.81, 24.755), + SIMD4(50.81, 24.755, 51.589, 25.801), + SIMD4(51.589, 25.801, 51.794, 24.02), + SIMD4(51.794, 24.02, 54.008, 24.122), + SIMD4(54.008, 24.122, 56.362, 26.396), + SIMD4(56.362, 26.396, 56.845, 24.242), + SIMD4(56.845, 24.242, 59.806, 22.31), + SIMD4(59.806, 22.31, 55.275, 17.228), + SIMD4(55.275, 17.228, 43.483, 12.637), + SIMD4(43.483, 12.637, 42.65, 16.775), + SIMD4(42.65, 16.775, 34.632, 28.058), + SIMD4(34.632, 28.058, 34.923, 29.501), + SIMD4(34.923, 29.501, 33.922, 27.649), + SIMD4(33.922, 27.649, 32.423, 29.851), + SIMD4(32.423, 29.851, 36.866, 22), + SIMD4(36.866, 22, 37.482, 18.614), + SIMD4(37.482, 18.614, 43.318, 12.39), + SIMD4(43.318, 12.39, 42.716, 11.736), + SIMD4(42.716, 11.736, 44.614, 10.442), + SIMD4(44.614, 10.442, 51.111, 12.025), + SIMD4(51.111, 12.025, 50.552, 9.199), + SIMD4(50.552, 9.199, 46.565, 2.855), + SIMD4(46.565, 2.855, 40.263, -2.573), + SIMD4(40.263, -2.573, 38.74, -5.909), + SIMD4(38.74, -5.909, 40.776, -14.692), + SIMD4(40.776, -14.692, 34.786, -19.784), + SIMD4(34.786, -19.784, 35.459, -24.123), + SIMD4(35.459, -24.123, 32.575, -25.727), + SIMD4(32.575, -25.727, 32.203, -28.752), + SIMD4(32.203, -28.752, 28.22, -32.772), + SIMD4(28.22, -32.772, 20.071, -34.795), + SIMD4(20.071, -34.795, 18.378, -34.136), + SIMD4(18.378, -34.136, 13.869, -21.699), + SIMD4(13.869, -21.699, 11.64, -16.673), + SIMD4(11.64, -16.673, 13.687, -10.731), + SIMD4(13.687, -10.731, 11.915, -5.038), + SIMD4(11.915, -5.038, 8.798, -1.111), + SIMD4(8.798, -1.111, 9.404, 3.734), + SIMD4(9.404, 3.734, 8.5, 4.772), + SIMD4(8.5, 4.772, 5.898, 4.263), + SIMD4(5.898, 4.263, 4.326, 6.271), + SIMD4(4.326, 6.271, -1.965, 4.711), + SIMD4(-1.965, 4.711, -9.005, 4.833), + SIMD4(-9.005, 4.833, -16.614, 12.171), + SIMD4(-16.614, 12.171, -17.625, 14.73), + SIMD4(-17.625, 14.73, -16.146, 18.109), + SIMD4(-16.146, 18.109, -16.973, 21.886), + SIMD4(-16.973, 21.886, -14.44, 26.255), + SIMD4(-14.44, 26.255, -9.565, 29.934), + SIMD4(-9.565, 29.934, -9.301, 32.565), + SIMD4(-9.301, 32.565, -5.93, 35.76), + SIMD4(-5.93, 35.76, -2.17, 35.169), + SIMD4(-2.17, 35.169, 9.51, 37.35), + SIMD4(9.51, 37.35, 11.1, 36.9), + SIMD4(11.1, 36.9, 10.34, 33.786), + SIMD4(10.34, 33.786, 19.086, 30.266), + SIMD4(19.086, 30.266, 21.543, 32.843), + SIMD4(21.543, 32.843, 28.914, 30.87), + SIMD4(28.914, 30.87, 33.773, 30.968), + SIMD4(33.773, 30.968, 36.161, 36.651), + SIMD4(36.161, 36.651, 27.641, 36.659), + SIMD4(27.641, 36.659, 26.171, 39.464), + SIMD4(26.171, 39.464, 33.513, 42.019), + SIMD4(33.513, 42.019, 38.348, 40.949), + SIMD4(38.348, 40.949, 41.703, 41.963), + SIMD4(41.703, 41.963, 36.675, 45.245), + SIMD4(36.675, 45.245, 39.121, 47.263), + SIMD4(39.121, 47.263, 34.962, 46.273), + SIMD4(34.962, 46.273, 36.335, 45.113), + SIMD4(36.335, 45.113, 33.883, 44.362), + SIMD4(33.883, 44.362, 32.454, 45.328), + SIMD4(32.454, 45.328, 33.299, 46.081), + SIMD4(33.299, 46.081, 30.749, 46.583), + SIMD4(30.749, 46.583, 27.674, 42.578), + SIMD4(27.674, 42.578, 28.807, 41.055), + SIMD4(28.807, 41.055, 22.626, 40.257), + SIMD4(22.626, 40.257, 24.04, 37.655), + SIMD4(24.04, 37.655, 23.115, 37.92), + SIMD4(23.115, 37.92, 22.49, 36.41), + SIMD4(22.49, 36.41, 19.406, 40.251), + SIMD4(19.406, 40.251, 19.54, 41.72), + SIMD4(19.54, 41.72, 13.142, 45.737), + SIMD4(13.142, 45.737, 12.589, 44.091), + SIMD4(12.589, 44.091, 18.48, 40.169), + SIMD4(18.48, 40.169, 16.87, 40.442), + SIMD4(16.87, 40.442, 16.101, 37.986), + SIMD4(16.101, 37.986, 15.414, 40.048), + SIMD4(15.414, 40.048, 8.889, 44.366), + SIMD4(8.889, 44.366, 3.101, 43.075), + SIMD4(3.101, 43.075, -2.146, 36.674), + SIMD4(-2.146, 36.674, -5.377, 35.947), + SIMD4(-5.377, 35.947, -8.899, 36.869), + SIMD4(-8.899, 36.869, -9.393, 43.027), + SIMD4(-9.393, 43.027, -1.384, 44.023), + SIMD4(-1.384, 44.023, -1.194, 46.015), + SIMD4(-1.194, 46.015, -4.592, 48.684), + SIMD4(-4.592, 48.684, -1.617, 48.644), + SIMD4(-1.617, 48.644, -1.933, 49.776), + SIMD4(-1.933, 49.776, 1.339, 50.127), + SIMD4(1.339, 50.127, 4.706, 53.092), + SIMD4(4.706, 53.092, 8.122, 53.528), + SIMD4(8.122, 53.528, 8.544, 57.11), + SIMD4(8.544, 57.11, 10.58, 57.73), + SIMD4(10.58, 57.73, 10.912, 56.459), + SIMD4(10.912, 56.459, 9.65, 55.47), + SIMD4(9.65, 55.47, 10.94, 54.009), + SIMD4(10.94, 54.009, 19.661, 54.426), + SIMD4(19.661, 54.426, 21.268, 55.19), + SIMD4(21.268, 55.19, 21.582, 57.412), + SIMD4(21.582, 57.412, 24.121, 57.026), + SIMD4(24.121, 57.026, 24.429, 58.383), + SIMD4(24.429, 58.383, 23.34, 59.187), + SIMD4(23.34, 59.187, 29.118, 60.028), + SIMD4(29.118, 60.028, 21.322, 60.72), + SIMD4(21.322, 60.72, 21.536, 63.19), + SIMD4(21.536, 63.19, 25.398, 65.112), + SIMD4(25.398, 65.112, 22.183, 65.724), + SIMD4(22.183, 65.724, 17.848, 62.75), + SIMD4(17.848, 62.75, 17.12, 61.341), + SIMD4(17.12, 61.341, 18.788, 60.082), + SIMD4(18.788, 60.082, 16.829, 58.72), + SIMD4(16.829, 58.72, 15.88, 56.104), + SIMD4(15.88, 56.104, 12.943, 55.362), + SIMD4(12.943, 55.362, 10.357, 59.47), + SIMD4(10.357, 59.47, 8.382, 58.313), + SIMD4(8.382, 58.313, 5.666, 58.588), + SIMD4(5.666, 58.588, 4.992, 61.971), + SIMD4(4.992, 61.971, 14.761, 67.811), + SIMD4(14.761, 67.811, 24.547, 71.031), + SIMD4(24.547, 71.031, 28.166, 71.185), + SIMD4(28.166, 71.185, 41.06, 67.457), + SIMD4(41.06, 67.457, 38.383, 66), + SIMD4(38.383, 66, 33.185, 66.633), + SIMD4(33.185, 66.633, 34.815, 65.9), + SIMD4(34.815, 65.9, 34.944, 64.414), + SIMD4(34.944, 64.414, 37.013, 63.85), + SIMD4(37.013, 63.85, 37.176, 65.143), + SIMD4(37.176, 65.143, 39.594, 64.521), + SIMD4(39.594, 64.521, 42.093, 66.476), + SIMD4(42.093, 66.476, 43.95, 66.069), + SIMD4(43.95, 66.069, 43.453, 68.571), + SIMD4(43.453, 68.571, 46.25, 68.25), + SIMD4(46.25, 68.25, 46.821, 67.69), + SIMD4(46.821, 67.69, 45.562, 67.01), + SIMD4(45.562, 67.01, 46.349, 66.668), + SIMD4(46.349, 66.668, 53.718, 68.857), + SIMD4(53.718, 68.857, 59.942, 68.279), + SIMD4(59.942, 68.279, 61.078, 68.941), + SIMD4(61.078, 68.941, 60.55, 69.85), + SIMD4(60.55, 69.85, 68.512, 68.092), + SIMD4(68.512, 68.092, 69.181, 68.616), + SIMD4(69.181, 68.616, 66.93, 69.455), + SIMD4(66.93, 69.455, 66.695, 71.029), + SIMD4(66.695, 71.029, 69.196, 72.844), + SIMD4(69.196, 72.844, 72.588, 72.776), + SIMD4(72.588, 72.776, 71.848, 71.409), + SIMD4(71.848, 71.409, 73.668, 68.408), + SIMD4(73.668, 68.408, 71.28, 66.32), + SIMD4(71.28, 66.32, 72.423, 66.173), + SIMD4(72.423, 66.173, 75.052, 67.76), + SIMD4(75.052, 67.76, 73.602, 69.628), + SIMD4(73.602, 69.628, 74.4, 70.632), + SIMD4(74.4, 70.632, 73.101, 71.447), + SIMD4(73.101, 71.447, 74.659, 72.832), + SIMD4(74.659, 72.832, 76.359, 71.153), + SIMD4(76.359, 71.153, 75.903, 71.874), + SIMD4(75.903, 71.874, 77.577, 72.267), + SIMD4(77.577, 72.267, 81.5, 71.75), + SIMD4(81.5, 71.75, 80.511, 73.648), + SIMD4(80.511, 73.648, 86.822, 73.937), + SIMD4(86.822, 73.937, 86.01, 74.46), + SIMD4(86.01, 74.46, 87.167, 75.117), + SIMD4(87.167, 75.117, 104.352, 77.698), + SIMD4(104.352, 77.698, 106.97, 76.974), + SIMD4(18.252, 79.702, 21.544, 78.956), + SIMD4(21.544, 78.956, 17.118, 76.809), + SIMD4(17.118, 76.809, 13.171, 78.025), + SIMD4(13.171, 78.025, 10.445, 79.652), + SIMD4(10.445, 79.652, 18.252, 79.702), + SIMD4(25.448, 80.407, 27.408, 80.056), + SIMD4(27.408, 80.056, 18.462, 79.86), + SIMD4(18.462, 79.86, 17.368, 80.319), + SIMD4(17.368, 80.319, 25.448, 80.407), + SIMD4(99.94, 78.881, 91.181, 80.341), + SIMD4(91.181, 80.341, 95.941, 81.25), + SIMD4(95.941, 81.25, 100.187, 79.78), + SIMD4(100.187, 79.78, 99.94, 78.881), + SIMD4(-87.02, 79.66, -85.814, 79.337), + SIMD4(-85.814, 79.337, -90.804, 78.215), + SIMD4(-90.804, 78.215, -96.076, 79.705), + SIMD4(-96.076, 79.705, -96.71, 80.158), + SIMD4(-96.71, 80.158, -94.735, 81.206), + SIMD4(-94.735, 81.206, -92.41, 81.257), + SIMD4(-92.41, 81.257, -87.02, 79.66), + SIMD4(-68.5, 83.106, -61.85, 82.629), + SIMD4(-61.85, 82.629, -71.18, 79.8), + SIMD4(-71.18, 79.8, -76.908, 79.323), + SIMD4(-76.908, 79.323, -75.393, 78.526), + SIMD4(-75.393, 78.526, -80.561, 76.178), + SIMD4(-80.561, 76.178, -89.491, 76.472), + SIMD4(-89.491, 76.472, -87.767, 77.178), + SIMD4(-87.767, 77.178, -88.26, 77.9), + SIMD4(-88.26, 77.9, -84.976, 77.539), + SIMD4(-84.976, 77.539, -87.962, 78.372), + SIMD4(-87.962, 78.372, -85.095, 79.345), + SIMD4(-85.095, 79.345, -86.932, 80.251), + SIMD4(-86.932, 80.251, -81.848, 80.464), + SIMD4(-81.848, 80.464, -87.599, 80.516), + SIMD4(-87.599, 80.516, -91.587, 81.894), + SIMD4(-91.587, 81.894, -68.5, 83.106), + SIMD4(-27.1, 83.52, -20.845, 82.727), + SIMD4(-20.845, 82.727, -31.9, 82.2), + SIMD4(-31.9, 82.2, -12.209, 81.292), + SIMD4(-12.209, 81.292, -20.046, 80.177), + SIMD4(-20.046, 80.177, -17.73, 80.129), + SIMD4(-17.73, 80.129, -19.705, 78.751), + SIMD4(-19.705, 78.751, -18.473, 76.986), + SIMD4(-18.473, 76.986, -21.679, 76.628), + SIMD4(-21.679, 76.628, -19.834, 76.098), + SIMD4(-19.834, 76.098, -20.668, 75.156), + SIMD4(-20.668, 75.156, -19.373, 74.296), + SIMD4(-19.373, 74.296, -23.566, 73.307), + SIMD4(-23.566, 73.307, -22.3, 72.184), + SIMD4(-22.3, 72.184, -24.793, 72.33), + SIMD4(-24.793, 72.33, -21.754, 70.664), + SIMD4(-21.754, 70.664, -25.543, 71.431), + SIMD4(-25.543, 71.431, -26.363, 70.226), + SIMD4(-26.363, 70.226, -22.349, 70.129), + SIMD4(-22.349, 70.129, -39.812, 65.458), + SIMD4(-39.812, 65.458, -42.819, 62.682), + SIMD4(-42.819, 62.682, -43.378, 60.098), + SIMD4(-43.378, 60.098, -46.264, 60.853), + SIMD4(-46.264, 60.853, -49.233, 61.407), + SIMD4(-49.233, 61.407, -53.662, 66.1), + SIMD4(-53.662, 66.1, -53.969, 67.189), + SIMD4(-53.969, 67.189, -50.871, 69.929), + SIMD4(-50.871, 69.929, -54.683, 69.61), + SIMD4(-54.683, 69.61, -54.359, 70.821), + SIMD4(-54.359, 70.821, -51.39, 70.57), + SIMD4(-51.39, 70.57, -55.835, 71.654), + SIMD4(-55.835, 71.654, -54.718, 72.586), + SIMD4(-54.718, 72.586, -57.324, 74.71), + SIMD4(-57.324, 74.71, -61.269, 76.102), + SIMD4(-61.269, 76.102, -68.504, 76.061), + SIMD4(-68.504, 76.061, -71.403, 77.009), + SIMD4(-71.403, 77.009, -66.764, 77.376), + SIMD4(-66.764, 77.376, -73.159, 78.433), + SIMD4(-73.159, 78.433, -65.711, 79.394), + SIMD4(-65.711, 79.394, -68.023, 80.117), + SIMD4(-68.023, 80.117, -60.282, 82.034), + SIMD4(-60.282, 82.034, -44.523, 81.661), + SIMD4(-44.523, 81.661, -46.764, 82.628), + SIMD4(-46.764, 82.628, -27.1, 83.52), + ] +} diff --git a/Sources/Retrolemetry/HardwareMetrics.swift b/Sources/Retrolemetry/HardwareMetrics.swift new file mode 100644 index 0000000..6781141 --- /dev/null +++ b/Sources/Retrolemetry/HardwareMetrics.swift @@ -0,0 +1,137 @@ +import Foundation +import CoreGraphics +import IOKit +import IOKit.ps + +struct PowerReading { + var voltage: Double? + var current: Double? + var onACPower = false + var isCharging = false + + /// Battery flow is not CPU/package power or total computer power consumption. + var watts: Double? { + guard let voltage, let current else { return nil } + return abs(voltage * current) + } + + var status: String { + guard voltage != nil || current != nil else { return "SENSOR UNAVAILABLE" } + if isCharging { return "BATTERY CHARGING" } + return onACPower ? "AC / BATTERY FLOW" : "BATTERY DISCHARGE" + } +} + +/// Read only exported properties with public IOKit functions. Driver counters are +/// optional and may disappear on other hardware/OS versions; never substitute CPU load. +final class HardwareMetricsReader { + private var accelerators: [io_service_t] = [] + private var battery: io_service_t = 0 + private var lastDiscovery = Date.distantPast + + init() { discoverServices() } + + deinit { + for service in accelerators { IOObjectRelease(service) } + if battery != 0 { IOObjectRelease(battery) } + } + + func gpuUsage() -> Double? { + if Date().timeIntervalSince(lastDiscovery) >= 30 { discoverServices() } + // On multi-GPU Macs report the busiest exposed device, not a sum of percentages. + return accelerators.compactMap { service in + guard let stats = property(service, "PerformanceStatistics") as? [String: Any] else { return nil } + return Self.gpuUsage(statistics: stats) + }.max() + } + + static func gpuUsage(statistics: [String: Any]) -> Double? { + guard let value = statistics["Device Utilization %"] as? NSNumber else { return nil } + let percent = value.doubleValue + guard percent.isFinite, (0...100).contains(percent) else { return nil } + return percent / 100 + } + + func powerReading() -> PowerReading { + var reading = PowerReading() + if let blob = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), + let sources = IOPSCopyPowerSourcesList(blob)?.takeRetainedValue() as? [CFTypeRef] { + for source in sources { + guard let info = IOPSGetPowerSourceDescription(blob, source)?.takeUnretainedValue() as? [String: Any], + info[kIOPSTypeKey] as? String == kIOPSInternalBatteryType else { continue } + reading.voltage = Self.volts(info[kIOPSVoltageKey] as? NSNumber) + reading.current = Self.amps(info[kIOPSCurrentKey] as? NSNumber) + reading.onACPower = info[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue + reading.isCharging = (info[kIOPSIsChargingKey] as? NSNumber)?.boolValue ?? false + break + } + } + // macOS sometimes omits voltage and rounds battery current in IOPowerSources. + // The exported battery properties give mV/mA without opening a private sensor connection. + if battery != 0 { + if reading.voltage == nil { + reading.voltage = Self.volts(property(battery, "Voltage") as? NSNumber) + } + let current = property(battery, "InstantAmperage") as? NSNumber + ?? property(battery, "Amperage") as? NSNumber + if let amps = Self.amps(current) { reading.current = amps } + if let external = property(battery, "ExternalConnected") as? NSNumber { reading.onACPower = external.boolValue } + if let charging = property(battery, "IsCharging") as? NSNumber { reading.isCharging = charging.boolValue } + } + return reading + } + + static func volts(_ millivolts: NSNumber?) -> Double? { + guard let millivolts else { return nil } + let value = millivolts.doubleValue / 1000 + return value.isFinite && value > 0 && value <= 100 ? value : nil + } + + static func amps(_ milliamps: NSNumber?) -> Double? { + guard let milliamps else { return nil } + // Some drivers encode negative discharge current as an unsigned two's-complement value. + let value = Double(milliamps.int64Value) / 1000 + return abs(value) <= 100 ? value : nil + } + + private func property(_ service: io_service_t, _ key: String) -> CFTypeRef? { + IORegistryEntryCreateCFProperty(service, key as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() + } + + private func discoverServices() { + lastDiscovery = Date() + for service in accelerators { IOObjectRelease(service) } + accelerators = [] + var iterator: io_iterator_t = 0 + if IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator) == KERN_SUCCESS { + defer { IOObjectRelease(iterator) } + var service = IOIteratorNext(iterator) + while service != 0 { + accelerators.append(service) + service = IOIteratorNext(iterator) + } + } + if battery != 0 { IOObjectRelease(battery) } + battery = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery")) + } +} + +/// Missing samples produce gaps, not a fabricated zero or a line joining across an outage. +enum UsageHistoryGeometry { + static func segments(_ values: [Double?], in rect: CGRect) -> [[CGPoint]] { + guard !values.isEmpty else { return [] } + var segments: [[CGPoint]] = [] + var current: [CGPoint] = [] + for (index, value) in values.enumerated() { + guard let value, value.isFinite, (0...1).contains(value) else { + if !current.isEmpty { segments.append(current); current = [] } + continue + } + let x = rect.minX + rect.width * CGFloat(index) / CGFloat(max(1, values.count - 1)) + let y = rect.maxY - rect.height * CGFloat(value) + current.append(CGPoint(x: x, y: y)) + } + if !current.isEmpty { segments.append(current) } + return segments + } +} diff --git a/Sources/Retrolemetry/LayoutEditor.swift b/Sources/Retrolemetry/LayoutEditor.swift new file mode 100644 index 0000000..b4f8c22 --- /dev/null +++ b/Sources/Retrolemetry/LayoutEditor.swift @@ -0,0 +1,779 @@ +import SwiftUI + +struct ModuleFrame: Codable, Equatable { + var x: Double + var y: Double + var width: Double + var height: Double + var visible: Bool = true + + var rect: CGRect { + CGRect(x: x, y: y, width: width, height: height) + } +} + +struct SceneModule: Identifiable, Hashable { + let id: String + let name: String +} + +enum LayoutDefaults { + static func modules(for scene: ConsoleScene) -> [SceneModule] { + switch scene { + case .system: + [ + module("marketFocus", "Market focus chart"), module("globe", "Rotating globe"), + module("marketClocks", "World clocks"), module("marketTickerA", "Ticker board A"), + module("marketTickerB", "Ticker board B"), module("fxGraph", "USD to ILS graph") + ] + case .radar: + [module("radar", "Radar"), module("weatherHeader", "Weather header"), module("weatherStats", "Weather conditions"), module("temperature", "Hourly forecast"), module("precipitation", "Daily forecast"), module("weatherStatus", "Weather status")] + case .signal: + [module("scope", "Signal scope"), module("signalHeader", "Channel header"), module("cpuTrace", "CPU trace"), module("memoryTrace", "Memory trace"), module("networkTrace", "Network trace"), module("ioReadout", "Network I/O")] + case .fullMetrics: + [module("metricCPU", "CPU tile"), module("metricGPU", "GPU tile"), module("metricMemory", "Memory tile"), module("metricDisk", "Disk tile"), module("metricNetwork", "Network tile"), module("metricPower", "Power / voltage tile"), module("graphCPU", "CPU graph"), module("graphGPU", "GPU graph"), module("graphMemory", "Memory graph"), module("graphNetwork", "Network TX / RX graph"), module("statusUptime", "Uptime"), module("statusLoad", "Load averages"), module("statusTX", "Network RX")] + } + } + + static func frames(for scene: ConsoleScene) -> [String: ModuleFrame] { + switch scene { + case .system: + return [ + "marketFocus": frame(30, 60, 360, 260), + "globe": frame(410, 60, 240, 260), + "marketClocks": frame(670, 60, 260, 120), + "fxGraph": frame(670, 200, 260, 120), + "marketTickerA": frame(30, 340, 430, 150), + "marketTickerB": frame(480, 340, 450, 150) + ] + case .radar: + return [ + "radar": frame(25, 55, 438.8523, 429.6496), "weatherHeader": frame(480, 58, 455, 60), + "weatherStats": frame(480, 130, 455, 62), "temperature": frame(480, 204, 455, 92), + "precipitation": frame(480, 307, 455, 138), + "weatherStatus": frame(480, 457, 455, 30) + ] + case .signal: + return [ + "scope": frame(50, 78, 860, 320), "signalHeader": frame(62, 90, 836, 25), + "cpuTrace": frame(62, 418, 200, 78), "memoryTrace": frame(274, 418, 200, 78), + "networkTrace": frame(486, 418, 200, 78), "ioReadout": frame(698, 418, 217.7964, 77.9483) + ] + case .fullMetrics: + let tileW = (904.0 - 5 * 12) / 6 + let tileStep = tileW + 12 + return [ + "metricCPU": frame(28, 55, tileW, 132), "metricGPU": frame(28 + tileStep, 55, tileW, 132), + "metricMemory": frame(28 + tileStep * 2, 55, tileW, 132), "metricDisk": frame(28 + tileStep * 3, 55, tileW, 132), + "metricNetwork": frame(28 + tileStep * 4, 55, tileW, 132), "metricPower": frame(28 + tileStep * 5, 55, tileW, 132), + "graphCPU": frame(28, 199, 217, 184), "graphGPU": frame(257, 199, 217, 184), + "graphMemory": frame(486, 199, 217, 184), "graphNetwork": frame(715, 199, 217, 184), + "statusUptime": frame(28, 395, 290.7309, 108.1884), + "statusLoad": frame(333, 394.7723, 292.7358, 107.8150), + "statusTX": frame(638, 395, 287.8994, 107.7403) + ] + } + } + + /// Preserve hand-arranged layouts. Newly added modules start hidden there so they + /// cannot cover existing modules; untouched old defaults can adopt the expanded layout. + static func merging(_ saved: [String: ModuleFrame], for scene: ConsoleScene) -> [String: ModuleFrame] { + var defaults = frames(for: scene) + if scene == .fullMetrics, saved["metricGPU"] == nil { + let legacy = legacyMetricsFrames + if saved.allSatisfy({ legacy[$0.key] == $0.value }) { return defaults } + for id in ["metricGPU", "metricPower", "graphGPU"] { defaults[id]?.visible = false } + } + return defaults.merging(saved) { _, saved in saved } + } + + private static var legacyMetricsFrames: [String: ModuleFrame] { + [ + "metricCPU": frame(28, 55, 217, 116), "metricMemory": frame(257, 55, 217, 116), + "metricDisk": frame(486, 55, 217, 116), "metricNetwork": frame(715, 55, 217, 116), + "graphCPU": frame(28, 183, 293, 200), "graphMemory": frame(333, 183, 293, 200), + "graphNetwork": frame(638, 183, 294, 200), + "statusUptime": frame(28, 395, 290.7309, 108.1884), + "statusLoad": frame(333, 394.7723, 292.7358, 107.8150), + "statusTX": frame(638, 395, 287.8994, 107.7403) + ] + } + + private static func module(_ id: String, _ name: String) -> SceneModule { SceneModule(id: id, name: name) } + private static func frame(_ x: Double, _ y: Double, _ width: Double, _ height: Double) -> ModuleFrame { + ModuleFrame(x: x, y: y, width: width, height: height) + } +} + +@MainActor +final class LayoutStore: ObservableObject { + static let shared = LayoutStore() + @Published private(set) var layouts: [String: [String: ModuleFrame]] = [:] + @Published private var interactionPreview: InteractionPreview? + @Published var fontScale: Double { + didSet { defaults.set(fontScale, forKey: "DockTelemetry.fontScale") } + } + @Published var secondaryFontScale: Double { + didSet { defaults.set(secondaryFontScale, forKey: "DockTelemetry.secondaryFontScale") } + } + @Published var auxiliaryFontScale: Double { + didSet { defaults.set(auxiliaryFontScale, forKey: "DockTelemetry.auxiliaryFontScale") } + } + @Published var globalTypographyEnabled: Bool { + didSet { defaults.set(globalTypographyEnabled, forKey: "DockTelemetry.typography.global") } + } + @Published private var sceneTypography: [String: ConsoleTypography] = [:] + @Published private var globalTypographyGroups: [String: Double] = [:] + private let defaults: UserDefaults + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + fontScale = defaults.object(forKey: "DockTelemetry.fontScale") as? Double ?? 1.45 + secondaryFontScale = defaults.object(forKey: "DockTelemetry.secondaryFontScale") as? Double ?? 1 + auxiliaryFontScale = defaults.object(forKey: "DockTelemetry.auxiliaryFontScale") as? Double ?? 1 + globalTypographyEnabled = defaults.object(forKey: "DockTelemetry.typography.global") as? Bool ?? true + if let data = defaults.data(forKey: "DockTelemetry.typography.groups.v2"), + let saved = try? JSONDecoder().decode([String: Double].self, from: data) { + globalTypographyGroups = saved.filter { $0.value.isFinite && (0.65...3).contains($0.value) } + } + for scene in ConsoleScene.allCases { + if let data = defaults.data(forKey: "DockTelemetry.typography.v1.\(scene.rawValue)"), + let saved = try? JSONDecoder().decode(ConsoleTypography.self, from: data) { + sceneTypography[sceneKey(scene)] = saved + } + } + for scene in ConsoleScene.allCases { layouts[sceneKey(scene)] = load(scene) } + } + + func typography(for scene: ConsoleScene) -> ConsoleTypography { + let global = ConsoleTypography(primary: fontScale, secondary: secondaryFontScale, other: auxiliaryFontScale, groups: globalTypographyGroups) + return globalTypographyEnabled ? global : (sceneTypography[sceneKey(scene)] ?? global) + } + + func setFontScale(_ value: Double, role: ConsoleFontRole, scene: ConsoleScene) { + let value = min(3, max(role == .primary ? 0.75 : 0.65, value)) + if globalTypographyEnabled { + globalTypographyGroups[role.rawValue] = value + if let data = try? JSONEncoder().encode(globalTypographyGroups) { + defaults.set(data, forKey: "DockTelemetry.typography.groups.v2") + } + } else { + var typography = typography(for: scene) + typography[role] = value + sceneTypography[sceneKey(scene)] = typography + if let data = try? JSONEncoder().encode(typography) { + defaults.set(data, forKey: "DockTelemetry.typography.v1.\(scene.rawValue)") + } + } + } + + func frame(_ scene: ConsoleScene, _ module: String) -> ModuleFrame { + if interactionPreview?.scene == scene, interactionPreview?.module == module, + let previewFrame = interactionPreview?.frame { + return previewFrame + } + return layouts[sceneKey(scene)]?[module] ?? LayoutDefaults.frames(for: scene)[module] ?? ModuleFrame(x: 40, y: 80, width: 200, height: 100) + } + + func update(_ scene: ConsoleScene, module: String, frame: ModuleFrame) { + var sceneLayout = layouts[sceneKey(scene)] ?? LayoutDefaults.frames(for: scene) + sceneLayout[module] = constrained(frame) + layouts[sceneKey(scene)] = sceneLayout + save(scene, sceneLayout) + } + + /// Preview drag and resize changes in memory, then save once at mouse-up. + func previewInteraction(_ scene: ConsoleScene, module: String, frame: ModuleFrame) { + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { + interactionPreview = InteractionPreview(scene: scene, module: module, frame: constrained(frame)) + } + } + + func commitInteraction() { + guard let preview = interactionPreview else { return } + var sceneLayout = layouts[sceneKey(preview.scene)] ?? LayoutDefaults.frames(for: preview.scene) + sceneLayout[preview.module] = preview.frame + layouts[sceneKey(preview.scene)] = sceneLayout + interactionPreview = nil + save(preview.scene, sceneLayout) + } + + func cancelInteraction() { + interactionPreview = nil + } + + func setVisible(_ visible: Bool, scene: ConsoleScene, module: String) { + var value = frame(scene, module) + value.visible = visible + update(scene, module: module, frame: value) + } + + func reset(_ scene: ConsoleScene) { + let defaults = LayoutDefaults.frames(for: scene) + layouts[sceneKey(scene)] = defaults + save(scene, defaults) + } + + private func constrained(_ value: ModuleFrame) -> ModuleFrame { + var result = value + result.width = min(930, max(70, result.width)) + result.height = min(470, max(38, result.height)) + result.x = min(945 - result.width, max(15, result.x)) + result.y = min(505 - result.height, max(45, result.y)) + return result + } + + private func sceneKey(_ scene: ConsoleScene) -> String { String(scene.rawValue) } + private func storageKey(_ scene: ConsoleScene) -> String { + scene == .system + ? "DockTelemetry.layout.v5.\(scene.rawValue)" + : "DockTelemetry.layout.v3.\(scene.rawValue)" + } + + private func load(_ scene: ConsoleScene) -> [String: ModuleFrame] { + guard let data = defaults.data(forKey: storageKey(scene)), + let saved = try? JSONDecoder().decode([String: ModuleFrame].self, from: data) else { + return LayoutDefaults.frames(for: scene) + } + return LayoutDefaults.merging(saved, for: scene) + } + + private func save(_ scene: ConsoleScene, _ layout: [String: ModuleFrame]) { + guard let data = try? JSONEncoder().encode(layout) else { return } + defaults.set(data, forKey: storageKey(scene)) + } + + private struct InteractionPreview { + let scene: ConsoleScene + let module: String + let frame: ModuleFrame + } +} + +struct LayoutModuleContainer: View { + @ObservedObject private var layouts = LayoutStore.shared + let scene: ConsoleScene + let module: String + @ViewBuilder let content: () -> Content + + var body: some View { + let value = layouts.frame(scene, module) + if value.visible { + content() + .frame(width: value.width, height: value.height) + .clipped() + .position(x: value.x + value.width / 2, y: value.y + value.height / 2) + } + } +} + +struct LayoutEditorView: View { + @ObservedObject private var layouts = LayoutStore.shared + @StateObject private var marketPreview = MarketModel(preview: true) + @ObservedObject private var weatherLocation = WeatherLocation.shared + @AppStorage("DockTelemetry.visualStyle") private var visualStyleRaw = ConsoleStyle.phosphor.rawValue + @AppStorage("DockTelemetry.crtEnabled") private var crtEnabled = true + @AppStorage("DockTelemetry.crtTubeEnabled") private var crtTubeEnabled = false + @AppStorage("DockTelemetry.crtTubeStrength") private var crtTubeStrength = 0.35 + @AppStorage("DockTelemetry.phosphorBackgroundTint") private var phosphorTint = 0.12 + @AppStorage("DockTelemetry.bloomStrength") private var bloom = 0.72 + @AppStorage("DockTelemetry.scanlineStrength") private var scanlines = 0.22 + @AppStorage("DockTelemetry.noiseStrength") private var noise = 0.32 + @AppStorage("DockTelemetry.vhsTrackingEnabled") private var tracking = true + @AppStorage("DockTelemetry.trackingLine1Thickness") private var firstLine = 1.5 + @AppStorage("DockTelemetry.trackingLine2Thickness") private var secondLine = 8.0 + @State private var previewEffects = true + @AppStorage("DockTelemetry.radarWidthCorrection") private var radarWidthCorrection = 1.10 + @AppStorage("DockTelemetry.radarHeightCorrection") private var radarHeightCorrection = 0.9254 + @AppStorage("DockTelemetry.radarTargetMode") private var radarTargetModeRaw = RadarTargetMode.precipitation.rawValue + @AppStorage("DockTelemetry.radarTargetPulse") private var radarTargetPulse = true + @AppStorage(WeatherRegionSelection.preferenceKey) private var regionSelectionRaw = WeatherRegionSelection.automatic.rawValue + @AppStorage("DockTelemetry.globeWidthCorrection") private var globeWidthCorrection = 1.10 + @AppStorage("DockTelemetry.globeHeightCorrection") private var globeHeightCorrection = 0.9254 + @AppStorage("DockTelemetry.signalSynthwaveGrid") private var signalSynthwaveGrid = false + @AppStorage("DockTelemetry.signalDisplayMode") private var signalDisplayModeRaw = SignalDisplayMode.spinning.rawValue + @AppStorage("DockTelemetry.signalGridAnimationEnabled") private var signalGridAnimationEnabled = true + @AppStorage("DockTelemetry.signalGridMetric") private var signalGridMetricRaw = SignalGridMetric.cpu.rawValue + @AppStorage("DockTelemetry.signalGridPattern") private var signalGridPatternRaw = SignalGridPattern.recede.rawValue + @AppStorage("DockTelemetry.signalGridResponse") private var signalGridResponseRaw = SignalGridResponse.medium.rawValue + @AppStorage("DockTelemetry.layoutSnapEnabled") private var snapEnabled = false + @AppStorage("DockTelemetry.layoutSnapStep") private var snapStep = 10.0 + @State private var scene: ConsoleScene = .system + @State private var selection = "marketFocus" + @State private var interactionModule: String? + @State private var interactionStart: ModuleFrame? + @State private var interactionKind: InteractionKind? + private let scale = 0.68 + + private enum InteractionKind: Equatable { case move, resize } + + init(initialScene: ConsoleScene = .system) { + _scene = State(initialValue: initialScene) + _selection = State(initialValue: LayoutDefaults.modules(for: initialScene).first?.id ?? "") + } + + var body: some View { + return VStack(spacing: 14) { + HStack { + Picker("View", selection: $scene) { + ForEach(ConsoleScene.allCases, id: \.self) { Text($0.tabTitle).tag($0) } + } + .pickerStyle(.segmented).labelsHidden() + .frame(width: 440) + .onChange(of: scene) { + layouts.cancelInteraction() + clearInteraction() + selection = LayoutDefaults.modules(for: scene).first?.id ?? "" + } + Spacer() + Toggle("Preview CRT effects", isOn: $previewEffects) + Button("Reset this view") { layouts.reset(scene) } + } + + HStack(alignment: .top, spacing: 14) { + editorCanvas + editorInspector + } + editorBottomTray + } + .padding(18) + } + + private var editorInspector: some View { + VStack(alignment: .leading, spacing: 12) { + GroupBox("Layout") { + VStack(alignment: .leading, spacing: 8) { + Toggle("Snap while dragging", isOn: $snapEnabled) + Picker("Grid", selection: $snapStep) { + Text("5 px").tag(5.0) + Text("10 px").tag(10.0) + Text("20 px").tag(20.0) + } + .disabled(!snapEnabled) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + if scene == .signal { + GroupBox("Signal Analysis") { + VStack(alignment: .leading, spacing: 6) { + Picker("Display", selection: $signalDisplayModeRaw) { + ForEach(SignalDisplayMode.allCases) { mode in + Text(mode.title).tag(mode.rawValue) + } + } + Toggle("Synthwave perspective grid", isOn: $signalSynthwaveGrid) + Group { + Toggle("Animate grid", isOn: $signalGridAnimationEnabled) + Picker("Pattern", selection: $signalGridPatternRaw) { + ForEach(SignalGridPattern.allCases) { pattern in + Text(pattern.title).tag(pattern.rawValue) + } + } + Picker("Respond to", selection: $signalGridMetricRaw) { + ForEach(SignalGridMetric.allCases) { metric in + Text(metric.title).tag(metric.rawValue) + } + } + Picker("Frequency response", selection: $signalGridResponseRaw) { + ForEach(SignalGridResponse.allCases) { response in + Text(response.title).tag(response.rawValue) + } + } + Text("GPU uses optional driver utilization counters. Unsupported Macs show N/A, not system load.") + .font(.caption2) + .foregroundStyle(.secondary) + } + .disabled(!signalSynthwaveGrid) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } else if scene == .radar { + GroupBox("Radar") { + VStack(spacing: 9) { + WeatherRegionPicker() + editorSlider("Width", value: $radarWidthCorrection, range: 0.70...1.35) + editorSlider("Height", value: $radarHeightCorrection, range: 0.70...1.35) + Picker("Targets", selection: $radarTargetModeRaw) { + ForEach(RadarTargetMode.allCases) { mode in + Text(mode.title).tag(mode.rawValue) + } + } + Toggle("Pulse targets", isOn: $radarTargetPulse) + Text("Automatic uses your weather location; manual selection needs no location permission. Six regional forecast points refresh every 15 minutes—not live radar echoes. Click the radar to cycle targets.") + .font(.caption2).foregroundStyle(.secondary) + } + } + } else if scene == .system { + GroupBox("Globe shape") { + VStack(spacing: 9) { + editorSlider("Width", value: $globeWidthCorrection, range: 0.70...1.35) + editorSlider("Height", value: $globeHeightCorrection, range: 0.70...1.35) + } + } + } else if scene == .fullMetrics { + GroupBox("GPU and power") { + VStack(alignment: .leading, spacing: 9) { + Text("GPU reports the busiest available device. Power and voltage describe battery flow, not total Mac power.") + Text("New modules start hidden in custom layouts to avoid overlaps. Enable them below, or reset this view for the expanded six-tile layout.") + } + .font(.caption).foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + Spacer(minLength: 0) + } + .frame(width: 290, height: 540 * scale) + } + + private var editorBottomTray: some View { + HStack(alignment: .top, spacing: 12) { + GroupBox("Typography") { + VStack(spacing: 9) { + Toggle("Apply to all views", isOn: $layouts.globalTypographyEnabled) + ForEach(ConsoleFontRole.allCases, id: \.self) { role in + editorSlider(role.title, value: fontBinding(role), range: (role == .primary ? 0.75 : 0.65)...3.0) + } + Text("Dark texts: all dim text, wherever it appears. Main text: bright labels and names.") + .font(.caption2).foregroundStyle(.secondary) + } + } + .frame(width: 310) + + GroupBox("Modules") { + LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], alignment: .leading, spacing: 7) { + ForEach(LayoutDefaults.modules(for: scene)) { module in + let value = layouts.frame(scene, module.id) + HStack(spacing: 5) { + Toggle("", isOn: Binding( + get: { value.visible }, + set: { + layouts.setVisible($0, scene: scene, module: module.id) + if !$0 && selection == module.id { + selection = "" + layouts.cancelInteraction() + clearInteraction() + } + } + )).labelsHidden() + Button(module.name) { selection = module.id } + .buttonStyle(.plain) + .lineLimit(1) + .foregroundStyle(selection == module.id ? Color.accentColor : Color.primary) + Spacer(minLength: 0) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .frame(width: 360) + + GroupBox("Selected module") { + if let module = LayoutDefaults.modules(for: scene).first(where: { $0.id == selection }) { + moduleControls(module) + } else { + Text("Click a module to select it. Click empty canvas space to clear the selection.") + .font(.caption) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .frame(maxWidth: .infinity) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + private func editorSlider( + _ title: String, + value: Binding, + range: ClosedRange + ) -> some View { + HStack(spacing: 8) { + Text(title).frame(width: 122, alignment: .leading) + Slider(value: value, in: range) + Text("\(Int(value.wrappedValue * 100))%") + .monospacedDigit() + .frame(width: 42, alignment: .trailing) + } + } + + private func fontBinding(_ role: ConsoleFontRole) -> Binding { + Binding(get: { layouts.typography(for: scene)[role] }, + set: { layouts.setFontScale($0, role: role, scene: scene) }) + } + + private var editorCanvas: some View { + ZStack(alignment: .topLeading) { + Color.black + staticScene + ZStack { + ForEach(LayoutDefaults.modules(for: scene).filter { layouts.frame(scene, $0.id).visible }) { module in + moduleBox(module) + } + } + .frame(width: 960 * scale, height: 540 * scale) + .modifier(CRTTubeEffect(enabled: previewEffects && crtTubeEnabled, strength: crtTubeStrength, + size: CGSize(width: 960 * scale, height: 540 * scale), opaqueBackground: false)) + } + .foregroundStyle(Color(red: 0.34, green: 1, blue: 0.43)) + .font(.system(size: 8, weight: .bold, design: .monospaced)) + .frame(width: 960 * scale, height: 540 * scale) + .contentShape(Rectangle()) + .gesture(editorGesture) + .transaction { transaction in transaction.animation = nil } + .clipped() + .overlay(Rectangle().stroke(Color.green.opacity(0.7), lineWidth: 1)) + } + + private var staticScene: some View { + let style = ConsoleStyle(rawValue: visualStyleRaw) ?? .phosphor + ThemeRuntime.palette = style.palette + let telemetry = TelemetrySnapshot( + cpu: 0.38, memory: 0.61, disk: 0.62, + networkIn: 240_000, networkOut: 82_000, + uptime: 213_420, load: (2.4, 3.1, 3.8), gpu: 0.68, + power: PowerReading(voltage: 12.16, current: -0.85), + memoryCapacity: CapacityReading(totalBytes: 32_000_000_000, usedBytes: 19_520_000_000), + diskCapacity: CapacityReading(totalBytes: 1_000_000_000_000, usedBytes: 620_000_000_000) + ) + let cpu = (0..<96).map { 0.24 + sin(Double($0) * 0.22) * 0.11 } + let memory = (0..<96).map { 0.57 + sin(Double($0) * 0.06) * 0.025 } + let network = (0..<96).map { max(0.02, sin(Double($0) * 0.31) * 0.18 + 0.12) } + let gpu: [Double?] = (0..<96).map { 0.48 + sin(Double($0) * 0.17) * 0.28 } + let previewHour = Date() + let hourly = previewHourlyForecast(from: previewHour) + let daily = previewDailyForecast(from: previewHour) + let selection = WeatherRegionSelection(rawValue: regionSelectionRaw) ?? .automatic + let region = selection.resolve(coordinate: weatherLocation.coordinate ?? GlobeCoordinate(latitude: 32, longitude: 35)) + let weather = WeatherSnapshot( + location: "LOCAL PREVIEW", condition: "PARTLY CLOUDY", + temperature: 24, apparentTemperature: 25, humidity: 0.58, + windSpeed: 12, precipitation: 0, + temperatureForecast: [0.72, 0.68, 0.61, 0.55, 0.50, 0.45, 0.42, 0.40, 0.36, 0.34, 0.31, 0.29], + precipitationForecast: [0.08, 0.05, 0.04, 0.03, 0.04, 0.08, 0.12, 0.09, 0.06, 0.04, 0.03, 0.02], + hourlyForecast: hourly, + dailyForecast: daily, + updatedAt: Date(), status: "STATIC LAYOUT PREVIEW", + radarWeather: region.map { RadarWeatherPoint.preview(region: $0) } ?? [], radarUpdatedAt: Date(), radarStatus: "STATIC FORECAST PREVIEW", radarRegion: region + ) + return ZStack { + ConsoleBackground(style: style, phosphorTintStrength: phosphorTint) + .modifier(CRTTubeEffect(enabled: previewEffects && crtTubeEnabled, strength: crtTubeStrength)) + Group { + switch scene { + case .system: + SystemScene(market: marketPreview, time: 10, location: weatherLocation.coordinate) + case .radar: + RadarScene(weather: weather, time: 10) + case .signal: + SignalScene(snapshot: telemetry, cpuHistory: cpu, memoryHistory: memory, networkHistory: network, gpuHistory: gpu, time: 10) + case .fullMetrics: + FullMetricsScene(snapshot: telemetry, cpuHistory: cpu, memoryHistory: memory, + networkReceiveHistory: network.map { $0 * 1_000_000 }, + networkTransmitHistory: network.reversed().map { $0 * 400_000 }, gpuHistory: gpu, time: 10) + } + } + .consoleFont(14, role: .secondary, weight: .medium, fallback: .other) + .compositingGroup() + .shadow(color: previewEffects && crtEnabled ? style.palette.primary.opacity(0.24*bloom) : .clear, radius: 2.5+3.5*bloom) + .modifier(CRTTubeEffect(enabled: previewEffects && crtTubeEnabled, strength: crtTubeStrength, opaqueBackground: false)) + if previewEffects && crtEnabled { + CRTOverlay(scanlineStrength: scanlines, noiseStrength: noise, vhsTrackingEnabled: tracking, + trackingLine1Thickness: firstLine, trackingLine2Thickness: secondLine, time: 10, + tubeStrength: crtTubeEnabled ? crtTubeStrength : 0) + } + } + .frame(width: 960, height: 540) + .foregroundStyle(style.palette.primary) + .environment(\.consoleTypography, layouts.typography(for: scene)) + .environment(\.consoleAnimationEnabled, false) + .scaleEffect(scale, anchor: .topLeading) + .frame(width: 960 * scale, height: 540 * scale, alignment: .topLeading) + .allowsHitTesting(false) + } + + private func moduleBox(_ module: SceneModule) -> some View { + let value = layouts.frame(scene, module.id) + let selected = selection == module.id + return ZStack(alignment: .bottomTrailing) { + RoundedRectangle(cornerRadius: 3) + .fill(value.visible ? Color.white.opacity(0.001) : Color.gray.opacity(0.12)) + RoundedRectangle(cornerRadius: 3) + .stroke( + selected ? Color.yellow : (value.visible ? Color.green.opacity(0.38) : Color.gray), + style: StrokeStyle(lineWidth: selected ? 2 : 1, dash: value.visible ? [] : [5, 4]) + ) + if selected { + ZStack { + Rectangle().fill(Color.black.opacity(0.8)) + Rectangle().stroke(Color.yellow, lineWidth: 2) + Path { path in + path.move(to: CGPoint(x: 4, y: 12)) + path.addLine(to: CGPoint(x: 12, y: 4)) + path.move(to: CGPoint(x: 8, y: 12)) + path.addLine(to: CGPoint(x: 12, y: 8)) + } + .stroke(Color.yellow, lineWidth: 1.5) + } + .frame(width: 16, height: 16) + } + } + .frame(width: value.width * scale, height: value.height * scale) + .position(x: (value.x + value.width / 2) * scale, y: (value.y + value.height / 2) * scale) + .zIndex(selected ? 20 : 0) + .opacity(value.visible ? 1 : 0.55) + .allowsHitTesting(false) + } + + private var editorGesture: some Gesture { + DragGesture(minimumDistance: 0, coordinateSpace: .local) + .onChanged { gesture in + if interactionModule == nil { + let point = editorPoint(gesture.startLocation) + let selectedFrame = layouts.frame(scene, selection) + let handle = CGRect( + x: selectedFrame.x + selectedFrame.width - 24 / scale, + y: selectedFrame.y + selectedFrame.height - 24 / scale, + width: 24 / scale, + height: 24 / scale + ) + let resizing = !selection.isEmpty && selectedFrame.visible && handle.contains(point) + let module = resizing ? selection : hitTest(point) + guard !module.isEmpty else { + selection = "" + layouts.cancelInteraction() + clearInteraction() + return + } + selection = module + interactionModule = module + interactionStart = layouts.frame(scene, module) + interactionKind = resizing ? .resize : .move + } + + guard let module = interactionModule, var updated = interactionStart else { return } + let start = editorPoint(gesture.startLocation) + let current = editorPoint(gesture.location) + let dx = current.x - start.x + let dy = current.y - start.y + if interactionKind == .resize { + updated.width += dx + updated.height += dy + } else { + updated.x += dx + updated.y += dy + } + if snapEnabled { updated = snapped(updated, kind: interactionKind) } + layouts.previewInteraction(scene, module: module, frame: updated) + } + .onEnded { _ in + layouts.commitInteraction() + clearInteraction() + } + } + + private func hitTest(_ point: CGPoint) -> String { + LayoutDefaults.modules(for: scene) + .filter { layouts.frame(scene, $0.id).visible && layouts.frame(scene, $0.id).rect.contains(point) } + .min { lhs, rhs in + let left = layouts.frame(scene, lhs.id) + let right = layouts.frame(scene, rhs.id) + return left.width * left.height < right.width * right.height + }?.id ?? "" + } + + private func editorPoint(_ point: CGPoint) -> CGPoint { + CRTTubeGeometry.sourcePoint(for: CGPoint(x: point.x / scale, y: point.y / scale), + size: CGSize(width: 960, height: 540), + strength: previewEffects && crtTubeEnabled && CRTTubeEffect.isAvailable ? crtTubeStrength : 0) + } + + private func clearInteraction() { + interactionModule = nil + interactionKind = nil + interactionStart = nil + } + + private func snapped(_ value: ModuleFrame, kind: InteractionKind?) -> ModuleFrame { + let step = max(1, snapStep) + var result = value + if kind == .resize { + result.width = (result.width / step).rounded() * step + result.height = (result.height / step).rounded() * step + } else { + result.x = (result.x / step).rounded() * step + result.y = (result.y / step).rounded() * step + } + return result + } + + private func previewHourlyForecast(from start: Date) -> [HourlyWeatherPoint] { + var result: [HourlyWeatherPoint] = [] + for index in 0..<12 { + let indexValue = Double(index) + let time = start.addingTimeInterval(indexValue * 3600) + let temperature = 24 - indexValue * 0.35 + sin(indexValue * 0.7) + let rainChance = max(0.02, sin(indexValue * 0.42) * 0.18 + 0.12) + let condition = index < 5 ? "PARTLY CLOUDY" : "CLEAR SKY" + result.append(HourlyWeatherPoint( + time: time, + temperature: temperature, + precipitationChance: rainChance, + condition: condition + )) + } + return result + } + + private func previewDailyForecast(from start: Date) -> [DailyWeatherPoint] { + var result: [DailyWeatherPoint] = [] + for index in 0..<7 { + let date = Calendar.current.date(byAdding: .day, value: index, to: start) ?? start + let low = 18 + Double(index % 2) + let high = 25 + Double(index % 3) + let rainChance = Double((index * 17) % 55) / 100 + let condition = index.isMultiple(of: 3) ? "RAIN SHOWERS" : "PARTLY CLOUDY" + result.append(DailyWeatherPoint( + date: date, + low: low, + high: high, + precipitationChance: rainChance, + condition: condition + )) + } + return result + } + + @ViewBuilder + private func moduleControls(_ module: SceneModule) -> some View { + let value = layouts.frame(scene, module.id) + VStack(alignment: .leading, spacing: 5) { + Text(module.name).font(.caption).bold() + HStack { + Stepper("X \(Int(value.x))", value: frameBinding(module.id, \.x), in: 15...875, step: 1) + Stepper("Y \(Int(value.y))", value: frameBinding(module.id, \.y), in: 45...467, step: 1) + } + HStack { + Stepper("W \(Int(value.width))", value: frameBinding(module.id, \.width), in: 70...930, step: 1) + Stepper("H \(Int(value.height))", value: frameBinding(module.id, \.height), in: 38...470, step: 1) + } + Text(snapEnabled ? "Dragging snaps to the \(Int(snapStep)) px grid." : "Drag changes save at mouse-up. Steppers save immediately.") + .font(.caption2).foregroundStyle(.secondary) + } + .padding(8) + .background(.quaternary, in: RoundedRectangle(cornerRadius: 6)) + } + + private func frameBinding(_ module: String, _ keyPath: WritableKeyPath) -> Binding { + Binding( + get: { layouts.frame(scene, module)[keyPath: keyPath] }, + set: { newValue in + var value = layouts.frame(scene, module) + value[keyPath: keyPath] = newValue + layouts.update(scene, module: module, frame: value) + } + ) + } +} diff --git a/Sources/Retrolemetry/MarketData.swift b/Sources/Retrolemetry/MarketData.swift new file mode 100644 index 0000000..519d1de --- /dev/null +++ b/Sources/Retrolemetry/MarketData.swift @@ -0,0 +1,558 @@ +import Foundation +import Security + +struct MarketQuote: Identifiable, Sendable { + let symbol: String + let price: Double + let change: Double + let percentChange: Double + let high: Double + let low: Double + let open: Double + let previousClose: Double + let tradeTime: Date + + var id: String { symbol } +} + +struct FXRatePoint: Identifiable, Sendable { + let date: Date + let rate: Double + var id: Date { date } +} + +enum MarketTimeframe: String, CaseIterable, Sendable { + case today + case week + case month + case year + + var label: String { + switch self { + case .today: "TODAY" + case .week: "1 WEEK" + case .month: "1 MONTH" + case .year: "1 YEAR" + } + } + + var next: MarketTimeframe { + let values = Self.allCases + let index = values.firstIndex(of: self) ?? 0 + return values[(index + 1) % values.count] + } + + var yahooRange: String { + switch self { + case .today: "1d" + case .week: "5d" + case .month: "1mo" + case .year: "1y" + } + } + + var yahooInterval: String { + switch self { + case .today: "5m" + case .week: "30m" + case .month: "1d" + case .year: "1wk" + } + } + + var refreshInterval: TimeInterval { + switch self { + case .today: 120 + case .week: 600 + case .month: 1_800 + case .year: 3_600 + } + } +} + +enum MarketFeedState: Equatable { + case needsAPIKey + case loading + case live(Date) + case stale(Date) + case failed(String) + + var label: String { + switch self { + case .needsAPIKey: "API KEY REQUIRED" + case .loading: "CONNECTING" + case .live: "LIVE" + case .stale: "STALE" + case .failed: "FEED ERROR" + } + } +} + +extension Notification.Name { + static let marketConfigurationDidChange = Notification.Name("Retrolemetry.marketConfigurationDidChange") +} + +enum MarketKeychain { + private static let service = "io.github.SamSpring.Retrolemetry.finnhub" + private static let account = "api-token" + + static func apiKey() -> String? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, + let data = result as? Data, + let value = String(data: data, encoding: .utf8), + !value.isEmpty else { return nil } + return value + } + + static func save(apiKey: String) throws { + let trimmed = apiKey.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + delete() + return + } + let data = Data(trimmed.utf8) + let lookup: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account + ] + let update = [kSecValueData as String: data] + let status = SecItemUpdate(lookup as CFDictionary, update as CFDictionary) + if status == errSecItemNotFound { + var item = lookup + item[kSecValueData as String] = data + let addStatus = SecItemAdd(item as CFDictionary, nil) + guard addStatus == errSecSuccess else { throw KeychainError.status(addStatus) } + } else if status != errSecSuccess { + throw KeychainError.status(status) + } + NotificationCenter.default.post(name: .marketConfigurationDidChange, object: nil) + } + + static func delete() { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account + ] + SecItemDelete(query as CFDictionary) + NotificationCenter.default.post(name: .marketConfigurationDidChange, object: nil) + } + + enum KeychainError: LocalizedError { + case status(OSStatus) + + var errorDescription: String? { + switch self { + case .status(let status): + SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)" + } + } + } +} + +enum MarketSymbols { + static let defaultValue = "OKLO, RGTI, NXE, QUBT, QBTS" + + static func parse(_ value: String) -> [String] { + var seen = Set() + return value + .components(separatedBy: CharacterSet(charactersIn: ",; \n\t")) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() } + .filter { !$0.isEmpty && seen.insert($0).inserted } + .prefix(12) + .map { $0 } + } +} + +struct MarketClockZone: Identifiable, Hashable { + let id: String + let title: String + let shortTitle: String + + static let options: [MarketClockZone] = [ + .init(id: "America/New_York", title: "Florida / New York", shortTitle: "FLORIDA"), + .init(id: "America/Los_Angeles", title: "Los Angeles", shortTitle: "LA"), + .init(id: "Europe/London", title: "London", shortTitle: "LONDON"), + .init(id: "Asia/Jerusalem", title: "Tel Aviv", shortTitle: "TEL AVIV"), + .init(id: "Europe/Paris", title: "Paris", shortTitle: "PARIS"), + .init(id: "Europe/Berlin", title: "Berlin", shortTitle: "BERLIN"), + .init(id: "Asia/Dubai", title: "Dubai", shortTitle: "DUBAI"), + .init(id: "Asia/Tokyo", title: "Tokyo", shortTitle: "TOKYO"), + .init(id: "Asia/Hong_Kong", title: "Hong Kong", shortTitle: "HONG KONG"), + .init(id: "Asia/Singapore", title: "Singapore", shortTitle: "SINGAPORE"), + .init(id: "Australia/Sydney", title: "Sydney", shortTitle: "SYDNEY"), + .init(id: "UTC", title: "UTC", shortTitle: "UTC") + ] + + static func option(for identifier: String) -> MarketClockZone { + options.first(where: { $0.id == identifier }) ?? options[0] + } +} + +@MainActor +final class MarketModel: ObservableObject { + @Published private(set) var focusedSymbol: String? + @Published private(set) var quotes: [String: MarketQuote] = [:] + @Published private(set) var histories: [String: [Double]] = [:] + @Published private(set) var rangeHistories: [String: [MarketTimeframe: [Double]]] = [:] + @Published private(set) var loadingRanges: Set = [] + @Published private(set) var unavailableRanges: Set = [] + @Published private(set) var symbols: [String] = MarketSymbols.parse(MarketSymbols.defaultValue) + @Published private(set) var state: MarketFeedState = .needsAPIKey + @Published private(set) var usdIlsHistory: [FXRatePoint] = [] + @Published private(set) var usdIlsUpdatedAt: Date? + + private var refreshTask: Task? + private var observer: NSObjectProtocol? + private let isPreview: Bool + private var cachedAPIKey: String? + private var attemptedKeychainLoad = false + private var rangeUpdatedAt: [String: Date] = [:] + + init(preview: Bool = false) { + isPreview = preview + if preview { + let prices = ["OKLO": 73.42, "RGTI": 18.63, "NXE": 7.91, "QUBT": 14.28, "QBTS": 17.54] + for (index, symbol) in symbols.enumerated() { + let price = prices[symbol] ?? 10 + quotes[symbol] = MarketQuote( + symbol: symbol, + price: price, + change: index.isMultiple(of: 2) ? price * 0.018 : -price * 0.012, + percentChange: index.isMultiple(of: 2) ? 1.8 : -1.2, + high: price * 1.035, + low: price * 0.965, + open: price * 0.984, + previousClose: price * 0.982, + tradeTime: Date() + ) + var previewHistory: [Double] = [] + for sample in 0..<36 { + let trend = Double(sample) / 2100 + let wave = sin(Double(sample) * 0.42 + Double(index)) * 0.008 + previewHistory.append(price * (0.985 + trend + wave)) + } + histories[symbol] = previewHistory + rangeHistories[symbol] = Dictionary(uniqueKeysWithValues: MarketTimeframe.allCases.map { timeframe in + let count: Int + switch timeframe { + case .today: count = 36 + case .week: count = 54 + case .month: count = 24 + case .year: count = 52 + } + let values = (0.. [Double] { + if let values = rangeHistories[symbol]?[timeframe], values.count > 1 { + return values + } + return timeframe == .today ? (histories[symbol] ?? []) : [] + } + + func isLoadingChart(for symbol: String, timeframe: MarketTimeframe) -> Bool { + loadingRanges.contains(rangeKey(symbol, timeframe)) + } + + func isChartUnavailable(for symbol: String, timeframe: MarketTimeframe) -> Bool { + unavailableRanges.contains(rangeKey(symbol, timeframe)) + } + + func loadChart(for symbol: String, timeframe: MarketTimeframe) async { + guard !isPreview else { return } + let key = rangeKey(symbol, timeframe) + if loadingRanges.contains(key) { return } + if let updated = rangeUpdatedAt[key], Date().timeIntervalSince(updated) < timeframe.refreshInterval { return } + + loadingRanges.insert(key) + unavailableRanges.remove(key) + defer { loadingRanges.remove(key) } + do { + let values = try await MarketAPI.yahooChart(symbol: symbol, timeframe: timeframe) + guard values.count > 1 else { + unavailableRanges.insert(key) + rangeUpdatedAt[key] = Date() + return + } + var ranges = rangeHistories[symbol] ?? [:] + ranges[timeframe] = values + rangeHistories[symbol] = ranges + rangeUpdatedAt[key] = Date() + } catch { + unavailableRanges.insert(key) + rangeUpdatedAt[key] = Date() + } + } + + private func rangeKey(_ symbol: String, _ timeframe: MarketTimeframe) -> String { + "\(symbol):\(timeframe.rawValue)" + } + + private func refresh() async { + let configured = UserDefaults.standard.string(forKey: "DockTelemetry.marketSymbols") ?? MarketSymbols.defaultValue + let nextSymbols = MarketSymbols.parse(configured) + symbols = nextSymbols.isEmpty ? MarketSymbols.parse(MarketSymbols.defaultValue) : nextSymbols + + await refreshExchangeRateIfNeeded() + + if !attemptedKeychainLoad { + cachedAPIKey = MarketKeychain.apiKey() + attemptedKeychainLoad = true + } + guard let apiKey = cachedAPIKey else { + state = .needsAPIKey + return + } + if quotes.isEmpty { state = .loading } + + let requestedSymbols = symbols + let results = await withTaskGroup(of: (String, Result).self) { group in + for symbol in requestedSymbols { + group.addTask { + do { + return (symbol, .success(try await MarketAPI.quote(symbol: symbol, apiKey: apiKey))) + } catch { + return (symbol, .failure(error)) + } + } + } + var collected: [(String, Result)] = [] + for await result in group { collected.append(result) } + return collected + } + + var successful = 0 + var lastError: Error? + for (symbol, result) in results { + switch result { + case .success(let quote): + quotes[symbol] = quote + var samples = histories[symbol] ?? [] + samples.append(quote.price) + if samples.count > 90 { samples.removeFirst(samples.count - 90) } + histories[symbol] = samples + successful += 1 + case .failure(let error): + lastError = error + } + } + + let now = Date() + if successful == requestedSymbols.count { + state = .live(now) + } else if successful > 0 || !quotes.isEmpty { + state = .stale(now) + } else { + state = .failed(lastError?.localizedDescription ?? "No quote data") + } + } + + private func refreshExchangeRateIfNeeded() async { + if let usdIlsUpdatedAt, Date().timeIntervalSince(usdIlsUpdatedAt) < 60 * 60 { return } + do { + let points = try await MarketAPI.usdIlsHistory() + guard !points.isEmpty else { return } + usdIlsHistory = points + usdIlsUpdatedAt = Date() + } catch { + // Keep the last successful daily reference series if the feed is temporarily unavailable. + } + } +} + +private enum MarketAPI { + static func quote(symbol: String, apiKey: String) async throws -> MarketQuote { + var components = URLComponents(string: "https://finnhub.io/api/v1/quote")! + components.queryItems = [URLQueryItem(name: "symbol", value: symbol)] + var request = URLRequest(url: components.url!) + request.timeoutInterval = 10 + request.setValue(apiKey, forHTTPHeaderField: "X-Finnhub-Token") + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { + throw MarketAPIError.badResponse + } + let payload = try JSONDecoder().decode(FinnhubQuote.self, from: data) + guard payload.c > 0 else { throw MarketAPIError.noQuote } + return MarketQuote( + symbol: symbol, + price: payload.c, + change: payload.d, + percentChange: payload.dp, + high: payload.h, + low: payload.l, + open: payload.o, + previousClose: payload.pc, + tradeTime: Date(timeIntervalSince1970: TimeInterval(payload.t)) + ) + } + + static func usdIlsHistory() async throws -> [FXRatePoint] { + let calendar = Calendar(identifier: .gregorian) + let start = calendar.date(byAdding: .day, value: -35, to: Date()) ?? Date() + let formatter = DateFormatter() + formatter.calendar = calendar + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd" + var components = URLComponents(string: "https://api.frankfurter.dev/v2/rates")! + components.queryItems = [ + URLQueryItem(name: "base", value: "USD"), + URLQueryItem(name: "quotes", value: "ILS"), + URLQueryItem(name: "from", value: formatter.string(from: start)) + ] + var request = URLRequest(url: components.url!) + request.timeoutInterval = 12 + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { + throw MarketAPIError.badResponse + } + let payload = try JSONDecoder().decode([FrankfurterRate].self, from: data) + return payload.compactMap { item in + guard item.quote == "ILS", let date = formatter.date(from: item.date) else { return nil } + return FXRatePoint(date: date, rate: item.rate) + } + .sorted { $0.date < $1.date } + .suffix(24) + .map { $0 } + } + + static func yahooChart(symbol: String, timeframe: MarketTimeframe) async throws -> [Double] { + let safeSymbol = symbol.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? symbol + var components = URLComponents(string: "https://query2.finance.yahoo.com/v8/finance/chart/\(safeSymbol)")! + components.queryItems = [ + URLQueryItem(name: "range", value: timeframe.yahooRange), + URLQueryItem(name: "interval", value: timeframe.yahooInterval) + ] + var request = URLRequest(url: components.url!) + request.timeoutInterval = 12 + request.setValue("Retrolemetry/1.0", forHTTPHeaderField: "User-Agent") + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { + throw MarketAPIError.badResponse + } + let payload = try JSONDecoder().decode(YahooChartResponse.self, from: data) + guard let closes = payload.chart.result?.first?.indicators.quote.first?.close else { + throw MarketAPIError.noChartData + } + return closes.compactMap { $0 } + } + + private struct FinnhubQuote: Decodable { + let c: Double + let d: Double + let dp: Double + let h: Double + let l: Double + let o: Double + let pc: Double + let t: Int + } + + private struct FrankfurterRate: Decodable { + let date: String + let base: String + let quote: String + let rate: Double + } + + private struct YahooChartResponse: Decodable { + let chart: Chart + + struct Chart: Decodable { + let result: [Result]? + } + + struct Result: Decodable { + let indicators: Indicators + } + + struct Indicators: Decodable { + let quote: [Quote] + } + + struct Quote: Decodable { + let close: [Double?] + } + } + + private enum MarketAPIError: LocalizedError { + case badResponse + case noQuote + case noChartData + + var errorDescription: String? { + switch self { + case .badResponse: "Finnhub did not accept the request" + case .noQuote: "No current quote is available" + case .noChartData: "No historical chart data is available" + } + } + } +} diff --git a/Sources/Retrolemetry/MarketInteractions.swift b/Sources/Retrolemetry/MarketInteractions.swift new file mode 100644 index 0000000..23dfffc --- /dev/null +++ b/Sources/Retrolemetry/MarketInteractions.swift @@ -0,0 +1,15 @@ +import Foundation + +/// Kept identical to the ticker's explicit header, padding and row spacing. +enum MarketTickerGeometry { + static func headerHeight(_ typography: ConsoleTypography) -> Double { max(12, 11 * typography.scale(.secondary, dimmed: true)) } + static func row(at point: CGPoint, frame: ModuleFrame, typography: ConsoleTypography) -> Int? { + guard frame.visible, frame.rect.contains(point) else { return nil } + let header = headerHeight(typography) + let top = frame.y + 7 + header + 1 + 6 + let height = max(0, (frame.height - 14 - header - 1 - 18) / 5) + guard height > 0, point.y >= top else { return nil } + let row = Int((point.y - top) / (height + 3)) + return (0..<5).contains(row) && point.y <= top + Double(row) * (height + 3) + height ? row : nil + } +} diff --git a/Sources/Retrolemetry/RadarMapData.swift b/Sources/Retrolemetry/RadarMapData.swift new file mode 100644 index 0000000..c31a023 --- /dev/null +++ b/Sources/Retrolemetry/RadarMapData.swift @@ -0,0 +1,218 @@ +// Geographic artwork only; not a boundary or navigation authority. +// Israel: Natural Earth 50m admin-0 countries, public domain (default de facto view). +// https://www.naturalearthdata.com/about/terms-of-use/ +// Tel Aviv-Yafo: OpenStreetMap relation 1382494, ODbL 1.0. Data copyright OSM contributors. +// https://www.openstreetmap.org/relation/1382494 and https://www.openstreetmap.org/copyright +// This city coordinate dataset remains under ODbL, separate from the MIT application code. +// Retrieved 2026-10-14; simplified by Nominatim to 0.0005 degrees. +enum RadarMapData { + static let israel: [SIMD2] = [ + SIMD2(35.840723, 33.415674), + SIMD2(35.816125, 33.361879), + SIMD2(35.792531, 33.334107), + SIMD2(35.785024, 33.291089), + SIMD2(35.800038, 33.256121), + SIMD2(35.808618, 33.208577), + SIMD2(35.826849, 33.195117), + SIMD2(35.833283, 33.163702), + SIMD2(35.817197, 33.133173), + SIMD2(35.824704, 33.108024), + SIMD2(35.84508, 33.084665), + SIMD2(35.859022, 32.989367), + SIMD2(35.887977, 32.944379), + SIMD2(35.841863, 32.875954), + SIMD2(35.833283, 32.820094), + SIMD2(35.787305, 32.734912), + SIMD2(35.734473, 32.728906), + SIMD2(35.61123, 32.68208), + SIMD2(35.594531, 32.668018), + SIMD2(35.572852, 32.640869), + SIMD2(35.569043, 32.619873), + SIMD2(35.551465, 32.395508), + SIMD2(35.484375, 32.40166), + SIMD2(35.402637, 32.450635), + SIMD2(35.386719, 32.493018), + SIMD2(35.362109, 32.507471), + SIMD2(35.303809, 32.512939), + SIMD2(35.193262, 32.534424), + SIMD2(35.065039, 32.460449), + SIMD2(35.010547, 32.338184), + SIMD2(34.999512, 32.281055), + SIMD2(34.955957, 32.160937), + SIMD2(34.971387, 32.087109), + SIMD2(34.978809, 31.991602), + SIMD2(34.989746, 31.913281), + SIMD2(34.97832, 31.866406), + SIMD2(34.953809, 31.84126), + SIMD2(34.961133, 31.82334), + SIMD2(34.983008, 31.816797), + SIMD2(35.053223, 31.837939), + SIMD2(35.127148, 31.816748), + SIMD2(35.198047, 31.776318), + SIMD2(35.203711, 31.75), + SIMD2(35.153418, 31.734473), + SIMD2(35.034668, 31.673242), + SIMD2(34.950977, 31.602295), + SIMD2(34.929199, 31.536572), + SIMD2(34.872754, 31.396875), + SIMD2(34.880469, 31.368164), + SIMD2(34.907813, 31.351318), + SIMD2(35.101172, 31.366211), + SIMD2(35.27666, 31.422803), + SIMD2(35.408691, 31.48291), + SIMD2(35.450586, 31.479297), + SIMD2(35.422852, 31.325391), + SIMD2(35.423535, 31.324854), + SIMD2(35.400684, 31.230518), + SIMD2(35.409668, 31.214453), + SIMD2(35.439258, 31.132422), + SIMD2(35.383008, 30.982275), + SIMD2(35.320117, 30.860205), + SIMD2(35.297852, 30.802246), + SIMD2(35.236621, 30.673486), + SIMD2(35.174023, 30.523926), + SIMD2(35.140625, 30.420898), + SIMD2(35.148145, 30.384326), + SIMD2(35.132617, 30.195312), + SIMD2(35.141602, 30.141699), + SIMD2(35.068164, 29.977881), + SIMD2(35.053418, 29.896924), + SIMD2(35.023926, 29.787061), + SIMD2(34.973438, 29.555029), + SIMD2(34.904297, 29.477344), + SIMD2(34.869824, 29.563916), + SIMD2(34.791113, 29.812109), + SIMD2(34.735059, 29.982031), + SIMD2(34.658594, 30.191455), + SIMD2(34.529688, 30.446045), + SIMD2(34.517773, 30.507373), + SIMD2(34.489941, 30.596289), + SIMD2(34.400977, 30.827832), + SIMD2(34.328516, 30.99502), + SIMD2(34.245313, 31.208301), + SIMD2(34.34834, 31.29292), + SIMD2(34.350195, 31.362744), + SIMD2(34.525586, 31.525635), + SIMD2(34.524121, 31.54165), + SIMD2(34.477344, 31.584863), + SIMD2(34.483984, 31.592285), + SIMD2(34.678418, 31.895703), + SIMD2(34.803809, 32.196338), + SIMD2(34.921875, 32.614062), + SIMD2(35.005859, 32.826611), + SIMD2(35.077051, 32.967187), + SIMD2(35.108594, 33.083691), + SIMD2(35.22334, 33.091992), + SIMD2(35.308887, 33.079541), + SIMD2(35.41123, 33.075684), + SIMD2(35.493164, 33.119482), + SIMD2(35.53252, 33.250488), + SIMD2(35.579297, 33.271484), + SIMD2(35.60293, 33.240625), + SIMD2(35.627246, 33.275049), + SIMD2(35.734473, 33.332617), + SIMD2(35.7875, 33.369775), + SIMD2(35.840723, 33.415674), + ] + static let telAviv: [SIMD2] = [ + SIMD2(34.739131, 32.033756), + SIMD2(34.743405, 32.033017), + SIMD2(34.749869, 32.029344), + SIMD2(34.750847, 32.030599), + SIMD2(34.755268, 32.031152), + SIMD2(34.755929, 32.033503), + SIMD2(34.759484, 32.032929), + SIMD2(34.759952, 32.036474), + SIMD2(34.765509, 32.036245), + SIMD2(34.774386, 32.032779), + SIMD2(34.778101, 32.038671), + SIMD2(34.778824, 32.038237), + SIMD2(34.786001, 32.046825), + SIMD2(34.78808, 32.046759), + SIMD2(34.790555, 32.041484), + SIMD2(34.796805, 32.039728), + SIMD2(34.807252, 32.034553), + SIMD2(34.809749, 32.041538), + SIMD2(34.812423, 32.040916), + SIMD2(34.813813, 32.044601), + SIMD2(34.813241, 32.044694), + SIMD2(34.81388, 32.050315), + SIMD2(34.813003, 32.052352), + SIMD2(34.810427, 32.05486), + SIMD2(34.811796, 32.058632), + SIMD2(34.806141, 32.061627), + SIMD2(34.804492, 32.065628), + SIMD2(34.80281, 32.066047), + SIMD2(34.802566, 32.070456), + SIMD2(34.800599, 32.072926), + SIMD2(34.801933, 32.077714), + SIMD2(34.797859, 32.080211), + SIMD2(34.80002, 32.08119), + SIMD2(34.799122, 32.084393), + SIMD2(34.801785, 32.092929), + SIMD2(34.802214, 32.093405), + SIMD2(34.804219, 32.091007), + SIMD2(34.807054, 32.091166), + SIMD2(34.806958, 32.089776), + SIMD2(34.809324, 32.090977), + SIMD2(34.808561, 32.094394), + SIMD2(34.80974, 32.095093), + SIMD2(34.809705, 32.096319), + SIMD2(34.812884, 32.095743), + SIMD2(34.815619, 32.098177), + SIMD2(34.818215, 32.097794), + SIMD2(34.818992, 32.09625), + SIMD2(34.81998, 32.096287), + SIMD2(34.822621, 32.099148), + SIMD2(34.821168, 32.101198), + SIMD2(34.82419, 32.102337), + SIMD2(34.822957, 32.103627), + SIMD2(34.825178, 32.10494), + SIMD2(34.828715, 32.105837), + SIMD2(34.835873, 32.105164), + SIMD2(34.83974, 32.106991), + SIMD2(34.841461, 32.106907), + SIMD2(34.842951, 32.108419), + SIMD2(34.846656, 32.10662), + SIMD2(34.849252, 32.107032), + SIMD2(34.852262, 32.119401), + SIMD2(34.850382, 32.120326), + SIMD2(34.848907, 32.118705), + SIMD2(34.844279, 32.119721), + SIMD2(34.844404, 32.12046), + SIMD2(34.842058, 32.121483), + SIMD2(34.842004, 32.123339), + SIMD2(34.839946, 32.123937), + SIMD2(34.83995, 32.125768), + SIMD2(34.836435, 32.125875), + SIMD2(34.837307, 32.127695), + SIMD2(34.828911, 32.128695), + SIMD2(34.828043, 32.127841), + SIMD2(34.826181, 32.127853), + SIMD2(34.827595, 32.130363), + SIMD2(34.819517, 32.130676), + SIMD2(34.821776, 32.12588), + SIMD2(34.824028, 32.123985), + SIMD2(34.823569, 32.123271), + SIMD2(34.811163, 32.124431), + SIMD2(34.809008, 32.128398), + SIMD2(34.804469, 32.130696), + SIMD2(34.799862, 32.130526), + SIMD2(34.797511, 32.128603), + SIMD2(34.795596, 32.128702), + SIMD2(34.797017, 32.13434), + SIMD2(34.801337, 32.140883), + SIMD2(34.802436, 32.144024), + SIMD2(34.78763, 32.146977), + SIMD2(34.775431, 32.114155), + SIMD2(34.7715, 32.110011), + SIMD2(34.771245, 32.103602), + SIMD2(34.766219, 32.095138), + SIMD2(34.759114, 32.071652), + SIMD2(34.754018, 32.060576), + SIMD2(34.748075, 32.057707), + SIMD2(34.74077, 32.047984), + SIMD2(34.740775, 32.038572), + SIMD2(34.739131, 32.033756), + ] +} diff --git a/Sources/Retrolemetry/RadarWeather.swift b/Sources/Retrolemetry/RadarWeather.swift new file mode 100644 index 0000000..f9784b1 --- /dev/null +++ b/Sources/Retrolemetry/RadarWeather.swift @@ -0,0 +1,161 @@ +import Foundation +import simd + +/// Public, fixed forecast samples. These are not the user's location or radar echoes. +struct RadarWeatherSite: Equatable { + let name: String + let latitude: Double + let longitude: Double + + static let all: [Self] = [ + Self(name: "NORTH", latitude: 33.2075, longitude: 35.5707), + Self(name: "HAIFA", latitude: 32.7940, longitude: 34.9896), + Self(name: "TEL AVIV", latitude: 32.0853, longitude: 34.7818), + Self(name: "JERUSALEM", latitude: 31.7683, longitude: 35.2137), + Self(name: "BEER SHEVA", latitude: 31.2520, longitude: 34.7915), + Self(name: "EILAT", latitude: 29.5581, longitude: 34.9482) + ] +} + +struct RadarWeatherPoint { + let site: RadarWeatherSite + let temperature: Double? + let windSpeed: Double? + let windDirection: Double? + let rainChance: Double? + let forecastAt: Date + + func value(for mode: RadarTargetMode) -> Double? { + switch mode { + case .precipitation: rainChance + case .temperature: temperature + case .wind: windSpeed + case .decorative: nil + } + } + + func readout(for mode: RadarTargetMode) -> String { + guard let value = value(for: mode) else { return "N/A" } + switch mode { + case .precipitation: return String(format: "%.0f%%", value * 100) + case .temperature: return String(format: "%.0f°C", value) + case .wind: return String(format: "%.0f KM/H", value) + case .decorative: return "DEMO" + } + } + + static func preview(at date: Date = Date(), region: RadarRegion = .israel) -> [Self] { + region.sites.enumerated().map { i, site in + Self(site: site, temperature: 20 + Double(i)*1.5, + windSpeed: 9 + Double(i)*3, windDirection: Double(210 + i*12), + rainChance: [0.6, 0.35, 0.2, 0.4, 0.1, 0.02][i], forecastAt: date) + } + } +} + +enum RegionalWeatherFeed { + static var url: URL { url(for: .israel) } + static func url(for region: RadarRegion) -> URL { + var parts = URLComponents(string: "https://api.open-meteo.com/v1/forecast")! + parts.queryItems = [ + URLQueryItem(name: "latitude", value: region.sites.map { String($0.latitude) }.joined(separator: ",")), + URLQueryItem(name: "longitude", value: region.sites.map { String($0.longitude) }.joined(separator: ",")), + URLQueryItem(name: "current", value: "temperature_2m,wind_speed_10m,wind_direction_10m"), + URLQueryItem(name: "hourly", value: "precipitation_probability"), + URLQueryItem(name: "forecast_days", value: "2"), + URLQueryItem(name: "wind_speed_unit", value: "kmh"), + URLQueryItem(name: "timeformat", value: "unixtime"), + URLQueryItem(name: "timezone", value: "GMT") + ] + return parts.url! + } + + static func decode(_ data: Data, region: RadarRegion = .israel, at now: Date = Date()) throws -> [RadarWeatherPoint] { + let payloads = try JSONDecoder().decode([Payload].self, from: data) + guard payloads.count == region.sites.count else { throw URLError(.cannotParseResponse) } + return try zip(region.sites, payloads).map { site, payload in + // The batch is returned in request order. Reject a mismatched location rather + // than pinning another area's forecast to this target. + guard abs(site.latitude - payload.latitude) < 0.3, + abs(site.longitude - payload.longitude) < 0.3 else { throw URLError(.cannotParseResponse) } + func valid(_ value: Double?, _ range: ClosedRange) -> Double? { + value.flatMap { $0.isFinite && range.contains($0) ? $0 : nil } + } + let count = min(payload.hourly.time.count, payload.hourly.precipitationProbability.count) + let hour = (0.. now.timeIntervalSince1970 + } + let rain = hour.flatMap { valid(payload.hourly.precipitationProbability[$0], 0...100) }.map { $0 / 100 } + let timestamp = payload.current.time + guard timestamp.isFinite, abs(timestamp - now.timeIntervalSince1970) < 3600 else { + throw URLError(.cannotParseResponse) + } + return RadarWeatherPoint(site: site, + temperature: valid(payload.current.temperature, -90...65), + windSpeed: valid(payload.current.windSpeed, 0...500), + windDirection: valid(payload.current.windDirection, 0...360), rainChance: rain, + forecastAt: Date(timeIntervalSince1970: timestamp)) + } + } + + private struct Payload: Decodable { + let latitude: Double + let longitude: Double + let current: Current + let hourly: Hourly + struct Current: Decodable { + let time: Double + let temperature: Double? + let windSpeed: Double? + let windDirection: Double? + enum CodingKeys: String, CodingKey { + case time, temperature = "temperature_2m", windSpeed = "wind_speed_10m", windDirection = "wind_direction_10m" + } + } + struct Hourly: Decodable { + let time: [Double] + let precipitationProbability: [Double?] + enum CodingKeys: String, CodingKey { case time, precipitationProbability = "precipitation_probability" } + } + } +} + +/// Same inexpensive local projection for the Metal layer and static layout preview. +enum RadarMapGeometry { + static func position(latitude: Double, longitude: Double, region: RadarRegion = .israel) -> SIMD2 { + let center: (lon: Double, lat: Double, span: Double) + switch region { + case .israel: center = (35.05, 31.45, 2.25) + case .northAmerica: center = (-110, 45, 58) + case .europe: center = (10, 53, 30) + } + let scaleLatitude = region == .israel ? 32 : center.lat + return SIMD2(Float((longitude - center.lon) * cos(scaleLatitude * .pi / 180) / center.span), Float((center.lat - latitude) / center.span)) + } + static var segments: [SIMD4] { segments(for: .israel) } + static func segments(for region: RadarRegion) -> [SIMD4] { cached[region] ?? [] } + private static let cached: [RadarRegion: [SIMD4]] = { + func edges(_ ring: [SIMD2]) -> [SIMD4] { + zip(ring, ring.dropFirst()).map { a, b in + let p = position(latitude: Double(a.y), longitude: Double(a.x)) + let q = position(latitude: Double(b.y), longitude: Double(b.x)) + return SIMD4(p.x, p.y, q.x, q.y) + } + } + func projected(_ edges: [SIMD4], region: RadarRegion) -> [SIMD4] { + edges.map { edge in + let p = position(latitude: Double(edge.y), longitude: Double(edge.x), region: region) + let q = position(latitude: Double(edge.w), longitude: Double(edge.z), region: region) + return SIMD4(p.x, p.y, q.x, q.y) + } + } + return [.israel: edges(RadarMapData.israel) + edges(RadarMapData.telAviv), + .northAmerica: projected(RegionalMapData.northAmerica, region: .northAmerica), + .europe: projected(RegionalMapData.europe, region: .europe)] + }() + static var countrySegmentCount: Int { RadarMapData.israel.count - 1 } + static func countrySegmentCount(for region: RadarRegion) -> Int { + region == .israel ? countrySegmentCount : segments(for: region).count + } +} diff --git a/Sources/Retrolemetry/RegionalMapData.swift b/Sources/Retrolemetry/RegionalMapData.swift new file mode 100644 index 0000000..f44cc86 --- /dev/null +++ b/Sources/Retrolemetry/RegionalMapData.swift @@ -0,0 +1,2237 @@ +// Public-domain Natural Earth 50m admin-0 country artwork, simplified to 0.30 degrees. +// Default de facto boundaries; clipped coverage; not a navigation/boundary authority. +// https://www.naturalearthdata.com/about/terms-of-use/ +// Regenerate with scripts/prepare_regional_maps.mjs and ne_50m_admin_0_countries.geojson. +enum RegionalMapData { + static let northAmerica: [SIMD4] = [ +SIMD4(-66.1294, 18.4449, -65.6209, 18.2423), + SIMD4(-65.6209, 18.2423, -66.7724, 17.9866), + SIMD4(-66.7724, 17.9866, -67.1969, 17.9942), + SIMD4(-67.1969, 17.9942, -67.1586, 18.4992), + SIMD4(-67.1586, 18.4992, -66.1294, 18.4449), + SIMD4(-168.716, 63.3106, -169.5713, 62.9968), + SIMD4(-166.1354, 60.3835, -165.5918, 59.9131), + SIMD4(-165.5918, 59.9131, -166.1875, 59.7738), + SIMD4(-166.1875, 59.7738, -167.4364, 60.2066), + SIMD4(-167.4364, 60.2066, -166.1354, 60.3835), + SIMD4(-152.898, 57.8239, -152.2162, 57.577), + SIMD4(-152.2162, 57.577, -153.9727, 56.7742), + SIMD4(-153.9727, 56.7742, -154.3768, 57.107), + SIMD4(-154.3768, 57.107, -154.5353, 57.5594), + SIMD4(-154.5353, 57.5594, -153.6877, 57.3051), + SIMD4(-153.6877, 57.3051, -153.8416, 57.8628), + SIMD4(-153.8416, 57.8628, -152.898, 57.8239), + SIMD4(-130.0251, 55.8882, -130.5753, 54.7697), + SIMD4(-130.5753, 54.7697, -131.0479, 55.1577), + SIMD4(-131.0479, 55.1577, -131.0328, 56.0881), + SIMD4(-131.0328, 56.0881, -132.119, 55.5698), + SIMD4(-132.119, 55.5698, -131.5514, 56.2068), + SIMD4(-131.5514, 56.2068, -133.4659, 57.1722), + SIMD4(-133.4659, 57.1722, -133.6487, 57.6423), + SIMD4(-133.6487, 57.6423, -133.117, 57.5662), + SIMD4(-133.117, 57.5662, -133.5352, 57.833), + SIMD4(-133.5352, 57.833, -133.1943, 57.8777), + SIMD4(-133.1943, 57.8777, -134.0311, 58.0722), + SIMD4(-134.0311, 58.0722, -133.8768, 58.5182), + SIMD4(-133.8768, 58.5182, -134.7761, 58.4539), + SIMD4(-134.7761, 58.4539, -135.3637, 59.4194), + SIMD4(-135.3637, 59.4194, -135.0902, 58.2458), + SIMD4(-135.0902, 58.2458, -135.8976, 58.4002), + SIMD4(-135.8976, 58.4002, -136.15, 59.0481), + SIMD4(-136.15, 59.0481, -136.989, 59.0345), + SIMD4(-136.989, 59.0345, -136.0615, 58.4527), + SIMD4(-136.0615, 58.4527, -136.6074, 58.244), + SIMD4(-136.6074, 58.244, -139.7991, 59.5462), + SIMD4(-139.7991, 59.5462, -138.9881, 59.835), + SIMD4(-138.9881, 59.835, -139.4314, 60.0123), + SIMD4(-139.4314, 60.0123, -140.4198, 59.7107), + SIMD4(-140.4198, 59.7107, -141.4087, 60.1177), + SIMD4(-141.4087, 60.1177, -144.1472, 60.0164), + SIMD4(-144.1472, 60.0164, -144.9013, 60.3352), + SIMD4(-144.9013, 60.3352, -144.6911, 60.6691), + SIMD4(-144.6911, 60.6691, -145.2483, 60.3801), + SIMD4(-145.2483, 60.3801, -146.5705, 60.7291), + SIMD4(-146.5705, 60.7291, -146.3844, 61.1358), + SIMD4(-146.3844, 61.1358, -148.3419, 61.0604), + SIMD4(-148.3419, 61.0604, -148.6401, 60.4895), + SIMD4(-148.6401, 60.4895, -147.9641, 60.4849), + SIMD4(-147.9641, 60.4849, -148.4307, 59.9891), + SIMD4(-148.4307, 59.9891, -149.3953, 60.1058), + SIMD4(-149.3953, 60.1058, -150.9345, 59.2491), + SIMD4(-150.9345, 59.2491, -151.9495, 59.2651), + SIMD4(-151.9495, 59.2651, -151.0465, 59.7718), + SIMD4(-151.0465, 59.7718, -151.8532, 59.7821), + SIMD4(-151.8532, 59.7821, -151.3218, 60.7429), + SIMD4(-151.3218, 60.7429, -149.0751, 60.8764), + SIMD4(-149.0751, 60.8764, -150.0533, 61.1711), + SIMD4(-150.0533, 61.1711, -149.4335, 61.5008), + SIMD4(-149.4335, 61.5008, -153.025, 60.2957), + SIMD4(-153.025, 60.2957, -152.6601, 59.9972), + SIMD4(-152.6601, 59.9972, -154.1783, 59.1556), + SIMD4(-154.1783, 59.1556, -153.4376, 58.7548), + SIMD4(-153.4376, 58.7548, -158.4761, 56.0755), + SIMD4(-158.4761, 56.0755, -161.5169, 55.6184), + SIMD4(-161.5169, 55.6184, -163.3353, 54.8392), + SIMD4(-163.3353, 54.8392, -161.1925, 55.9543), + SIMD4(-161.1925, 55.9543, -160.2917, 55.8051), + SIMD4(-160.2917, 55.8051, -160.3021, 56.3141), + SIMD4(-160.3021, 56.3141, -157.4619, 57.5062), + SIMD4(-157.4619, 57.5062, -157.6109, 58.0508), + SIMD4(-157.6109, 58.0508, -157.1937, 58.1942), + SIMD4(-157.1937, 58.1942, -157.5236, 58.4213), + SIMD4(-157.5236, 58.4213, -156.8089, 59.1343), + SIMD4(-156.8089, 59.1343, -158.1909, 58.6143), + SIMD4(-158.1909, 58.6143, -158.5032, 58.8503), + SIMD4(-158.5032, 58.8503, -158.0805, 58.9774), + SIMD4(-158.0805, 58.9774, -158.8095, 58.9739), + SIMD4(-158.8095, 58.9739, -158.9507, 58.4045), + SIMD4(-158.9507, 58.4045, -160.3631, 59.0512), + SIMD4(-160.3631, 59.0512, -162.1449, 58.6442), + SIMD4(-162.1449, 58.6442, -161.6444, 59.1097), + SIMD4(-161.6444, 59.1097, -162.4213, 60.284), + SIMD4(-162.4213, 60.284, -161.9466, 60.6848), + SIMD4(-161.9466, 60.6848, -162.5708, 59.9897), + SIMD4(-162.5708, 59.9897, -163.9069, 59.8068), + SIMD4(-163.9069, 59.8068, -165.3538, 60.5412), + SIMD4(-165.3538, 60.5412, -163.5869, 60.903), + SIMD4(-163.5869, 60.903, -165.1148, 60.9328), + SIMD4(-165.1148, 60.9328, -164.869, 61.1118), + SIMD4(-164.869, 61.1118, -166.1681, 61.6508), + SIMD4(-166.1681, 61.6508, -164.7579, 62.4967), + SIMD4(-164.7579, 62.4967, -164.409, 63.215), + SIMD4(-164.409, 63.215, -163.2878, 63.0464), + SIMD4(-163.2878, 63.0464, -160.9267, 63.6605), + SIMD4(-160.9267, 63.6605, -161.4907, 64.4338), + SIMD4(-161.4907, 64.4338, -160.887, 64.7956), + SIMD4(-160.887, 64.7956, -162.7111, 64.3775), + SIMD4(-162.7111, 64.3775, -166.1428, 64.5828), + SIMD4(-166.1428, 64.5828, -166.9284, 65.1571), + SIMD4(-166.9284, 65.1571, -166.157, 65.2858), + SIMD4(-166.157, 65.2858, -168.0884, 65.6578), + SIMD4(-168.0884, 65.6578, -164.4605, 66.5884), + SIMD4(-164.4605, 66.5884, -163.6382, 66.5747), + SIMD4(-163.6382, 66.5747, -164.0337, 66.2155), + SIMD4(-164.0337, 66.2155, -163.6954, 66.0838), + SIMD4(-163.6954, 66.0838, -161.0343, 66.1888), + SIMD4(-161.0343, 66.1888, -162.3616, 66.9473), + SIMD4(-162.3616, 66.9473, -160.2317, 66.4203), + SIMD4(-160.2317, 66.4203, -166.7863, 68.3596), + SIMD4(-166.7863, 68.3596, -166.2091, 68.8854), + SIMD4(-166.2091, 68.8854, -163.5357, 69.1701), + SIMD4(-163.5357, 69.1701, -161.881, 70.3317), + SIMD4(-161.881, 70.3317, -160.1171, 70.5912), + SIMD4(-160.1171, 70.5912, -159.8657, 70.2789), + SIMD4(-159.8657, 70.2789, -159.3868, 70.5245), + SIMD4(-159.3868, 70.5245, -160.0816, 70.6349), + SIMD4(-160.0816, 70.6349, -159.6809, 70.7868), + SIMD4(-159.6809, 70.7868, -156.4702, 71.4077), + SIMD4(-156.4702, 71.4077, -155.5794, 71.1211), + SIMD4(-155.5794, 71.1211, -155.9735, 70.842), + SIMD4(-155.9735, 70.842, -154.9438, 71.0831), + SIMD4(-154.9438, 71.0831, -152.3004, 70.8468), + SIMD4(-152.3004, 70.8468, -151.9447, 70.4521), + SIMD4(-151.9447, 70.4521, -143.2183, 70.1163), + SIMD4(-143.2183, 70.1163, -141.0021, 69.6508), + SIMD4(-141.0021, 69.6508, -141.0021, 60.3002), + SIMD4(-141.0021, 60.3002, -139.0792, 60.3437), + SIMD4(-139.0792, 60.3437, -137.4386, 58.9031), + SIMD4(-137.4386, 58.9031, -135.4759, 59.7933), + SIMD4(-135.4759, 59.7933, -133.4011, 58.4109), + SIMD4(-133.4011, 58.4109, -131.8243, 56.59), + SIMD4(-131.8243, 56.59, -130.0251, 55.8882), + SIMD4(-163.476, 54.9807, -163.0833, 54.669), + SIMD4(-163.0833, 54.669, -164.7438, 54.4075), + SIMD4(-164.7438, 54.4075, -164.4786, 54.9068), + SIMD4(-164.4786, 54.9068, -163.476, 54.9807), + SIMD4(-130.9792, 55.4892, -131.7237, 55.2184), + SIMD4(-131.7237, 55.2184, -131.625, 55.8317), + SIMD4(-131.625, 55.8317, -130.9792, 55.4892), + SIMD4(-133.3662, 57.0035, -132.9541, 56.8803), + SIMD4(-132.9541, 56.8803, -133.1566, 56.6111), + SIMD4(-133.1566, 56.6111, -133.6028, 56.4641), + SIMD4(-133.6028, 56.4641, -133.9794, 57.0096), + SIMD4(-133.9794, 57.0096, -133.3662, 57.0035), + SIMD4(-134.9698, 57.3514, -134.654, 56.2275), + SIMD4(-134.654, 56.2275, -135.1631, 56.8241), + SIMD4(-135.1631, 56.8241, -135.8228, 57.2804), + SIMD4(-135.8228, 57.2804, -134.9698, 57.3514), + SIMD4(-134.6803, 58.1617, -134.0702, 57.9945), + SIMD4(-134.0702, 57.9945, -133.9088, 57.3687), + SIMD4(-133.9088, 57.3687, -134.5915, 57.092), + SIMD4(-134.5915, 57.092, -134.9235, 58.3546), + SIMD4(-134.9235, 58.3546, -134.6803, 58.1617), + SIMD4(-135.7304, 58.2442, -134.9547, 58.0153), + SIMD4(-134.9547, 58.0153, -135.2202, 57.5736), + SIMD4(-135.2202, 57.5736, -135.9108, 57.4466), + SIMD4(-135.9108, 57.4466, -136.5686, 57.9722), + SIMD4(-136.5686, 57.9722, -135.7304, 58.2442), + SIMD4(-133.5661, 56.3392, -132.1727, 55.4806), + SIMD4(-132.1727, 55.4806, -132.6313, 55.4732), + SIMD4(-132.6313, 55.4732, -131.9764, 55.2086), + SIMD4(-131.9764, 55.2086, -132.0217, 54.7263), + SIMD4(-132.0217, 54.7263, -132.4687, 54.9379), + SIMD4(-132.4687, 54.9379, -133.6802, 55.7852), + SIMD4(-133.6802, 55.7852, -133.2415, 55.9208), + SIMD4(-133.2415, 55.9208, -133.7425, 55.9648), + SIMD4(-133.7425, 55.9648, -133.5661, 56.3392), + SIMD4(-133.9896, 56.845, -134.0675, 56.133), + SIMD4(-134.0675, 56.133, -134.3906, 56.7495), + SIMD4(-134.3906, 56.7495, -133.9896, 56.845), + SIMD4(-152.4169, 58.3602, -151.9825, 58.2443), + SIMD4(-151.9825, 58.2443, -152.5582, 58.1186), + SIMD4(-152.5582, 58.1186, -153.3813, 58.0872), + SIMD4(-153.3813, 58.0872, -152.4169, 58.3602), + SIMD4(-166.6153, 53.9009, -166.2309, 53.9326), + SIMD4(-166.2309, 53.9326, -167.7809, 53.3002), + SIMD4(-167.7809, 53.3002, -166.6153, 53.9009), + SIMD4(-155.5813, 19.012, -156.0487, 19.75), + SIMD4(-156.0487, 19.75, -155.8316, 20.2758), + SIMD4(-155.8316, 20.2758, -154.8042, 19.5245), + SIMD4(-154.8042, 19.5245, -155.5813, 19.012), + SIMD4(-74.7089, 45.0039, -70.865, 45.2707), + SIMD4(-70.865, 45.2707, -69.2429, 47.463), + SIMD4(-69.2429, 47.463, -67.8068, 47.0828), + SIMD4(-67.8068, 47.0828, -67.8022, 45.7275), + SIMD4(-67.8022, 45.7275, -66.987, 44.8277), + SIMD4(-66.987, 44.8277, -68.5325, 44.2586), + SIMD4(-68.5325, 44.2586, -68.7627, 44.5708), + SIMD4(-68.7627, 44.5708, -70.2692, 43.6719), + SIMD4(-70.2692, 43.6719, -71.0462, 42.3311), + SIMD4(-71.0462, 42.3311, -69.9486, 41.6771), + SIMD4(-69.9486, 41.6771, -71.3901, 41.7953), + SIMD4(-71.3901, 41.7953, -71.5229, 41.379), + SIMD4(-71.5229, 41.379, -73.9871, 40.7514), + SIMD4(-73.9871, 40.7514, -73.9699, 41.2497), + SIMD4(-73.9699, 41.2497, -74.0799, 39.7881), + SIMD4(-74.0799, 39.7881, -74.7945, 39.0019), + SIMD4(-74.7945, 39.0019, -75.5242, 39.4902), + SIMD4(-75.5242, 39.4902, -75.0742, 39.9835), + SIMD4(-75.0742, 39.9835, -75.5876, 39.6408), + SIMD4(-75.5876, 39.6408, -75.0388, 38.4264), + SIMD4(-75.0388, 38.4264, -75.9344, 37.1519), + SIMD4(-75.9344, 37.1519, -75.6593, 37.954), + SIMD4(-75.6593, 37.954, -76.3412, 38.7097), + SIMD4(-76.3412, 38.7097, -75.8729, 39.5109), + SIMD4(-75.8729, 39.5109, -76.5704, 39.2693), + SIMD4(-76.5704, 39.2693, -76.3412, 38.087), + SIMD4(-76.3412, 38.087, -77.2325, 38.4077), + SIMD4(-77.2325, 38.4077, -77.0304, 38.8893), + SIMD4(-77.0304, 38.8893, -77.2604, 38.6), + SIMD4(-77.2604, 38.6, -76.2643, 37.8936), + SIMD4(-76.2643, 37.8936, -77.1111, 38.1657), + SIMD4(-77.1111, 38.1657, -76.2833, 37.0527), + SIMD4(-76.2833, 37.0527, -77.2509, 37.3292), + SIMD4(-77.2509, 37.3292, -75.9994, 36.9126), + SIMD4(-75.9994, 36.9126, -75.5342, 35.8191), + SIMD4(-75.5342, 35.8191, -75.9465, 36.6591), + SIMD4(-75.9465, 36.6591, -75.8201, 36.1128), + SIMD4(-75.8201, 36.1128, -76.7336, 36.2291), + SIMD4(-76.7336, 36.2291, -75.7588, 35.8433), + SIMD4(-75.7588, 35.8433, -76.1738, 35.3541), + SIMD4(-76.1738, 35.3541, -77.04, 35.5274), + SIMD4(-77.04, 35.5274, -76.4398, 34.8429), + SIMD4(-76.4398, 34.8429, -77.4123, 34.7308), + SIMD4(-77.4123, 34.7308, -77.9278, 33.9397), + SIMD4(-77.9278, 33.9397, -80.8025, 32.448), + SIMD4(-80.8025, 32.448, -81.5204, 30.8747), + SIMD4(-81.5204, 30.8747, -80.0887, 26.9939), + SIMD4(-80.0887, 26.9939, -80.3669, 25.3313), + SIMD4(-80.3669, 25.3313, -81.1105, 25.138), + SIMD4(-81.1105, 25.138, -82.7146, 27.4996), + SIMD4(-82.7146, 27.4996, -82.6515, 28.8875), + SIMD4(-82.6515, 28.8875, -83.6944, 29.926), + SIMD4(-83.6944, 29.926, -85.3189, 29.6802), + SIMD4(-85.3189, 29.6802, -85.6035, 30.2868), + SIMD4(-85.6035, 30.2868, -87.2012, 30.3393), + SIMD4(-87.2012, 30.3393, -86.9976, 30.5703), + SIMD4(-86.9976, 30.5703, -87.985, 30.2544), + SIMD4(-87.985, 30.2544, -88.0113, 30.6942), + SIMD4(-88.0113, 30.6942, -88.1354, 30.3666), + SIMD4(-88.1354, 30.3666, -90.2253, 30.3793), + SIMD4(-90.2253, 30.3793, -90.285, 30.0651), + SIMD4(-90.285, 30.0651, -89.4007, 30.046), + SIMD4(-89.4007, 30.046, -89.7209, 29.6193), + SIMD4(-89.7209, 29.6193, -89.0157, 29.2029), + SIMD4(-89.0157, 29.2029, -89.3761, 28.9813), + SIMD4(-89.3761, 28.9813, -90.1591, 29.5372), +SIMD4(-90.1591, 29.5372, -90.2128, 29.1049), + SIMD4(-90.2128, 29.1049, -91.2901, 29.289), + SIMD4(-91.2901, 29.289, -91.8932, 29.836), + SIMD4(-91.8932, 29.836, -92.2608, 29.5568), + SIMD4(-92.2608, 29.5568, -93.8415, 29.9797), + SIMD4(-93.8415, 29.9797, -94.7596, 29.3843), + SIMD4(-94.7596, 29.3843, -95.0229, 29.7023), + SIMD4(-95.0229, 29.7023, -95.2735, 28.9639), + SIMD4(-95.2735, 28.9639, -96.64, 28.7088), + SIMD4(-96.64, 28.7088, -96.4211, 28.4573), + SIMD4(-96.4211, 28.4573, -97.1565, 28.1443), + SIMD4(-97.1565, 28.1443, -97.4391, 27.3283), + SIMD4(-97.4391, 27.3283, -97.7685, 27.4575), + SIMD4(-97.7685, 27.4575, -97.3756, 25.8718), + SIMD4(-97.3756, 25.8718, -99.1078, 26.4469), + SIMD4(-99.1078, 26.4469, -101.3804, 29.7426), + SIMD4(-101.3804, 29.7426, -102.3431, 29.865), + SIMD4(-102.3431, 29.865, -103.2577, 29.0011), + SIMD4(-103.2577, 29.0011, -104.4006, 29.5737), + SIMD4(-104.4006, 29.5737, -104.9179, 30.5833), + SIMD4(-104.9179, 30.5833, -106.4454, 31.7684), + SIMD4(-106.4454, 31.7684, -111.042, 31.3242), + SIMD4(-111.042, 31.3242, -114.7248, 32.7153), + SIMD4(-114.7248, 32.7153, -117.1283, 32.5333), + SIMD4(-117.1283, 32.5333, -118.5062, 34.0174), + SIMD4(-118.5062, 34.0174, -120.6447, 34.58), + SIMD4(-120.6447, 34.58, -122.4992, 37.5426), + SIMD4(-122.4992, 37.5426, -122.0705, 37.4783), + SIMD4(-122.0705, 37.4783, -122.3143, 38.0073), + SIMD4(-122.3143, 38.0073, -121.5253, 38.0559), + SIMD4(-121.5253, 38.0559, -122.9988, 37.9886), + SIMD4(-122.9988, 37.9886, -123.7011, 38.9073), + SIMD4(-123.7011, 38.9073, -124.3565, 40.3711), + SIMD4(-124.3565, 40.3711, -124.0719, 41.4595), + SIMD4(-124.0719, 41.4595, -124.5396, 42.8129), + SIMD4(-124.5396, 42.8129, -123.9893, 46.2194), + SIMD4(-123.9893, 46.2194, -123.2206, 46.1536), + SIMD4(-123.2206, 46.1536, -124.0728, 46.2794), + SIMD4(-124.0728, 46.2794, -123.8429, 46.9632), + SIMD4(-123.8429, 46.9632, -124.71, 48.3804), + SIMD4(-124.71, 48.3804, -122.7786, 48.1376), + SIMD4(-122.7786, 48.1376, -123.1391, 47.3861), + SIMD4(-123.1391, 47.3861, -122.5328, 47.9197), + SIMD4(-122.5328, 47.9197, -123.0276, 47.1389), + SIMD4(-123.0276, 47.1389, -122.702, 47.1109), + SIMD4(-122.702, 47.1109, -122.242, 48.0107), + SIMD4(-122.242, 48.0107, -122.7888, 48.993), + SIMD4(-122.7888, 48.993, -95.1621, 48.9917), + SIMD4(-95.1621, 48.9917, -95.1553, 49.3697), + SIMD4(-95.1553, 49.3697, -94.6209, 48.7426), + SIMD4(-94.6209, 48.7426, -91.5183, 48.0583), + SIMD4(-91.5183, 48.0583, -88.3782, 48.3031), + SIMD4(-88.3782, 48.3031, -84.1495, 46.5428), + SIMD4(-84.1495, 46.5428, -82.5511, 45.3474), + SIMD4(-82.5511, 45.3474, -82.1378, 43.5709), + SIMD4(-82.1378, 43.5709, -83.1497, 42.1419), + SIMD4(-83.1497, 42.1419, -82.69, 41.6752), + SIMD4(-82.69, 41.6752, -79.0367, 42.8023), + SIMD4(-79.0367, 42.8023, -78.8456, 43.5834), + SIMD4(-78.8456, 43.5834, -76.82, 43.6288), + SIMD4(-76.82, 43.6288, -74.7089, 45.0039), + SIMD4(-72.5098, 40.986, -71.9032, 41.0607), + SIMD4(-71.9032, 41.0607, -73.929, 40.5988), + SIMD4(-73.929, 40.5988, -72.5098, 40.986), + SIMD4(-61.0121, 10.1343, -61.9061, 10.0691), + SIMD4(-61.9061, 10.0691, -61.5918, 10.7479), + SIMD4(-61.5918, 10.7479, -60.9176, 10.8402), + SIMD4(-60.9176, 10.8402, -61.0121, 10.1343), + SIMD4(-78.4216, 8.061, -77.7605, 8.1333), + SIMD4(-77.7605, 8.1333, -79.0864, 8.9972), + SIMD4(-79.0864, 8.9972, -80.459, 8.2139), + SIMD4(-82.8793, 8.0707, -82.844, 9.5708), + SIMD4(-82.844, 9.5708, -81.3548, 8.7806), + SIMD4(-81.3548, 8.7806, -79.1123, 9.5368), + SIMD4(-79.1123, 9.5368, -77.3742, 8.6583), + SIMD4(-83.1575, 14.9931, -83.6589, 10.8369), + SIMD4(-83.6589, 10.8369, -85.9611, 11.3313), + SIMD4(-85.9611, 11.3313, -87.6702, 12.9657), + SIMD4(-87.6702, 12.9657, -87.0093, 13.0078), + SIMD4(-87.0093, 13.0078, -86.759, 13.7461), + SIMD4(-86.759, 13.7461, -85.7339, 13.8587), + SIMD4(-85.7339, 13.8587, -84.8604, 14.8098), + SIMD4(-84.8604, 14.8098, -83.1575, 14.9931), + SIMD4(-117.1283, 32.5333, -114.7248, 32.7153), + SIMD4(-114.7248, 32.7153, -111.042, 31.3242), + SIMD4(-111.042, 31.3242, -106.4532, 31.7702), + SIMD4(-106.4532, 31.7702, -104.9179, 30.5833), + SIMD4(-104.9179, 30.5833, -104.4006, 29.5737), + SIMD4(-104.4006, 29.5737, -103.2577, 29.0011), + SIMD4(-103.2577, 29.0011, -102.3431, 29.865), + SIMD4(-102.3431, 29.865, -101.3804, 29.7426), + SIMD4(-101.3804, 29.7426, -99.1078, 26.4469), + SIMD4(-99.1078, 26.4469, -97.1462, 25.9615), + SIMD4(-97.1462, 25.9615, -97.8578, 22.6245), + SIMD4(-97.8578, 22.6245, -97.4092, 21.2726), + SIMD4(-97.4092, 21.2726, -97.7538, 22.0267), + SIMD4(-97.7538, 22.0267, -97.6375, 21.6037), + SIMD4(-97.6375, 21.6037, -95.9204, 18.8196), + SIMD4(-95.9204, 18.8196, -94.5462, 18.1749), + SIMD4(-94.5462, 18.1749, -91.2752, 18.6245), + SIMD4(-91.2752, 18.6245, -89.8876, 21.2526), + SIMD4(-89.8876, 21.2526, -86.8241, 21.4217), + SIMD4(-86.8241, 21.4217, -87.8532, 18.269), + SIMD4(-87.8532, 18.269, -88.0738, 18.8345), + SIMD4(-88.0738, 18.8345, -89.1615, 17.8148), + SIMD4(-89.1615, 17.8148, -90.9892, 17.8164), + SIMD4(-90.9892, 17.8164, -90.993, 17.2524), + SIMD4(-90.993, 17.2524, -91.4096, 17.2559), + SIMD4(-91.4096, 17.2559, -90.4472, 16.0727), + SIMD4(-90.4472, 16.0727, -91.7366, 16.0702), + SIMD4(-91.7366, 16.0702, -92.2352, 14.5454), + SIMD4(-92.2352, 14.5454, -94.7528, 16.2912), + SIMD4(-94.7528, 16.2912, -96.5108, 15.6519), + SIMD4(-96.5108, 15.6519, -97.7548, 15.9668), + SIMD4(-97.7548, 15.9668, -104.9385, 19.3094), + SIMD4(-104.9385, 19.3094, -105.6694, 20.3856), + SIMD4(-105.6694, 20.3856, -105.2602, 20.5791), + SIMD4(-105.2602, 20.5791, -105.2087, 21.4908), + SIMD4(-105.2087, 21.4908, -105.7918, 22.6275), + SIMD4(-105.7918, 22.6275, -108.0515, 25.067), + SIMD4(-108.0515, 25.067, -109.385, 25.7271), + SIMD4(-109.385, 25.7271, -109.2763, 26.5339), + SIMD4(-109.2763, 26.5339, -112.1618, 29.0189), + SIMD4(-112.1618, 29.0189, -113.0467, 31.1792), + SIMD4(-113.0467, 31.1792, -114.9336, 31.9007), + SIMD4(-114.9336, 31.9007, -114.5505, 30.0223), + SIMD4(-114.5505, 30.0223, -111.5697, 26.7076), + SIMD4(-111.5697, 26.7076, -110.6593, 24.3415), + SIMD4(-110.6593, 24.3415, -109.4209, 23.4801), + SIMD4(-109.4209, 23.4801, -110.0062, 22.894), + SIMD4(-110.0062, 22.894, -112.0726, 24.84), + SIMD4(-112.0726, 24.84, -112.3772, 26.2139), + SIMD4(-112.3772, 26.2139, -114.9935, 27.736), + SIMD4(-114.9935, 27.736, -114.0693, 27.6757), + SIMD4(-114.0693, 27.6757, -114.0485, 28.4262), + SIMD4(-114.0485, 28.4262, -115.6738, 29.7564), + SIMD4(-115.6738, 29.7564, -117.1283, 32.5333), + SIMD4(-77.2615, 18.4574, -76.2108, 17.9135), + SIMD4(-76.2108, 17.9135, -77.1584, 17.8451), + SIMD4(-77.1584, 17.8451, -78.3395, 18.2872), + SIMD4(-78.3395, 18.2872, -77.2615, 18.4574), + SIMD4(-83.1575, 14.9931, -84.9852, 14.7524), + SIMD4(-84.9852, 14.7524, -85.7339, 13.8587), + SIMD4(-85.7339, 13.8587, -86.759, 13.7461), + SIMD4(-86.759, 13.7461, -87.0592, 12.9915), + SIMD4(-87.0592, 12.9915, -88.151, 13.9874), + SIMD4(-88.151, 13.9874, -89.3626, 14.416), + SIMD4(-89.3626, 14.416, -89.1426, 15.0723), + SIMD4(-89.1426, 15.0723, -87.875, 15.8793), + SIMD4(-87.875, 15.8793, -84.9737, 15.9899), + SIMD4(-84.9737, 15.9899, -83.1575, 14.9931), + SIMD4(-71.7792, 19.7182, -71.7683, 18.0392), + SIMD4(-71.7683, 18.0392, -74.0854, 18.2151), + SIMD4(-74.0854, 18.2151, -74.3875, 18.6247), + SIMD4(-74.3875, 18.6247, -72.3467, 18.6237), + SIMD4(-72.3467, 18.6237, -73.4005, 19.8074), + SIMD4(-73.4005, 19.8074, -71.7792, 19.7182), + SIMD4(-92.2352, 14.5454, -91.7366, 16.0702), + SIMD4(-91.7366, 16.0702, -90.4472, 16.0727), + SIMD4(-90.4472, 16.0727, -91.4096, 17.2559), + SIMD4(-91.4096, 17.2559, -90.993, 17.2524), + SIMD4(-90.993, 17.2524, -90.9892, 17.8164), + SIMD4(-90.9892, 17.8164, -89.1615, 17.8148), + SIMD4(-89.1615, 17.8148, -89.2375, 15.8944), + SIMD4(-89.2375, 15.8944, -88.2283, 15.729), + SIMD4(-88.2283, 15.729, -90.0952, 13.7365), + SIMD4(-90.0952, 13.7365, -92.2352, 14.5454), + SIMD4(-89.3626, 14.416, -87.7314, 13.8411), + SIMD4(-87.7314, 13.8411, -87.8781, 13.2244), + SIMD4(-87.8781, 13.2244, -90.0952, 13.7365), + SIMD4(-90.0952, 13.7365, -89.3626, 14.416), + SIMD4(-71.7683, 18.0392, -71.616, 19.8774), + SIMD4(-71.616, 19.8774, -69.2325, 19.2718), + SIMD4(-69.2325, 19.2718, -69.6232, 19.1605), + SIMD4(-69.6232, 19.1605, -68.3593, 18.5381), + SIMD4(-68.3593, 18.5381, -71.0278, 18.2732), + SIMD4(-71.0278, 18.2732, -71.439, 17.6356), + SIMD4(-71.439, 17.6356, -71.7683, 18.0392), + SIMD4(-50.3192, 62.4732, -49.7931, 63.0446), + SIMD4(-49.7931, 63.0446, -50.3901, 62.822), + SIMD4(-50.3901, 62.822, -51.5382, 63.758), + SIMD4(-51.5382, 63.758, -50.2607, 64.2143), + SIMD4(-50.2607, 64.2143, -51.682, 64.1647), + SIMD4(-51.682, 64.1647, -51.4038, 64.4632), + SIMD4(-51.4038, 64.4632, -50.1216, 64.7038), + SIMD4(-50.1216, 64.7038, -50.9606, 65.2011), + SIMD4(-50.9606, 65.2011, -50.7802, 64.7461), + SIMD4(-50.7802, 64.7461, -52.0632, 64.3461), + SIMD4(-52.0632, 64.3461, -52.5377, 65.3288), + SIMD4(-52.5377, 65.3288, -51.0919, 65.7758), + SIMD4(-51.0919, 65.7758, -53.199, 65.594), + SIMD4(-53.199, 65.594, -53.3569, 66.0733), + SIMD4(-53.3569, 66.0733, -51.225, 66.8815), + SIMD4(-51.225, 66.8815, -53.6147, 66.1545), + SIMD4(-53.6147, 66.1545, -53.4188, 66.6485), + SIMD4(-53.4188, 66.6485, -52.3869, 66.8812), + SIMD4(-52.3869, 66.8812, -53.6872, 66.9865), + SIMD4(-53.6872, 66.9865, -53.7986, 67.4182), + SIMD4(-53.7986, 67.4182, -50.6135, 67.5279), + SIMD4(-50.6135, 67.5279, -53.7352, 67.549), + SIMD4(-53.7352, 67.549, -53.1516, 68.2078), + SIMD4(-53.1516, 68.2078, -51.1691, 68.3852), + SIMD4(-51.1691, 68.3852, -53.3832, 68.2974), + SIMD4(-53.3832, 68.2974, -53.0395, 68.6109), + SIMD4(-53.0395, 68.6109, -51.1333, 68.5984), + SIMD4(-51.1333, 68.5984, -50.8006, 68.7913), + SIMD4(-50.8006, 68.7913, -51.2494, 68.7399), + SIMD4(-51.2494, 68.7399, -51.0849, 69.1283), + SIMD4(-51.0849, 69.1283, -50.2974, 69.1706), + SIMD4(-50.2974, 69.1706, -51.077, 69.2095), + SIMD4(-51.077, 69.2095, -50.3229, 70.0271), + SIMD4(-50.3229, 70.0271, -54.5308, 70.6993), + SIMD4(-54.5308, 70.6993, -50.6821, 70.3969), + SIMD4(-50.6821, 70.3969, -51.7743, 71.0104), + SIMD4(-51.7743, 71.0104, -51.0189, 71.0013), + SIMD4(-51.0189, 71.0013, -53.117, 71.3129), + SIMD4(-53.117, 71.3129, -51.7786, 71.6829), + SIMD4(-51.7786, 71.6829, -53.4401, 71.579), + SIMD4(-53.4401, 71.579, -53.1445, 71.8074), + SIMD4(-53.1445, 71.8074, -53.6521, 72.3626), + SIMD4(-53.6521, 72.3626, -53.4625, 71.8936), + SIMD4(-53.4625, 71.8936, -53.963, 71.459), + SIMD4(-53.963, 71.459, -55.594, 71.5535), + SIMD4(-55.594, 71.5535, -54.8401, 72.3561), + SIMD4(-54.8401, 72.3561, -55.6017, 72.4535), + SIMD4(-55.6017, 72.4535, -54.7379, 72.8725), + SIMD4(-54.7379, 72.8725, -55.6686, 73.0079), + SIMD4(-55.6686, 73.0079, -55.2883, 73.3271), + SIMD4(-55.2883, 73.3271, -56.1041, 73.5582), + SIMD4(-56.1041, 73.5582, -55.8383, 73.7597), + SIMD4(-55.8383, 73.7597, -56.2254, 74.1291), + SIMD4(-56.2254, 74.1291, -57.2306, 74.1253), + SIMD4(-57.2306, 74.1253, -56.2555, 74.5268), + SIMD4(-56.2555, 74.5268, -58.5655, 75.3527), + SIMD4(-58.5655, 75.3527, -58.5162, 75.6891), + SIMD4(-58.5162, 75.6891, -63.2913, 76.3521), + SIMD4(-63.2913, 76.3521, -68.3173, 76.0908), + SIMD4(-68.3173, 76.0908, -69.4841, 76.3992), + SIMD4(-69.4841, 76.3992, -68.1143, 76.6506), + SIMD4(-68.1143, 76.6506, -71.1549, 77.0739), + SIMD4(-71.1549, 77.0739, -66.2665, 77.5154), + SIMD4(-66.2665, 77.5154, -69.9768, 77.5477), + SIMD4(-69.9768, 77.5477, -72.7148, 78.3623), + SIMD4(-72.7148, 78.3623, -65.9679, 79.1324), + SIMD4(-65.9679, 79.1324, -64.1792, 80.0993), + SIMD4(-64.1792, 80.0993, -67.1932, 80.2801), + SIMD4(-67.1932, 80.2801, -64.5155, 81), + SIMD4(-64.5155, 81, -61.436, 81.1336), + SIMD4(-61.436, 81.1336, -61.2029, 81.7469), + SIMD4(-61.2029, 81.7469, -60.4324, 81.9202), +SIMD4(-60.4324, 81.9202, -56.6151, 81.3629), + SIMD4(-56.6151, 81.3629, -59.268, 81.9821), + SIMD4(-59.268, 81.9821, -54.5489, 82.3506), + SIMD4(-54.5489, 82.3506, -53.6713, 82.1641), + SIMD4(-53.6713, 82.1641, -53.5557, 81.6533), + SIMD4(-53.5557, 81.6533, -53.0226, 82.3217), + SIMD4(-53.0226, 82.3217, -49.5411, 81.9181), + SIMD4(-49.5411, 81.9181, -50.9899, 82.4602), + SIMD4(-50.9899, 82.4602, -50.0371, 82.4724), + SIMD4(-52.7312, 69.9447, -51.9002, 69.6048), + SIMD4(-51.9002, 69.6048, -54.1827, 69.4035), + SIMD4(-54.1827, 69.4035, -53.825, 69.5403), + SIMD4(-53.825, 69.5403, -54.8658, 69.665), + SIMD4(-54.8658, 69.665, -54.3226, 69.9419), + SIMD4(-54.3226, 69.9419, -54.8156, 70.1894), + SIMD4(-54.8156, 70.1894, -52.7312, 69.9447), + SIMD4(-81.8375, 23.163, -79.8203, 22.887), + SIMD4(-79.8203, 22.887, -74.1368, 20.2319), + SIMD4(-74.1368, 20.2319, -76.8902, 19.9213), + SIMD4(-76.8902, 19.9213, -77.7151, 19.8555), + SIMD4(-77.7151, 19.8555, -77.1079, 20.4916), + SIMD4(-77.1079, 20.4916, -78.1164, 20.7619), + SIMD4(-78.1164, 20.7619, -78.7277, 21.5927), + SIMD4(-78.7277, 21.5927, -81.8162, 22.2002), + SIMD4(-81.8162, 22.2002, -81.8388, 22.6725), + SIMD4(-81.8388, 22.6725, -84.8872, 21.857), + SIMD4(-84.8872, 21.857, -84.0449, 22.666), + SIMD4(-84.0449, 22.666, -81.8375, 23.163), + SIMD4(-82.5636, 9.5767, -82.9398, 9.4492), + SIMD4(-82.9398, 9.4492, -82.8793, 8.0707), + SIMD4(-82.8793, 8.0707, -85.2356, 10.2421), + SIMD4(-85.2356, 10.2421, -85.1145, 9.5818), + SIMD4(-85.1145, 9.5818, -85.8497, 10.292), + SIMD4(-85.8497, 10.292, -85.6214, 11.1845), + SIMD4(-85.6214, 11.1845, -83.642, 10.9172), + SIMD4(-83.642, 10.9172, -82.5636, 9.5767), + SIMD4(-132.6555, 54.1275, -132.1661, 53.9552), + SIMD4(-132.1661, 53.9552, -132.5347, 53.6517), + SIMD4(-132.5347, 53.6517, -131.6676, 54.1414), + SIMD4(-131.6676, 54.1414, -131.8892, 53.714), + SIMD4(-131.8892, 53.714, -132.0113, 53.2652), + SIMD4(-132.0113, 53.2652, -132.6748, 53.2632), + SIMD4(-132.6748, 53.2632, -133.0979, 54.0056), + SIMD4(-133.0979, 54.0056, -132.6555, 54.1275), + SIMD4(-131.7537, 53.1956, -131.9718, 52.8798), + SIMD4(-131.9718, 52.8798, -131.1162, 52.2191), + SIMD4(-131.1162, 52.2191, -132.5468, 53.1375), + SIMD4(-132.5468, 53.1375, -131.7537, 53.1956), + SIMD4(-127.1973, 50.6404, -125.4821, 50.3168), + SIMD4(-125.4821, 50.3168, -123.2838, 48.4552), + SIMD4(-123.2838, 48.4552, -124.8683, 48.6536), + SIMD4(-124.8683, 48.6536, -124.8126, 49.2126), + SIMD4(-124.8126, 49.2126, -125.4895, 48.9338), + SIMD4(-125.4895, 48.9338, -126.1688, 49.4152), + SIMD4(-126.1688, 49.4152, -127.8639, 50.1277), + SIMD4(-127.8639, 50.1277, -127.4659, 50.5831), + SIMD4(-127.4659, 50.5831, -128.3499, 50.6966), + SIMD4(-128.3499, 50.6966, -127.1973, 50.6404), + SIMD4(-130.0251, 55.8882, -131.8243, 56.59), + SIMD4(-131.8243, 56.59, -133.4011, 58.4109), + SIMD4(-133.4011, 58.4109, -135.4759, 59.7933), + SIMD4(-135.4759, 59.7933, -137.4386, 58.9031), + SIMD4(-137.4386, 58.9031, -139.0792, 60.3437), + SIMD4(-139.0792, 60.3437, -141.0021, 60.3002), + SIMD4(-141.0021, 60.3002, -141.0021, 69.6508), + SIMD4(-141.0021, 69.6508, -135.2588, 68.6843), + SIMD4(-135.2588, 68.6843, -135.9102, 69.1115), + SIMD4(-135.9102, 69.1115, -134.4089, 69.6818), + SIMD4(-134.4089, 69.6818, -133.8798, 69.5077), + SIMD4(-133.8798, 69.5077, -134.1743, 69.2528), + SIMD4(-134.1743, 69.2528, -129.5384, 70.1052), + SIMD4(-129.5384, 70.1052, -132.6867, 69.2599), + SIMD4(-132.6867, 69.2599, -133.1968, 68.7398), + SIMD4(-133.1968, 68.7398, -131.7884, 69.432), + SIMD4(-131.7884, 69.432, -130.9707, 69.2091), + SIMD4(-130.9707, 69.2091, -128.853, 69.751), + SIMD4(-128.853, 69.751, -127.6838, 70.2604), + SIMD4(-127.6838, 70.2604, -127.991, 70.5738), + SIMD4(-127.991, 70.5738, -125.7278, 69.38), + SIMD4(-125.7278, 69.38, -124.555, 70.1512), + SIMD4(-124.555, 70.1512, -124.3381, 69.3648), + SIMD4(-124.3381, 69.3648, -121.7418, 69.7975), + SIMD4(-121.7418, 69.7975, -113.9644, 68.3991), + SIMD4(-113.9644, 68.3991, -115.4345, 67.9023), + SIMD4(-115.4345, 67.9023, -115.1332, 67.8192), + SIMD4(-115.1332, 67.8192, -110.0739, 67.9929), + SIMD4(-110.0739, 67.9929, -107.9887, 67.2564), + SIMD4(-107.9887, 67.2564, -108.496, 67.0923), + SIMD4(-108.496, 67.0923, -107.2595, 66.3985), + SIMD4(-107.2595, 66.3985, -107.746, 66.9615), + SIMD4(-107.746, 66.9615, -107.1565, 66.8817), + SIMD4(-107.1565, 66.8817, -107.9584, 67.8186), + SIMD4(-107.9584, 67.8186, -105.7502, 68.5923), + SIMD4(-105.7502, 68.5923, -108.7181, 68.2975), + SIMD4(-108.7181, 68.2975, -106.1645, 68.9199), + SIMD4(-106.1645, 68.9199, -104.4868, 68.0632), + SIMD4(-104.4868, 68.0632, -102.3204, 67.7356), + SIMD4(-102.3204, 67.7356, -98.4121, 67.8072), + SIMD4(-98.4121, 67.8072, -98.6315, 68.0726), + SIMD4(-98.6315, 68.0726, -97.4549, 67.617), + SIMD4(-97.4549, 67.617, -97.1398, 67.7962), + SIMD4(-97.1398, 67.7962, -98.6505, 68.3635), + SIMD4(-98.6505, 68.3635, -95.9703, 68.2491), + SIMD4(-95.9703, 68.2491, -96.3691, 67.5098), + SIMD4(-96.3691, 67.5098, -95.4189, 67.0132), + SIMD4(-95.4189, 67.0132, -96.4226, 67.0518), + SIMD4(-96.4226, 67.0518, -95.7875, 66.6168), + SIMD4(-95.7875, 66.6168, -96.0369, 66.9375), + SIMD4(-96.0369, 66.9375, -95.2587, 67.2625), + SIMD4(-95.2587, 67.2625, -95.4607, 68.0214), + SIMD4(-95.4607, 68.0214, -93.4489, 68.6189), + SIMD4(-93.4489, 68.6189, -93.8524, 69.0003), + SIMD4(-93.8524, 69.0003, -94.6004, 68.8032), + SIMD4(-94.6004, 68.8032, -93.5323, 69.4809), + SIMD4(-93.5323, 69.4809, -96.5514, 70.2103), + SIMD4(-96.5514, 70.2103, -95.8786, 70.549), + SIMD4(-95.8786, 70.549, -96.5489, 70.8087), + SIMD4(-96.5489, 70.8087, -96.4466, 71.2399), + SIMD4(-96.4466, 71.2399, -94.7349, 71.983), + SIMD4(-94.7349, 71.983, -91.5641, 70.1783), + SIMD4(-91.5641, 70.1783, -92.3205, 70.2354), + SIMD4(-92.3205, 70.2354, -91.9767, 70.0387), + SIMD4(-91.9767, 70.0387, -92.8878, 69.6682), + SIMD4(-92.8878, 69.6682, -90.4156, 69.457), + SIMD4(-90.4156, 69.457, -91.2372, 69.2855), + SIMD4(-91.2372, 69.2855, -90.2478, 68.2674), + SIMD4(-90.2478, 68.2674, -89.2795, 69.2555), + SIMD4(-89.2795, 69.2555, -88.0414, 68.8117), + SIMD4(-88.0414, 68.8117, -87.8279, 68.3), + SIMD4(-87.8279, 68.3, -88.3138, 67.9503), + SIMD4(-88.3138, 67.9503, -87.3594, 67.1772), + SIMD4(-87.3594, 67.1772, -86.5608, 67.4821), + SIMD4(-86.5608, 67.4821, -85.6898, 68.6709), + SIMD4(-85.6898, 68.6709, -84.8676, 68.7733), + SIMD4(-84.8676, 68.7733, -85.5074, 69.8453), + SIMD4(-85.5074, 69.8453, -82.6184, 69.6911), + SIMD4(-82.6184, 69.6911, -81.3778, 69.1856), + SIMD4(-81.3778, 69.1856, -81.9579, 68.8836), + SIMD4(-81.9579, 68.8836, -81.2815, 68.6572), + SIMD4(-81.2815, 68.6572, -82.5527, 68.4465), + SIMD4(-82.5527, 68.4465, -81.3011, 67.357), + SIMD4(-81.3011, 67.357, -82.6415, 66.5875), + SIMD4(-82.6415, 66.5875, -83.5231, 66.3688), + SIMD4(-83.5231, 66.3688, -84.8458, 67.0287), + SIMD4(-84.8458, 67.0287, -83.7976, 66.2385), + SIMD4(-83.7976, 66.2385, -86.7082, 66.523), + SIMD4(-86.7082, 66.523, -85.9587, 66.119), + SIMD4(-85.9587, 66.119, -87.4529, 65.339), + SIMD4(-87.4529, 65.339, -91.4272, 65.9479), + SIMD4(-91.4272, 65.9479, -87.0275, 65.1981), + SIMD4(-87.0275, 65.1981, -88.1056, 64.1833), + SIMD4(-88.1056, 64.1833, -90.0417, 64.1409), + SIMD4(-90.0417, 64.1409, -90.8119, 63.5809), + SIMD4(-90.8119, 63.5809, -93.6963, 64.1472), + SIMD4(-93.6963, 64.1472, -90.6986, 63.0639), + SIMD4(-90.6986, 63.0639, -92.3613, 62.8194), + SIMD4(-92.3613, 62.8194, -91.9358, 62.5924), + SIMD4(-91.9358, 62.5924, -92.5514, 62.5467), + SIMD4(-92.5514, 62.5467, -92.528, 62.1684), + SIMD4(-92.528, 62.1684, -93.2054, 62.3649), + SIMD4(-93.2054, 62.3649, -92.9055, 62.2151), + SIMD4(-92.9055, 62.2151, -94.7617, 60.4982), + SIMD4(-94.7617, 60.4982, -94.9573, 59.0688), + SIMD4(-94.9573, 59.0688, -94.3322, 58.2974), + SIMD4(-94.3322, 58.2974, -94.1232, 58.7367), + SIMD4(-94.1232, 58.7367, -93.1788, 58.7256), + SIMD4(-93.1788, 58.7256, -92.4328, 57.3203), + SIMD4(-92.4328, 57.3203, -92.7981, 56.922), + SIMD4(-92.7981, 56.922, -90.5922, 57.2245), + SIMD4(-90.5922, 57.2245, -85.6767, 55.6011), + SIMD4(-85.6767, 55.6011, -85.3653, 55.0793), + SIMD4(-85.3653, 55.0793, -82.3933, 55.0678), + SIMD4(-82.3933, 55.0678, -81.8279, 52.2242), + SIMD4(-81.8279, 52.2242, -80.658, 51.7584), + SIMD4(-80.658, 51.7584, -80.4433, 51.3886), + SIMD4(-80.4433, 51.3886, -80.8512, 51.125), + SIMD4(-80.8512, 51.125, -80.1036, 51.2829), + SIMD4(-80.1036, 51.2829, -79.3479, 50.7626), + SIMD4(-79.3479, 50.7626, -79.6888, 51.3466), + SIMD4(-79.6888, 51.3466, -79.297, 51.6228), + SIMD4(-79.297, 51.6228, -78.9032, 51.2003), + SIMD4(-78.9032, 51.2003, -78.4481, 52.2614), + SIMD4(-78.4481, 52.2614, -78.996, 54.0025), + SIMD4(-78.996, 54.0025, -79.7124, 54.6718), + SIMD4(-79.7124, 54.6718, -77.7753, 55.2913), + SIMD4(-77.7753, 55.2913, -76.5298, 56.5), + SIMD4(-76.5298, 56.5, -76.8909, 57.7581), + SIMD4(-76.8909, 57.7581, -78.5059, 58.6491), + SIMD4(-78.5059, 58.6491, -77.2892, 60.022), + SIMD4(-77.2892, 60.022, -77.603, 60.8252), + SIMD4(-77.603, 60.8252, -78.1813, 60.8191), + SIMD4(-78.1813, 60.8191, -77.5144, 61.5563), + SIMD4(-77.5144, 61.5563, -78.1334, 62.2823), + SIMD4(-78.1334, 62.2823, -77.3724, 62.5725), + SIMD4(-77.3724, 62.5725, -74.6326, 62.1157), + SIMD4(-74.6326, 62.1157, -73.7051, 62.4731), + SIMD4(-73.7051, 62.4731, -71.4227, 61.1589), + SIMD4(-71.4227, 61.1589, -69.4719, 61.0109), + SIMD4(-69.4719, 61.0109, -69.6737, 60.0759), + SIMD4(-69.6737, 60.0759, -70.6548, 60.0262), + SIMD4(-70.6548, 60.0262, -69.7339, 59.918), + SIMD4(-69.7339, 59.918, -69.344, 59.3031), + SIMD4(-69.344, 59.3031, -70.1543, 58.7606), + SIMD4(-70.1543, 58.7606, -68.3812, 58.7435), + SIMD4(-68.3812, 58.7435, -68.3565, 58.1632), + SIMD4(-68.3565, 58.1632, -69.0408, 57.9025), + SIMD4(-69.0408, 57.9025, -68.021, 58.4853), + SIMD4(-68.021, 58.4853, -67.6783, 57.9911), + SIMD4(-67.6783, 57.9911, -66.3624, 58.7912), + SIMD4(-66.3624, 58.7912, -66.0024, 58.4312), + SIMD4(-66.0024, 58.4312, -65.4751, 59.4703), + SIMD4(-65.4751, 59.4703, -65.0382, 59.3879), + SIMD4(-65.0382, 59.3879, -65.4334, 59.7765), + SIMD4(-65.4334, 59.7765, -64.4994, 60.2683), + SIMD4(-64.4994, 60.2683, -64.7685, 60.0121), + SIMD4(-64.7685, 60.0121, -63.4151, 59.1944), + SIMD4(-63.4151, 59.1944, -63.9711, 59.0538), + SIMD4(-63.9711, 59.0538, -62.8739, 58.6725), + SIMD4(-62.8739, 58.6725, -63.5371, 58.3299), + SIMD4(-63.5371, 58.3299, -62.5938, 58.474), + SIMD4(-62.5938, 58.474, -63.2615, 58.0147), + SIMD4(-63.2615, 58.0147, -61.9586, 57.9118), + SIMD4(-61.9586, 57.9118, -62.4956, 57.4892), + SIMD4(-62.4956, 57.4892, -61.3337, 57.0106), + SIMD4(-61.3337, 57.0106, -61.3716, 56.6808), + SIMD4(-61.3716, 56.6808, -62.4973, 56.8017), + SIMD4(-62.4973, 56.8017, -60.341, 55.7847), + SIMD4(-60.341, 55.7847, -60.6171, 55.0602), + SIMD4(-60.6171, 55.0602, -59.7588, 55.3096), + SIMD4(-59.7588, 55.3096, -59.4379, 55.1759), + SIMD4(-59.4379, 55.1759, -59.8378, 54.814), + SIMD4(-59.8378, 54.814, -59.2596, 55.2), + SIMD4(-59.2596, 55.2, -57.4045, 54.5909), + SIMD4(-57.4045, 54.5909, -60.3954, 53.6533), + SIMD4(-60.3954, 53.6533, -60.3295, 53.2661), + SIMD4(-60.3295, 53.2661, -57.9283, 54.1036), + SIMD4(-57.9283, 54.1036, -58.31, 54.2017), + SIMD4(-58.31, 54.2017, -57.4161, 54.1627), + SIMD4(-57.4161, 54.1627, -57.3317, 53.4691), + SIMD4(-57.3317, 53.4691, -55.9661, 53.4711), + SIMD4(-55.9661, 53.4711, -55.8028, 52.6432), + SIMD4(-55.8028, 52.6432, -56.3249, 52.5445), + SIMD4(-56.3249, 52.5445, -55.6728, 52.1901), + SIMD4(-55.6728, 52.1901, -56.976, 51.4577), + SIMD4(-56.976, 51.4577, -58.5104, 51.2951), + SIMD4(-58.5104, 51.2951, -60.0802, 50.2546), + SIMD4(-60.0802, 50.2546, -66.4955, 50.2119), + SIMD4(-66.4955, 50.2119, -69.6739, 48.1992), + SIMD4(-69.6739, 48.1992, -71.0183, 48.4556), + SIMD4(-71.0183, 48.4556, -69.775, 48.0981), +SIMD4(-69.775, 48.0981, -71.2678, 46.7959), + SIMD4(-71.2678, 46.7959, -74.3151, 45.5311), + SIMD4(-74.3151, 45.5311, -73.9738, 45.3451), + SIMD4(-73.9738, 45.3451, -76.82, 43.6288), + SIMD4(-76.82, 43.6288, -78.8456, 43.5834), + SIMD4(-78.8456, 43.5834, -79.0367, 42.8023), + SIMD4(-79.0367, 42.8023, -82.69, 41.6752), + SIMD4(-82.69, 41.6752, -83.1497, 42.1419), + SIMD4(-83.1497, 42.1419, -82.1378, 43.5709), + SIMD4(-82.1378, 43.5709, -82.5511, 45.3474), + SIMD4(-82.5511, 45.3474, -84.1495, 46.5428), + SIMD4(-84.1495, 46.5428, -88.3782, 48.3031), + SIMD4(-88.3782, 48.3031, -91.5183, 48.0583), + SIMD4(-91.5183, 48.0583, -94.6209, 48.7426), + SIMD4(-94.6209, 48.7426, -95.1553, 49.3697), + SIMD4(-95.1553, 49.3697, -95.1621, 48.9917), + SIMD4(-95.1621, 48.9917, -123.0773, 48.9802), + SIMD4(-123.0773, 48.9802, -123.1875, 49.6803), + SIMD4(-123.1875, 49.6803, -124.0286, 49.6029), + SIMD4(-124.0286, 49.6029, -123.5825, 49.6812), + SIMD4(-123.5825, 49.6812, -123.8254, 50.1442), + SIMD4(-123.8254, 50.1442, -124.2813, 49.7721), + SIMD4(-124.2813, 49.7721, -124.7824, 50.0201), + SIMD4(-124.7824, 50.0201, -124.8599, 50.8724), + SIMD4(-124.8599, 50.8724, -126.0943, 50.4976), + SIMD4(-126.0943, 50.4976, -126.5173, 51.0568), + SIMD4(-126.5173, 51.0568, -127.7081, 51.1512), + SIMD4(-127.7081, 51.1512, -126.6915, 51.7034), + SIMD4(-126.6915, 51.7034, -127.7141, 51.4902), + SIMD4(-127.7141, 51.4902, -127.7954, 52.191), + SIMD4(-127.7954, 52.191, -126.714, 52.0607), + SIMD4(-126.714, 52.0607, -127.194, 52.4577), + SIMD4(-127.194, 52.4577, -127.0193, 52.8425), + SIMD4(-127.0193, 52.8425, -128.1022, 51.7884), + SIMD4(-128.1022, 51.7884, -128.0533, 52.9107), + SIMD4(-128.0533, 52.9107, -129.1716, 53.5336), + SIMD4(-129.1716, 53.5336, -127.9278, 53.2747), + SIMD4(-127.9278, 53.2747, -128.6755, 53.5546), + SIMD4(-128.6755, 53.5546, -128.5321, 53.8581), + SIMD4(-128.5321, 53.8581, -129.5637, 53.2515), + SIMD4(-129.5637, 53.2515, -130.3353, 53.7239), + SIMD4(-130.3353, 53.7239, -129.626, 54.2303), + SIMD4(-129.626, 54.2303, -130.4303, 54.421), + SIMD4(-130.4303, 54.421, -129.5606, 55.4625), + SIMD4(-129.5606, 55.4625, -130.0485, 55.0573), + SIMD4(-130.0485, 55.0573, -130.0251, 55.8882), + SIMD4(-109.816, 78.6504, -109.3521, 78.3687), + SIMD4(-109.3521, 78.3687, -111.5175, 78.2747), + SIMD4(-111.5175, 78.2747, -113.2926, 78.3344), + SIMD4(-113.2926, 78.3344, -109.816, 78.6504), + SIMD4(-110.4581, 78.1032, -109.619, 78.0568), + SIMD4(-109.619, 78.0568, -110.8656, 77.8341), + SIMD4(-110.8656, 77.8341, -110.1985, 77.5245), + SIMD4(-110.1985, 77.5245, -112.1765, 77.3438), + SIMD4(-112.1765, 77.3438, -113.283, 77.8356), + SIMD4(-113.283, 77.8356, -110.4581, 78.1032), + SIMD4(-115.5513, 77.3633, -116.3292, 77.1371), + SIMD4(-116.3292, 77.1371, -115.8101, 76.9391), + SIMD4(-115.8101, 76.9391, -116.0762, 76.6535), + SIMD4(-116.0762, 76.6535, -117.4924, 76.2727), + SIMD4(-117.4924, 76.2727, -118.2028, 76.7605), + SIMD4(-118.2028, 76.7605, -118.9939, 76.1449), + SIMD4(-118.9939, 76.1449, -119.5804, 76.3265), + SIMD4(-119.5804, 76.3265, -119.5377, 75.9822), + SIMD4(-119.5377, 75.9822, -122.9028, 76.1347), + SIMD4(-122.9028, 76.1347, -119.0902, 77.3051), + SIMD4(-119.0902, 77.3051, -115.5513, 77.3633), + SIMD4(-108.2924, 76.0571, -105.4814, 75.7022), + SIMD4(-105.4814, 75.7022, -106.0926, 75.0895), + SIMD4(-106.0926, 75.0895, -112.5193, 74.4168), + SIMD4(-112.5193, 74.4168, -114.377, 74.6709), + SIMD4(-114.377, 74.6709, -111.0335, 75.2268), + SIMD4(-111.0335, 75.2268, -115.4781, 75.1041), + SIMD4(-115.4781, 75.1041, -117.6001, 75.2717), + SIMD4(-117.6001, 75.2717, -115.1418, 75.6785), + SIMD4(-115.1418, 75.6785, -117.1636, 75.6449), + SIMD4(-117.1636, 75.6449, -114.9915, 75.8963), + SIMD4(-114.9915, 75.8963, -116.6646, 75.9576), + SIMD4(-116.6646, 75.9576, -114.7786, 76.1726), + SIMD4(-114.7786, 76.1726, -115.8317, 76.2958), + SIMD4(-115.8317, 76.2958, -114.9985, 76.4975), + SIMD4(-114.9985, 76.4975, -109.0864, 75.5065), + SIMD4(-109.0864, 75.5065, -110.3095, 76.3974), + SIMD4(-110.3095, 76.3974, -108.8316, 76.8211), + SIMD4(-108.8316, 76.8211, -108.2924, 76.0571), + SIMD4(-114.5215, 72.5929, -113.0735, 72.9953), + SIMD4(-113.0735, 72.9953, -111.2697, 72.7137), + SIMD4(-111.2697, 72.7137, -111.6751, 72.3001), + SIMD4(-111.6751, 72.3001, -110.0084, 72.9836), + SIMD4(-110.0084, 72.9836, -107.8128, 71.6262), + SIMD4(-107.8128, 71.6262, -107.306, 71.8947), + SIMD4(-107.306, 71.8947, -108.2374, 73.1499), + SIMD4(-108.2374, 73.1499, -106.4821, 73.1962), + SIMD4(-106.4821, 73.1962, -105.4151, 72.7883), + SIMD4(-105.4151, 72.7883, -104.3859, 71.577), + SIMD4(-104.3859, 71.577, -104.5148, 71.0643), + SIMD4(-104.5148, 71.0643, -100.9091, 69.8692), + SIMD4(-100.9091, 69.8692, -103.4649, 69.6445), + SIMD4(-103.4649, 69.6445, -103.0318, 69.4335), + SIMD4(-103.0318, 69.4335, -101.7878, 69.1323), + SIMD4(-101.7878, 69.1323, -104.5714, 68.8721), + SIMD4(-104.5714, 68.8721, -106.6591, 69.4396), + SIMD4(-106.6591, 69.4396, -109.4721, 68.6767), + SIMD4(-109.4721, 68.6767, -113.1277, 68.4941), + SIMD4(-113.1277, 68.4941, -113.6941, 69.195), + SIMD4(-113.6941, 69.195, -116.5135, 69.4246), + SIMD4(-116.5135, 69.4246, -117.1954, 70.0541), + SIMD4(-117.1954, 70.0541, -111.6326, 70.3088), + SIMD4(-111.6326, 70.3088, -117.5871, 70.6295), + SIMD4(-117.5871, 70.6295, -118.3765, 70.9677), + SIMD4(-118.3765, 70.9677, -115.3034, 71.4937), + SIMD4(-115.3034, 71.4937, -118.9877, 71.7643), + SIMD4(-118.9877, 71.7643, -118.3745, 72.5339), + SIMD4(-118.3745, 72.5339, -116.5732, 73.0549), + SIMD4(-116.5732, 73.0549, -114.2064, 73.2978), + SIMD4(-114.2064, 73.2978, -114.5215, 72.5929), + SIMD4(-119.7363, 74.1126, -117.5148, 74.2317), + SIMD4(-117.5148, 74.2317, -115.3928, 73.502), + SIMD4(-115.3928, 73.502, -119.078, 72.6403), + SIMD4(-119.078, 72.6403, -120.1799, 72.2126), + SIMD4(-120.1799, 72.2126, -120.6193, 71.5058), + SIMD4(-120.6193, 71.5058, -123.0957, 71.0938), + SIMD4(-123.0957, 71.0938, -124.0078, 71.6774), + SIMD4(-124.0078, 71.6774, -125.8453, 71.9787), + SIMD4(-125.8453, 71.9787, -123.7973, 73.7682), + SIMD4(-123.7973, 73.7682, -124.6962, 74.3482), + SIMD4(-124.6962, 74.3482, -121.5041, 74.5451), + SIMD4(-121.5041, 74.5451, -119.7363, 74.1126), + SIMD4(-69.4889, 83.0168, -61.2072, 82.3411), + SIMD4(-61.2072, 82.3411, -68.6885, 81.2933), + SIMD4(-68.6885, 81.2933, -64.7801, 81.4929), + SIMD4(-64.7801, 81.4929, -72.056, 80.1232), + SIMD4(-72.056, 80.1232, -70.5591, 80.071), + SIMD4(-70.5591, 80.071, -71.3878, 79.7618), + SIMD4(-71.3878, 79.7618, -76.8988, 79.5123), + SIMD4(-76.8988, 79.5123, -74.4812, 79.2295), + SIMD4(-74.4812, 79.2295, -78.5816, 79.075), + SIMD4(-78.5816, 79.075, -74.4331, 78.7241), + SIMD4(-74.4331, 78.7241, -76.4161, 78.5115), + SIMD4(-76.4161, 78.5115, -75.1935, 78.3277), + SIMD4(-75.1935, 78.3277, -78.0126, 77.946), + SIMD4(-78.0126, 77.946, -78.4932, 77.3694), + SIMD4(-78.4932, 77.3694, -82.066, 77.2836), + SIMD4(-82.066, 77.2836, -77.9987, 76.852), + SIMD4(-77.9987, 76.852, -79.2859, 76.3548), + SIMD4(-79.2859, 76.3548, -80.9629, 76.1839), + SIMD4(-80.9629, 76.1839, -82.5298, 76.7233), + SIMD4(-82.5298, 76.7233, -82.2332, 76.4658), + SIMD4(-82.2332, 76.4658, -89.5701, 76.4919), + SIMD4(-89.5701, 76.4919, -88.5562, 77.0722), + SIMD4(-88.5562, 77.0722, -86.8123, 77.1849), + SIMD4(-86.8123, 77.1849, -88.017, 77.7847), + SIMD4(-88.017, 77.7847, -84.487, 77.368), + SIMD4(-84.487, 77.368, -82.5953, 77.9921), + SIMD4(-82.5953, 77.9921, -83.9282, 77.5183), + SIMD4(-83.9282, 77.5183, -85.292, 77.7639), + SIMD4(-85.292, 77.7639, -85.5476, 77.9277), + SIMD4(-85.5476, 77.9277, -84.2227, 78.176), + SIMD4(-84.2227, 78.176, -84.9104, 78.2397), + SIMD4(-84.9104, 78.2397, -84.7832, 78.5276), + SIMD4(-84.7832, 78.5276, -85.5859, 78.1096), + SIMD4(-85.5859, 78.1096, -87.5518, 78.1766), + SIMD4(-87.5518, 78.1766, -86.8079, 78.7744), + SIMD4(-86.8079, 78.7744, -81.7501, 78.9758), + SIMD4(-81.7501, 78.9758, -84.412, 78.9966), + SIMD4(-84.412, 78.9966, -83.5759, 79.0537), + SIMD4(-83.5759, 79.0537, -86.4208, 79.8452), + SIMD4(-86.4208, 79.8452, -86.4985, 80.2583), + SIMD4(-86.4985, 80.2583, -80.4759, 79.6063), + SIMD4(-80.4759, 79.6063, -80.1245, 79.6695), + SIMD4(-80.1245, 79.6695, -82.987, 80.3226), + SIMD4(-82.987, 80.3226, -76.863, 80.8648), + SIMD4(-76.863, 80.8648, -78.7162, 80.9517), + SIMD4(-78.7162, 80.9517, -76.8851, 81.4303), + SIMD4(-76.8851, 81.4303, -81.007, 80.6549), + SIMD4(-81.007, 80.6549, -85.1458, 80.5211), + SIMD4(-85.1458, 80.5211, -86.6154, 80.63), + SIMD4(-86.6154, 80.63, -83.2888, 81.1479), + SIMD4(-83.2888, 81.1479, -87.7117, 80.6563), + SIMD4(-87.7117, 80.6563, -89.2633, 80.9143), + SIMD4(-89.2633, 80.9143, -84.9412, 81.2862), + SIMD4(-84.9412, 81.2862, -89.623, 81.0325), + SIMD4(-89.623, 81.0325, -89.981, 81.1247), + SIMD4(-89.981, 81.1247, -87.597, 81.5258), + SIMD4(-87.597, 81.5258, -91.6841, 81.6357), + SIMD4(-91.6841, 81.6357, -85.0448, 81.9828), + SIMD4(-85.0448, 81.9828, -86.6156, 82.2186), + SIMD4(-86.6156, 82.2186, -84.8968, 82.4494), + SIMD4(-84.8968, 82.4494, -79.4249, 81.8544), + SIMD4(-79.4249, 81.8544, -82.4476, 82.395), + SIMD4(-82.4476, 82.395, -78.7488, 82.6794), + SIMD4(-78.7488, 82.6794, -79.8863, 82.9385), + SIMD4(-79.8863, 82.9385, -76.0094, 82.5352), + SIMD4(-76.0094, 82.5352, -75.5656, 82.6085), + SIMD4(-75.5656, 82.6085, -77.1249, 83.0085), + SIMD4(-77.1249, 83.0085, -69.4889, 83.0168), + SIMD4(-95.4844, 77.792, -93.1287, 77.6602), + SIMD4(-93.1287, 77.6602, -93.5439, 77.4667), + SIMD4(-93.5439, 77.4667, -96.2766, 77.6306), + SIMD4(-96.2766, 77.6306, -95.4844, 77.792), + SIMD4(-93.5426, 75.0279, -93.5731, 74.6688), + SIMD4(-93.5731, 74.6688, -94.5345, 74.6367), + SIMD4(-94.5345, 74.6367, -96.3863, 74.9995), + SIMD4(-96.3863, 74.9995, -94.8782, 75.63), + SIMD4(-94.8782, 75.63, -93.5426, 75.0279), + SIMD4(-100.0019, 73.9459, -97.1705, 73.8249), + SIMD4(-97.1705, 73.8249, -98.4218, 72.941), + SIMD4(-98.4218, 72.941, -96.4456, 72.5524), + SIMD4(-96.4456, 72.5524, -96.6134, 71.8338), + SIMD4(-96.6134, 71.8338, -98.3227, 71.8523), + SIMD4(-98.3227, 71.8523, -98.1986, 71.4409), + SIMD4(-98.1986, 71.4409, -99.2236, 71.3871), + SIMD4(-99.2236, 71.3871, -102.7087, 72.7645), + SIMD4(-102.7087, 72.7645, -100.1281, 72.9067), + SIMD4(-100.1281, 72.9067, -100.5364, 73.1979), + SIMD4(-100.5364, 73.1979, -99.8251, 73.2139), + SIMD4(-99.8251, 73.2139, -101.5232, 73.4864), + SIMD4(-101.5232, 73.4864, -100.5217, 73.4493), + SIMD4(-100.5217, 73.4493, -100.9851, 73.7653), + SIMD4(-100.9851, 73.7653, -100.0019, 73.9459), + SIMD4(-84.9196, 65.2611, -84.5011, 65.4584), + SIMD4(-84.5011, 65.4584, -82.05, 64.6443), + SIMD4(-82.05, 64.6443, -81.8871, 64.0164), + SIMD4(-81.8871, 64.0164, -80.2613, 63.802), + SIMD4(-80.2613, 63.802, -81.0464, 63.4616), + SIMD4(-81.0464, 63.4616, -83.5836, 64.0581), + SIMD4(-83.5836, 64.0581, -85.2381, 63.1393), + SIMD4(-85.2381, 63.1393, -85.7689, 63.7003), + SIMD4(-85.7689, 63.7003, -87.1771, 63.5951), + SIMD4(-87.1771, 63.5951, -86.2521, 64.1369), + SIMD4(-86.2521, 64.1369, -85.814, 65.8319), + SIMD4(-85.814, 65.8319, -84.9196, 65.2611), + SIMD4(-97.7009, 76.4665, -97.8905, 75.7604), + SIMD4(-97.8905, 75.7604, -97.336, 75.4198), + SIMD4(-97.336, 75.4198, -97.9918, 75.0458), + SIMD4(-97.9918, 75.0458, -100.7312, 75.3465), + SIMD4(-100.7312, 75.3465, -99.1946, 75.6984), + SIMD4(-99.1946, 75.6984, -102.7975, 75.5997), + SIMD4(-102.7975, 75.5997, -101.9428, 75.8838), + SIMD4(-101.9428, 75.8838, -100.9728, 75.7984), + SIMD4(-100.9728, 75.7984, -102.1377, 76.2849), + SIMD4(-102.1377, 76.2849, -101.7875, 76.4513), + SIMD4(-101.7875, 76.4513, -99.8655, 75.9242), + SIMD4(-99.8655, 75.9242, -100.1128, 76.1172), + SIMD4(-100.1128, 76.1172, -99.5411, 76.1463), + SIMD4(-99.5411, 76.1463, -100.8908, 76.4755), + SIMD4(-100.8908, 76.4755, -97.7009, 76.4665), + SIMD4(-103.426, 79.3156, -100.0147, 78.7286), + SIMD4(-100.0147, 78.7286, -98.9996, 77.9969), + SIMD4(-98.9996, 77.9969, -101.298, 78.1994), +SIMD4(-101.298, 78.1994, -104.5126, 78.2946), + SIMD4(-104.5126, 78.2946, -104.9956, 78.5185), + SIMD4(-104.9956, 78.5185, -103.3716, 78.7363), + SIMD4(-103.3716, 78.7363, -105.5802, 79.1142), + SIMD4(-105.5802, 79.1142, -103.426, 79.3156), + SIMD4(-91.8855, 81.1329, -88.8573, 80.1662), + SIMD4(-88.8573, 80.1662, -87.675, 80.3721), + SIMD4(-87.675, 80.3721, -87.9223, 80.0977), + SIMD4(-87.9223, 80.0977, -86.9772, 79.8942), + SIMD4(-86.9772, 79.8942, -87.2952, 79.5802), + SIMD4(-87.2952, 79.5802, -85.0421, 79.2846), + SIMD4(-85.0421, 79.2846, -87.6174, 78.6763), + SIMD4(-87.6174, 78.6763, -88.0402, 78.9953), + SIMD4(-88.0402, 78.9953, -87.9829, 78.5371), + SIMD4(-87.9829, 78.5371, -88.7416, 78.584), + SIMD4(-88.7416, 78.584, -88.8224, 78.1859), + SIMD4(-88.8224, 78.1859, -90.0371, 78.6068), + SIMD4(-90.0371, 78.6068, -89.4898, 78.1719), + SIMD4(-89.4898, 78.1719, -90.6144, 78.1499), + SIMD4(-90.6144, 78.1499, -94.1697, 78.9728), + SIMD4(-94.1697, 78.9728, -91.2999, 79.3727), + SIMD4(-91.2999, 79.3727, -95.1032, 79.2899), + SIMD4(-95.1032, 79.2899, -95.733, 79.4182), + SIMD4(-95.733, 79.4182, -94.4019, 79.7363), + SIMD4(-94.4019, 79.7363, -95.8575, 79.6738), + SIMD4(-95.8575, 79.6738, -96.7732, 80.1358), + SIMD4(-96.7732, 80.1358, -94.2626, 80.1949), + SIMD4(-94.2626, 80.1949, -96.3941, 80.315), + SIMD4(-96.3941, 80.315, -95.5491, 80.3666), + SIMD4(-95.5491, 80.3666, -95.927, 80.7207), + SIMD4(-95.927, 80.7207, -93.9279, 80.5592), + SIMD4(-93.9279, 80.5592, -95.2698, 81.0008), + SIMD4(-95.2698, 81.0008, -93.2356, 81.1289), + SIMD4(-93.2356, 81.1289, -94.1793, 81.3393), + SIMD4(-94.1793, 81.3393, -91.8855, 81.1329), + SIMD4(-94.295, 76.9125, -93.2119, 76.7547), + SIMD4(-93.2119, 76.7547, -93.5346, 76.4477), + SIMD4(-93.5346, 76.4477, -91.305, 76.6808), + SIMD4(-91.305, 76.6808, -89.2845, 76.3016), + SIMD4(-89.2845, 76.3016, -91.4073, 76.2201), + SIMD4(-91.4073, 76.2201, -88.9167, 75.454), + SIMD4(-88.9167, 75.454, -82.1537, 75.8311), + SIMD4(-82.1537, 75.8311, -79.6602, 75.4495), + SIMD4(-79.6602, 75.4495, -80.382, 75.0342), + SIMD4(-80.382, 75.0342, -79.4014, 74.9176), + SIMD4(-79.4014, 74.9176, -83.0576, 74.6298), + SIMD4(-83.0576, 74.6298, -91.5491, 74.6556), + SIMD4(-91.5491, 74.6556, -92.4083, 75.2973), + SIMD4(-92.4083, 75.2973, -92.1851, 75.8465), + SIMD4(-92.1851, 75.8465, -93.0917, 76.354), + SIMD4(-93.0917, 76.354, -95.2739, 76.2644), + SIMD4(-95.2739, 76.2644, -96.898, 76.754), + SIMD4(-96.898, 76.754, -94.295, 76.9125), + SIMD4(-96.2045, 78.5313, -94.9154, 78.3905), + SIMD4(-94.9154, 78.3905, -95.3292, 78.225), + SIMD4(-95.3292, 78.225, -94.9343, 78.0756), + SIMD4(-94.9343, 78.0756, -97.6582, 78.0906), + SIMD4(-97.6582, 78.0906, -96.9447, 78.1519), + SIMD4(-96.9447, 78.1519, -98.3326, 78.7735), + SIMD4(-98.3326, 78.7735, -96.2045, 78.5313), + SIMD4(-93.1709, 74.161, -90.3546, 73.8687), + SIMD4(-90.3546, 73.8687, -92.1179, 72.7538), + SIMD4(-92.1179, 72.7538, -94.2113, 72.7569), + SIMD4(-94.2113, 72.7569, -93.5339, 72.4995), + SIMD4(-93.5339, 72.4995, -94.0375, 72.0288), + SIMD4(-94.0375, 72.0288, -95.193, 72.0274), + SIMD4(-95.193, 72.0274, -95.6453, 73.6708), + SIMD4(-95.6453, 73.6708, -93.1709, 74.161), + SIMD4(-97.4395, 69.6427, -95.2678, 68.8261), + SIMD4(-95.2678, 68.8261, -96.5988, 68.4608), + SIMD4(-96.5988, 68.4608, -98.9045, 68.9324), + SIMD4(-98.9045, 68.9324, -99.5641, 69.0341), + SIMD4(-99.5641, 69.0341, -98.0414, 69.4566), + SIMD4(-98.0414, 69.4566, -98.0808, 69.8331), + SIMD4(-98.0808, 69.8331, -97.4395, 69.6427), + SIMD4(-61.1052, 45.9447, -59.865, 46.1595), + SIMD4(-59.865, 46.1595, -60.2051, 45.743), + SIMD4(-60.2051, 45.743, -61.2837, 45.5739), + SIMD4(-61.2837, 45.5739, -61.4953, 45.9415), + SIMD4(-61.4953, 45.9415, -60.4082, 47.0035), + SIMD4(-60.4082, 47.0035, -60.4945, 46.2703), + SIMD4(-60.4945, 46.2703, -61.1052, 45.9447), + SIMD4(-67.1249, 45.1694, -67.8022, 45.7275), + SIMD4(-67.8022, 45.7275, -67.8068, 47.0828), + SIMD4(-67.8068, 47.0828, -69.2429, 47.463), + SIMD4(-69.2429, 47.463, -70.865, 45.2707), + SIMD4(-70.865, 45.2707, -74.7089, 45.0039), + SIMD4(-74.7089, 45.0039, -70.5195, 47.0325), + SIMD4(-70.5195, 47.0325, -68.8157, 48.366), + SIMD4(-68.8157, 48.366, -66.5981, 49.1264), + SIMD4(-66.5981, 49.1264, -64.2618, 48.9219), + SIMD4(-64.2618, 48.9219, -64.3488, 48.4232), + SIMD4(-64.3488, 48.4232, -65.2594, 48.0212), + SIMD4(-65.2594, 48.0212, -66.7044, 48.0225), + SIMD4(-66.7044, 48.0225, -64.8521, 47.5699), + SIMD4(-64.8521, 47.5699, -65.3189, 47.1012), + SIMD4(-65.3189, 47.1012, -64.8314, 47.0608), + SIMD4(-64.8314, 47.0608, -64.5415, 46.2403), + SIMD4(-64.5415, 46.2403, -62.7501, 45.6482), + SIMD4(-62.7501, 45.6482, -61.9555, 45.8682), + SIMD4(-61.9555, 45.8682, -61.0315, 45.2917), + SIMD4(-61.0315, 45.2917, -64.2861, 44.5503), + SIMD4(-64.2861, 44.5503, -65.4817, 43.5181), + SIMD4(-65.4817, 43.5181, -66.1257, 43.8138), + SIMD4(-66.1257, 43.8138, -66.0906, 44.5049), + SIMD4(-66.0906, 44.5049, -63.368, 45.3648), + SIMD4(-63.368, 45.3648, -64.8731, 45.3546), + SIMD4(-64.8731, 45.3546, -64.3146, 45.8357), + SIMD4(-64.3146, 45.8357, -64.6327, 45.9466), + SIMD4(-64.6327, 45.9466, -65.8845, 45.2229), + SIMD4(-65.8845, 45.2229, -67.1249, 45.1694), + SIMD4(-55.4587, 51.5365, -56.0311, 51.3284), + SIMD4(-56.0311, 51.3284, -55.8, 51.0333), + SIMD4(-55.8, 51.0333, -56.8222, 49.6135), + SIMD4(-56.8222, 49.6135, -56.1794, 50.115), + SIMD4(-56.1794, 50.115, -55.5029, 49.9832), + SIMD4(-55.5029, 49.9832, -56.1402, 49.6191), + SIMD4(-56.1402, 49.6191, -55.2295, 49.5082), + SIMD4(-55.2295, 49.5082, -55.3532, 49.0794), + SIMD4(-55.3532, 49.0794, -54.5022, 49.5273), + SIMD4(-54.5022, 49.5273, -53.6194, 49.3216), + SIMD4(-53.6194, 49.3216, -54.1145, 48.3936), + SIMD4(-54.1145, 48.3936, -53.0427, 48.6566), + SIMD4(-53.0427, 48.6566, -53.8637, 47.787), + SIMD4(-53.8637, 47.787, -52.8833, 48.1312), + SIMD4(-52.8833, 48.1312, -52.8881, 47.0459), + SIMD4(-52.8881, 47.0459, -53.167, 46.6465), + SIMD4(-53.167, 46.6465, -53.5898, 46.6389), + SIMD4(-53.5898, 46.6389, -53.5974, 47.146), + SIMD4(-53.5974, 47.146, -54.1328, 46.8386), + SIMD4(-54.1328, 46.8386, -53.8495, 47.4403), + SIMD4(-53.8495, 47.4403, -54.1918, 47.8598), + SIMD4(-54.1918, 47.8598, -55.7885, 46.8672), + SIMD4(-55.7885, 46.8672, -54.7846, 47.6647), + SIMD4(-54.7846, 47.6647, -59.3207, 47.7369), + SIMD4(-59.3207, 47.7369, -58.3302, 48.5221), + SIMD4(-58.3302, 48.5221, -59.1677, 48.5585), + SIMD4(-59.1677, 48.5585, -57.9905, 48.9879), + SIMD4(-57.9905, 48.9879, -58.2134, 49.3867), + SIMD4(-58.2134, 49.3867, -57.0359, 51.0108), + SIMD4(-57.0359, 51.0108, -55.4587, 51.5365), + SIMD4(-86.5894, 71.0108, -84.8237, 71.0286), + SIMD4(-84.8237, 71.0286, -84.6994, 71.6314), + SIMD4(-84.6994, 71.6314, -85.9116, 71.9865), + SIMD4(-85.9116, 71.9865, -84.2837, 72.0445), + SIMD4(-84.2837, 72.0445, -85.6499, 72.7222), + SIMD4(-85.6499, 72.7222, -84.2566, 72.7967), + SIMD4(-84.2566, 72.7967, -85.4547, 73.1055), + SIMD4(-85.4547, 73.1055, -81.6054, 73.696), + SIMD4(-81.6054, 73.696, -80.2772, 72.7702), + SIMD4(-80.2772, 72.7702, -81.2293, 72.3117), + SIMD4(-81.2293, 72.3117, -80.6115, 72.4508), + SIMD4(-80.6115, 72.4508, -80.9251, 71.9077), + SIMD4(-80.9251, 71.9077, -79.8313, 72.4463), + SIMD4(-79.8313, 72.4463, -78.5851, 71.8806), + SIMD4(-78.5851, 71.8806, -78.6993, 72.3514), + SIMD4(-78.6993, 72.3514, -77.5165, 72.1778), + SIMD4(-77.5165, 72.1778, -78.4224, 72.5715), + SIMD4(-78.4224, 72.5715, -76.8935, 72.7207), + SIMD4(-76.8935, 72.7207, -75.0715, 72.3229), + SIMD4(-75.0715, 72.3229, -75.9228, 71.7172), + SIMD4(-75.9228, 71.7172, -74.2664, 72.0377), + SIMD4(-74.2664, 72.0377, -75.2048, 71.7091), + SIMD4(-75.2048, 71.7091, -74.7008, 71.6756), + SIMD4(-74.7008, 71.6756, -74.9962, 71.2181), + SIMD4(-74.9962, 71.2181, -73.8666, 71.771), + SIMD4(-73.8666, 71.771, -74.1973, 71.4042), + SIMD4(-74.1973, 71.4042, -71.6407, 71.5163), + SIMD4(-71.6407, 71.5163, -71.1865, 71.2787), + SIMD4(-71.1865, 71.2787, -72.6327, 70.8308), + SIMD4(-72.6327, 70.8308, -70.6727, 71.0522), + SIMD4(-70.6727, 71.0522, -71.8902, 70.4315), + SIMD4(-71.8902, 70.4315, -71.2759, 70.5003), + SIMD4(-71.2759, 70.5003, -71.4294, 70.1278), + SIMD4(-71.4294, 70.1278, -70.0847, 70.8295), + SIMD4(-70.0847, 70.8295, -68.4958, 70.6103), + SIMD4(-68.4958, 70.6103, -70.0577, 70.0426), + SIMD4(-70.0577, 70.0426, -67.8553, 70.2818), + SIMD4(-67.8553, 70.2818, -67.1928, 69.7568), + SIMD4(-67.1928, 69.7568, -69.2508, 69.5119), + SIMD4(-69.2508, 69.5119, -66.6763, 69.2584), + SIMD4(-66.6763, 69.2584, -69.3191, 68.857), + SIMD4(-69.3191, 68.857, -66.7139, 68.4457), + SIMD4(-66.7139, 68.4457, -66.9231, 68.0657), + SIMD4(-66.9231, 68.0657, -66.2124, 68.2804), + SIMD4(-66.2124, 68.2804, -66.5265, 67.8512), + SIMD4(-66.5265, 67.8512, -65.9424, 68.0709), + SIMD4(-65.9424, 68.0709, -65.4013, 67.6749), + SIMD4(-65.4013, 67.6749, -64.9769, 68.0434), + SIMD4(-64.9769, 68.0434, -63.8502, 67.5661), + SIMD4(-63.8502, 67.5661, -64.5893, 67.3155), + SIMD4(-64.5893, 67.3155, -63.0401, 67.235), + SIMD4(-63.0401, 67.235, -63.7016, 66.8224), + SIMD4(-63.7016, 66.8224, -62.1236, 67.0467), + SIMD4(-62.1236, 67.0467, -61.2997, 66.6487), + SIMD4(-61.2997, 66.6487, -62.5531, 66.4068), + SIMD4(-62.5531, 66.4068, -61.9916, 66.0353), + SIMD4(-61.9916, 66.0353, -62.6241, 66.0163), + SIMD4(-62.6241, 66.0163, -62.6589, 65.6399), + SIMD4(-62.6589, 65.6399, -63.4587, 65.853), + SIMD4(-63.4587, 65.853, -63.6066, 64.9281), + SIMD4(-63.6066, 64.9281, -65.4016, 65.764), + SIMD4(-65.4016, 65.764, -64.4454, 66.3171), + SIMD4(-64.4454, 66.3171, -65.8257, 65.9969), + SIMD4(-65.8257, 65.9969, -66.9863, 66.6275), + SIMD4(-66.9863, 66.6275, -67.8834, 66.4674), + SIMD4(-67.8834, 66.4674, -67.3504, 65.9297), + SIMD4(-67.3504, 65.9297, -68.7489, 66.2), + SIMD4(-68.7489, 66.2, -68.1867, 65.871), + SIMD4(-68.1867, 65.871, -66.6974, 64.8152), + SIMD4(-66.6974, 64.8152, -65.0945, 64.4846), + SIMD4(-65.0945, 64.4846, -65.5937, 64.3111), + SIMD4(-65.5937, 64.3111, -64.4109, 63.7063), + SIMD4(-64.4109, 63.7063, -64.6646, 63.2454), + SIMD4(-64.6646, 63.2454, -65.1918, 63.7643), + SIMD4(-65.1918, 63.7643, -64.6836, 62.9024), + SIMD4(-64.6836, 62.9024, -65.1085, 62.6265), + SIMD4(-65.1085, 62.6265, -67.8933, 63.7337), + SIMD4(-67.8933, 63.7337, -67.7226, 63.4228), + SIMD4(-67.7226, 63.4228, -68.9111, 63.7032), + SIMD4(-68.9111, 63.7032, -65.9802, 62.2089), + SIMD4(-65.9802, 62.2089, -66.3237, 61.8703), + SIMD4(-66.3237, 61.8703, -71.3473, 63.0661), + SIMD4(-71.3473, 63.0661, -71.9922, 63.4162), + SIMD4(-71.9922, 63.4162, -71.3809, 63.5803), + SIMD4(-71.3809, 63.5803, -72.4984, 63.8235), + SIMD4(-72.4984, 63.8235, -73.2713, 64.5825), + SIMD4(-73.2713, 64.5825, -74.6814, 64.8307), + SIMD4(-74.6814, 64.8307, -74.8939, 64.4657), + SIMD4(-74.8939, 64.4657, -77.7912, 64.3671), + SIMD4(-77.7912, 64.3671, -78.1897, 64.7518), + SIMD4(-78.1897, 64.7518, -77.3267, 65.4531), + SIMD4(-77.3267, 65.4531, -75.4521, 64.8416), + SIMD4(-75.4521, 64.8416, -75.7987, 65.2975), + SIMD4(-75.7987, 65.2975, -73.5508, 65.4853), + SIMD4(-73.5508, 65.4853, -74.4164, 66.1671), + SIMD4(-74.4164, 66.1671, -72.2341, 67.2844), + SIMD4(-72.2341, 67.2844, -74.7167, 69.0455), + SIMD4(-74.7167, 69.0455, -76.5851, 68.6987), + SIMD4(-76.5851, 68.6987, -75.6478, 69.2125), + SIMD4(-75.6478, 69.2125, -78.9798, 70.5813), + SIMD4(-78.9798, 70.5813, -79.4052, 70.4007), + SIMD4(-79.4052, 70.4007, -78.8098, 70.1786), + SIMD4(-78.8098, 70.1786, -79.0929, 69.9253), + SIMD4(-79.0929, 69.9253, -81.652, 70.0946), + SIMD4(-81.652, 70.0946, -80.9217, 69.7309), + SIMD4(-80.9217, 69.7309, -85.78, 70.0367), + SIMD4(-85.78, 70.0367, -86.3969, 70.4653), + SIMD4(-86.3969, 70.4653, -87.9007, 70.2519), + SIMD4(-87.9007, 70.2519, -89.4559, 71.0617), +SIMD4(-89.4559, 71.0617, -87.1401, 71.0116), + SIMD4(-87.1401, 71.0116, -89.6933, 71.4235), + SIMD4(-89.6933, 71.4235, -90.0252, 71.9488), + SIMD4(-90.0252, 71.9488, -88.7052, 73.4033), + SIMD4(-88.7052, 73.4033, -85.0093, 73.7786), + SIMD4(-85.0093, 73.7786, -86.6678, 72.7625), + SIMD4(-86.6678, 72.7625, -86.2185, 71.8991), + SIMD4(-86.2185, 71.8991, -85.0234, 71.3532), + SIMD4(-85.0234, 71.3532, -86.5894, 71.0108), + SIMD4(-61.8011, 49.0939, -64.2438, 49.9444), + SIMD4(-64.2438, 49.9444, -61.8011, 49.0939), + SIMD4(-63.8113, 46.4687, -62.0237, 46.4216), + SIMD4(-62.0237, 46.4216, -62.5313, 45.9773), + SIMD4(-62.5313, 45.9773, -62.9951, 46.2921), + SIMD4(-62.9951, 46.2921, -64.4031, 46.6916), + SIMD4(-64.4031, 46.6916, -63.9936, 47.0616), + SIMD4(-63.9936, 47.0616, -63.8113, 46.4687), + SIMD4(-82.0005, 62.9542, -83.0158, 62.2099), + SIMD4(-83.0158, 62.2099, -83.7286, 62.2572), + SIMD4(-83.7286, 62.2572, -83.3764, 62.9049), + SIMD4(-83.3764, 62.9049, -82.0005, 62.9542), + SIMD4(-79.5453, 62.4117, -79.3239, 62.0261), + SIMD4(-79.3239, 62.0261, -80.0041, 61.7025), + SIMD4(-80.0041, 61.7025, -80.2347, 62.1527), + SIMD4(-80.2347, 62.1527, -79.5453, 62.4117), + SIMD4(-75.6759, 68.3225, -75.0781, 68.1731), + SIMD4(-75.0781, 68.1731, -75.202, 67.4592), + SIMD4(-75.202, 67.4592, -76.8588, 67.2405), + SIMD4(-76.8588, 67.2405, -77.1259, 67.9471), + SIMD4(-77.1259, 67.9471, -75.6759, 68.3225), + SIMD4(-79.5373, 73.6545, -77.2065, 73.4996), + SIMD4(-77.2065, 73.4996, -76.09, 72.8812), + SIMD4(-76.09, 72.8812, -79.5005, 72.756), + SIMD4(-79.5005, 72.756, -80.8607, 73.6706), + SIMD4(-80.8607, 73.6706, -79.5373, 73.6545), + SIMD4(-80.7317, 52.7473, -81.9014, 53.1656), + SIMD4(-81.9014, 53.1656, -80.7317, 52.7473), + SIMD4(-78.9356, 56.2661, -80.0083, 55.911), + SIMD4(-80.0083, 55.911, -79.4824, 56.4038), + SIMD4(-79.4824, 56.4038, -78.9356, 56.2661), + SIMD4(-89.8333, 77.2676, -91.1473, 77.3873), + SIMD4(-91.1473, 77.3873, -90.8426, 77.655), + SIMD4(-90.8426, 77.655, -89.8333, 77.2676), + SIMD4(-104.5582, 77.1417, -106.0661, 77.7254), + SIMD4(-106.0661, 77.7254, -105.5879, 77.736), + SIMD4(-105.5879, 77.736, -104.5582, 77.1417), + SIMD4(-98.7916, 79.9811, -100.0568, 79.8982), + SIMD4(-100.0568, 79.8982, -98.7916, 79.9811), + SIMD4(-105.2889, 72.9199, -106.9497, 73.5104), + SIMD4(-106.9497, 73.5104, -105.5123, 73.7658), + SIMD4(-105.5123, 73.7658, -104.5551, 73.5411), + SIMD4(-104.5551, 73.5411, -105.2889, 72.9199), + SIMD4(-102.2273, 76.0149, -103.9853, 75.9331), + SIMD4(-103.9853, 75.9331, -104.4061, 76.1085), + SIMD4(-104.4061, 76.1085, -102.2273, 76.0149), + SIMD4(-104.0229, 76.5831, -103.0335, 76.4315), + SIMD4(-103.0335, 76.4315, -104.2707, 76.3263), + SIMD4(-104.2707, 76.3263, -104.5857, 76.6065), + SIMD4(-104.5857, 76.6065, -104.0229, 76.5831), + SIMD4(-118.3281, 75.5797, -119.3946, 75.6173), + SIMD4(-119.3946, 75.6173, -118.379, 75.958), + SIMD4(-118.379, 75.958, -117.4991, 76.0772), + SIMD4(-117.4991, 76.0772, -118.3281, 75.5797), + SIMD4(-113.8325, 77.7546, -115.0293, 77.9675), + SIMD4(-115.0293, 77.9675, -114.3029, 78.0327), + SIMD4(-114.3029, 78.0327, -113.8325, 77.7546), + SIMD4(-128.5524, 52.9397, -128.679, 52.2896), + SIMD4(-128.679, 52.2896, -129.0229, 52.756), + SIMD4(-129.0229, 52.756, -129.0333, 53.2799), + SIMD4(-129.0333, 53.2799, -128.5524, 52.9397), + SIMD4(-73.6217, 67.7838, -74.746, 67.9848), + SIMD4(-74.746, 67.9848, -74.3794, 68.0935), + SIMD4(-74.3794, 68.0935, -73.6217, 67.7838), + SIMD4(-98.2704, 73.8685, -99.417, 73.8954), + SIMD4(-99.417, 73.8954, -98.9667, 73.9882), + SIMD4(-98.9667, 73.9882, -97.6591, 74.0716), + SIMD4(-97.6591, 74.0716, -98.2704, 73.8685), + SIMD4(-104.1199, 75.0363, -104.8874, 75.1478), + SIMD4(-104.8874, 75.1478, -104.0747, 75.4245), + SIMD4(-104.0747, 75.4245, -103.6421, 75.1629), + SIMD4(-103.6421, 75.1629, -104.1199, 75.0363), + SIMD4(-89.1615, 17.8148, -88.2957, 18.4724), + SIMD4(-88.2957, 18.4724, -88.2035, 17.5166), + SIMD4(-88.2035, 17.5166, -88.4045, 16.4886), + SIMD4(-88.4045, 16.4886, -89.2328, 15.8887), + SIMD4(-89.2328, 15.8887, -89.1615, 17.8148), + SIMD4(-77.7438, 24.7074, -78.0449, 24.2875), + SIMD4(-78.0449, 24.2875, -78.3389, 24.642), + SIMD4(-78.3389, 24.642, -78.1628, 25.2023), + SIMD4(-78.1628, 25.2023, -77.7438, 24.7074), + ] + static let europe: [SIMD4] = [ +SIMD4(-2.6677, 51.623, -5.1684, 51.7407), + SIMD4(-5.1684, 51.7407, -3.9803, 52.5417), + SIMD4(-3.9803, 52.5417, -4.1015, 52.9155), + SIMD4(-4.1015, 52.9155, -4.6831, 52.8062), + SIMD4(-4.6831, 52.8062, -4.2686, 53.1445), + SIMD4(-4.2686, 53.1445, -2.7495, 53.3102), + SIMD4(-2.7495, 53.3102, -2.8465, 54.1353), + SIMD4(-2.8465, 54.1353, -3.592, 54.5644), + SIMD4(-3.592, 54.5644, -3.0362, 54.9531), + SIMD4(-3.0362, 54.9531, -5.0323, 54.7614), + SIMD4(-5.0323, 54.7614, -4.5841, 55.9387), + SIMD4(-4.5841, 55.9387, -5.2282, 55.8863), + SIMD4(-5.2282, 55.8863, -5.0843, 56.1975), + SIMD4(-5.0843, 56.1975, -5.7307, 55.3341), + SIMD4(-5.7307, 55.3341, -5.1884, 56.7581), + SIMD4(-5.1884, 56.7581, -6.1337, 56.7067), + SIMD4(-6.1337, 56.7067, -5.0167, 58.5666), + SIMD4(-5.0167, 58.5666, -3.8595, 58.5771), + SIMD4(-3.8595, 58.5771, -3.0462, 58.6155), + SIMD4(-3.0462, 58.6155, -4.1345, 57.5777), + SIMD4(-4.1345, 57.5777, -1.7779, 57.4937), + SIMD4(-1.7779, 57.4937, -3.31, 56.3635), + SIMD4(-3.31, 56.3635, -2.6743, 56.2534), + SIMD4(-2.6743, 56.2534, -3.7891, 56.0952), + SIMD4(-3.7891, 56.0952, -2.1471, 55.903), + SIMD4(-2.1471, 55.903, -1.2324, 54.7037), + SIMD4(-1.2324, 54.7037, -0.0844, 54.1181), + SIMD4(-0.0844, 54.1181, 0.1153, 53.6093), + SIMD4(0.1153, 53.6093, -0.6599, 53.724), + SIMD4(-0.6599, 53.724, 0.271, 53.3355), + SIMD4(0.271, 53.3355, 0.0459, 52.9056), + SIMD4(0.0459, 52.9056, 1.7434, 52.5785), + SIMD4(1.7434, 52.5785, 0.4245, 51.4656), + SIMD4(0.4245, 51.4656, 1.4149, 51.3633), + SIMD4(1.4149, 51.3633, 0.9602, 50.9259), + SIMD4(0.9602, 50.9259, -5.6552, 50.0772), + SIMD4(-5.6552, 50.0772, -4.1882, 51.1885), + SIMD4(-4.1882, 51.1885, -2.6677, 51.623), + SIMD4(-6.1987, 58.3633, -7.0519, 58.018), + SIMD4(-7.0519, 58.018, -6.1987, 58.3633), + SIMD4(-6.218, 54.0887, -8.1448, 54.4535), + SIMD4(-8.1448, 54.4535, -7.5504, 54.768), + SIMD4(-7.5504, 54.768, -6.1292, 55.2174), + SIMD4(-6.1292, 55.2174, -5.4704, 54.5002), + SIMD4(-5.4704, 54.5002, -6.218, 54.0887), + SIMD4(38.2144, 47.0915, 35.0146, 46.106), + SIMD4(35.0146, 46.106, 35.2304, 46.4406), + SIMD4(35.2304, 46.4406, 34.9464, 45.7287), + SIMD4(34.9464, 45.7287, 31.8313, 46.2817), + SIMD4(31.8313, 46.2817, 31.5549, 46.5543), + SIMD4(31.5549, 46.5543, 32.578, 46.6156), + SIMD4(32.578, 46.6156, 31.7592, 47.2128), + SIMD4(31.7592, 47.2128, 31.8729, 46.6498), + SIMD4(31.8729, 46.6498, 30.7963, 46.552), + SIMD4(30.7963, 46.552, 29.6284, 45.7225), + SIMD4(29.6284, 45.7225, 29.7059, 45.2599), + SIMD4(29.7059, 45.2599, 28.7607, 45.2341), + SIMD4(28.7607, 45.2341, 28.2125, 45.4504), + SIMD4(28.2125, 45.4504, 28.9584, 46.4585), + SIMD4(28.9584, 46.4585, 30.1311, 46.4231), + SIMD4(30.1311, 46.4231, 29.1254, 47.9646), + SIMD4(29.1254, 47.9646, 27.5492, 48.4777), + SIMD4(27.5492, 48.4777, 24.9791, 47.7241), + SIMD4(24.9791, 47.7241, 22.8767, 47.9473), + SIMD4(22.8767, 47.9473, 22.1318, 48.4053), + SIMD4(22.1318, 48.4053, 22.7057, 49.1712), + SIMD4(22.7057, 49.1712, 22.7062, 49.6062), + SIMD4(22.7062, 49.6062, 24.0899, 50.5305), + SIMD4(24.0899, 50.5305, 23.6086, 51.6105), + SIMD4(23.6086, 51.6105, 24.3619, 51.8675), + SIMD4(24.3619, 51.8675, 30.5445, 51.265), + SIMD4(30.5445, 51.265, 30.9807, 52.0462), + SIMD4(30.9807, 52.0462, 33.7353, 52.3448), + SIMD4(33.7353, 52.3448, 34.3979, 51.7804), + SIMD4(34.3979, 51.7804, 34.2139, 51.2554), + SIMD4(34.2139, 51.2554, 35.3119, 51.0439), + SIMD4(35.3119, 51.0439, 35.5911, 50.3687), + SIMD4(35.5911, 50.3687, 37.4229, 50.4115), + SIMD4(37.4229, 50.4115, 40.0807, 49.5769), + SIMD4(40.0807, 49.5769, 39.7787, 47.8875), + SIMD4(39.7787, 47.8875, 38.3688, 47.61), + SIMD4(38.3688, 47.61, 38.2144, 47.0915), + SIMD4(41.5101, 41.5175, 42.7879, 41.5637), + SIMD4(42.7879, 41.5637, 43.6316, 40.929), + SIMD4(43.6316, 40.929, 43.6662, 40.1264), + SIMD4(43.6662, 40.1264, 44.8172, 39.6504), + SIMD4(44.8172, 39.6504, 44.0232, 39.3774), + SIMD4(44.0232, 39.3774, 44.7651, 37.1424), + SIMD4(44.7651, 37.1424, 42.7746, 37.3719), + SIMD4(42.7746, 37.3719, 39.3566, 36.6816), + SIMD4(39.3566, 36.6816, 36.6586, 36.8025), + SIMD4(36.6586, 36.8025, 36.1273, 35.8314), + SIMD4(36.1273, 35.8314, 36.0489, 36.9106), + SIMD4(36.0489, 36.9106, 34.7036, 36.8168), + SIMD4(34.7036, 36.8168, 33.6947, 36.182), + SIMD4(33.6947, 36.182, 32.7948, 36.0359), + SIMD4(32.7948, 36.0359, 30.9503, 36.8487), + SIMD4(30.9503, 36.8487, 29.6891, 36.1567), + SIMD4(29.6891, 36.1567, 28.9696, 36.7153), + SIMD4(28.9696, 36.7153, 27.4539, 36.7122), + SIMD4(27.4539, 36.7122, 28.2424, 37.0291), + SIMD4(28.2424, 37.0291, 27.263, 36.9766), + SIMD4(27.263, 36.9766, 27.2324, 37.9787), + SIMD4(27.2324, 37.9787, 26.2907, 38.2772), + SIMD4(26.2907, 38.2772, 26.4413, 38.6412), + SIMD4(26.4413, 38.6412, 27.1442, 38.452), + SIMD4(27.1442, 38.452, 26.7637, 38.7096), + SIMD4(26.7637, 38.7096, 26.8992, 39.5497), + SIMD4(26.8992, 39.5497, 26.1131, 39.4674), + SIMD4(26.1131, 39.4674, 26.1813, 39.9901), + SIMD4(26.1813, 39.9901, 26.7381, 40.4002), + SIMD4(26.7381, 40.4002, 29.0071, 40.3897), + SIMD4(29.0071, 40.3897, 29.8492, 40.7601), + SIMD4(29.8492, 40.7601, 29.1481, 41.221), + SIMD4(29.1481, 41.221, 31.2549, 41.1076), + SIMD4(31.2549, 41.1076, 33.3813, 42.0176), + SIMD4(33.3813, 42.0176, 35.0064, 42.0633), + SIMD4(35.0064, 42.0633, 38.3811, 40.9245), + SIMD4(38.3811, 40.9245, 40.2652, 40.9613), + SIMD4(40.2652, 40.9613, 41.5101, 41.5175), + SIMD4(28.0145, 41.969, 28.9563, 41.0082), + SIMD4(28.9563, 41.0082, 27.4994, 40.9731), + SIMD4(27.4994, 40.9731, 26.2027, 40.0754), + SIMD4(26.2027, 40.0754, 26.7921, 40.6266), + SIMD4(26.7921, 40.6266, 26.1055, 40.6113), + SIMD4(26.1055, 40.6113, 26.3311, 40.9545), + SIMD4(26.3311, 40.9545, 26.5797, 41.9479), + SIMD4(26.5797, 41.9479, 28.0145, 41.969), + SIMD4(9.524, 47.5242, 9.4877, 47.0623), + SIMD4(9.4877, 47.0623, 10.4546, 46.8994), + SIMD4(10.4546, 46.8994, 10.1283, 46.2382), + SIMD4(10.1283, 46.2382, 9.3044, 46.4956), + SIMD4(9.3044, 46.4956, 8.9537, 45.83), + SIMD4(8.9537, 45.83, 8.3707, 46.4451), + SIMD4(8.3707, 46.4451, 7.129, 45.8804), + SIMD4(7.129, 45.8804, 6.7581, 46.4158), + SIMD4(6.7581, 46.4158, 5.9715, 46.1512), + SIMD4(5.9715, 46.1512, 6.9684, 47.4532), + SIMD4(6.9684, 47.4532, 9.524, 47.5242), + SIMD4(19.0765, 57.8359, 18.2065, 57.0102), + SIMD4(18.2065, 57.0102, 18.1365, 57.5566), + SIMD4(18.1365, 57.5566, 19.0765, 57.8359), + SIMD4(11.3883, 59.0365, 12.4861, 60.1068), + SIMD4(12.4861, 60.1068, 12.2941, 61.0027), + SIMD4(12.2941, 61.0027, 12.8808, 61.3523), + SIMD4(12.8808, 61.3523, 12.1554, 61.7208), + SIMD4(12.1554, 61.7208, 12.1752, 63.5959), + SIMD4(12.1752, 63.5959, 14.0633, 64.0955), + SIMD4(14.0633, 64.0955, 13.6503, 64.5815), + SIMD4(13.6503, 64.5815, 14.4797, 65.3015), + SIMD4(14.4797, 65.3015, 14.5433, 66.1293), + SIMD4(14.5433, 66.1293, 15.4838, 66.306), + SIMD4(15.4838, 66.306, 16.7836, 67.895), + SIMD4(16.7836, 67.895, 17.9167, 67.9649), + SIMD4(17.9167, 67.9649, 18.303, 68.5554), + SIMD4(18.303, 68.5554, 19.9698, 68.3564), + SIMD4(19.9698, 68.3564, 20.1167, 69.0209), + SIMD4(20.1167, 69.0209, 20.6222, 69.0369), + SIMD4(20.6222, 69.0369, 23.6389, 67.9544), + SIMD4(23.6389, 67.9544, 23.4549, 67.4603), + SIMD4(23.4549, 67.4603, 23.9886, 66.8105), + SIMD4(23.9886, 66.8105, 23.7003, 66.2526), + SIMD4(23.7003, 66.2526, 24.1555, 65.8053), + SIMD4(24.1555, 65.8053, 22.401, 65.8621), + SIMD4(22.401, 65.8621, 21.4104, 65.3174), + SIMD4(21.4104, 65.3174, 21.3938, 64.5443), + SIMD4(21.3938, 64.5443, 20.7627, 63.8678), + SIMD4(20.7627, 63.8678, 17.3784, 62.4628), + SIMD4(17.3784, 62.4628, 17.251, 60.7008), + SIMD4(17.251, 60.7008, 18.9904, 59.8278), + SIMD4(18.9904, 59.8278, 17.9643, 59.3594), + SIMD4(17.9643, 59.3594, 18.6176, 59.3271), + SIMD4(18.6176, 59.3271, 18.2854, 59.1094), + SIMD4(18.2854, 59.1094, 16.2143, 58.6367), + SIMD4(16.2143, 58.6367, 16.9238, 58.4926), + SIMD4(16.9238, 58.4926, 15.9203, 56.1674), + SIMD4(15.9203, 56.1674, 14.714, 56.1341), + SIMD4(14.714, 56.1341, 14.1737, 55.3966), + SIMD4(14.1737, 55.3966, 12.8858, 55.4114), + SIMD4(12.8858, 55.4114, 12.4712, 56.2905), + SIMD4(12.4712, 56.2905, 12.8837, 56.6177), + SIMD4(12.8837, 56.6177, 11.2482, 58.3691), + SIMD4(11.2482, 58.3691, 11.3883, 59.0365), + SIMD4(3.1453, 39.7901, 3.4618, 39.6978), + SIMD4(3.4618, 39.6978, 3.1546, 39.3333), + SIMD4(3.1546, 39.3333, 2.6341, 39.5562), + SIMD4(2.6341, 39.5562, 3.1453, 39.7901), + SIMD4(-1.794, 43.4073, -0.0412, 42.6891), + SIMD4(-0.0412, 42.6891, 3.2114, 42.4312), + SIMD4(3.2114, 42.4312, 3.248, 41.9442), + SIMD4(3.248, 41.9442, 0.7146, 40.8229), + SIMD4(0.7146, 40.8229, -0.327, 39.5199), + SIMD4(-0.327, 39.5199, 0.2016, 38.7592), + SIMD4(0.2016, 38.7592, -2.1115, 36.7767), + SIMD4(-2.1115, 36.7767, -4.3668, 36.7181), + SIMD4(-4.3668, 36.7181, -5.6255, 36.0259), + SIMD4(-5.6255, 36.0259, -6.8638, 37.2789), + SIMD4(-6.8638, 37.2789, -7.4062, 37.1794), + SIMD4(-7.4062, 37.1794, -6.9979, 39.0564), + SIMD4(-6.9979, 39.0564, -7.5357, 39.6616), + SIMD4(-7.5357, 39.6616, -6.9754, 39.7984), + SIMD4(-6.9754, 39.7984, -6.9285, 41.0091), + SIMD4(-6.9285, 41.0091, -6.2217, 41.5604), + SIMD4(-6.2217, 41.5604, -6.6183, 41.9424), + SIMD4(-6.6183, 41.9424, -8.8523, 41.9269), + SIMD4(-8.8523, 41.9269, -9.1781, 43.174), + SIMD4(-9.1781, 43.174, -7.6981, 43.7646), + SIMD4(-7.6981, 43.7646, -1.794, 43.4073), + SIMD4(22.5387, 49.0727, 22.1113, 48.3934), + SIMD4(22.1113, 48.3934, 20.49, 48.5269), + SIMD4(20.49, 48.5269, 18.1456, 47.7634), + SIMD4(18.1456, 47.7634, 16.8654, 48.3869), + SIMD4(16.8654, 48.3869, 17.7585, 48.8881), + SIMD4(17.7585, 48.8881, 19.4416, 49.5977), + SIMD4(19.4416, 49.5977, 19.8022, 49.1923), + SIMD4(19.8022, 49.1923, 21.3505, 49.4288), + SIMD4(21.3505, 49.4288, 22.5387, 49.0727), + SIMD4(16.5162, 46.4999, 15.6359, 46.2007), + SIMD4(15.6359, 46.2007, 15.2421, 45.4414), + SIMD4(15.2421, 45.4414, 13.6152, 45.4768), + SIMD4(13.6152, 45.4768, 13.6635, 45.792), + SIMD4(13.6635, 45.792, 13.3782, 46.2616), + SIMD4(13.3782, 46.2616, 13.7, 46.5203), + SIMD4(13.7, 46.5203, 16.0931, 46.8633), + SIMD4(16.0931, 46.8633, 16.5162, 46.4999), + SIMD4(21.3601, 44.8267, 22.7209, 44.6055), + SIMD4(22.7209, 44.6055, 22.3696, 43.7813), + SIMD4(22.3696, 43.7813, 22.9769, 43.188), + SIMD4(22.9769, 43.188, 22.4221, 42.3289), + SIMD4(22.4221, 42.3289, 21.5625, 42.2475), + SIMD4(21.5625, 42.2475, 21.7529, 42.6698), + SIMD4(21.7529, 42.6698, 20.8006, 43.2611), + SIMD4(20.8006, 43.2611, 20.3443, 42.8279), + SIMD4(20.3443, 42.8279, 19.4513, 43.5621), + SIMD4(19.4513, 43.5621, 19.3568, 44.8585), + SIMD4(19.3568, 44.8585, 18.9955, 44.904), + SIMD4(18.9955, 44.904, 19.4, 45.2125), + SIMD4(19.4, 45.2125, 18.9054, 45.9317), + SIMD4(18.9054, 45.9317, 20.2102, 46.126), + SIMD4(20.2102, 46.126, 21.4902, 45.1479), + SIMD4(21.4902, 45.1479, 21.3601, 44.8267), + SIMD4(39.9783, 43.4198, 36.6508, 45.1265), + SIMD4(36.6508, 45.1265, 38.4923, 46.0905), + SIMD4(38.4923, 46.0905, 37.7665, 46.6361), + SIMD4(37.7665, 46.6361, 39.2707, 47.0441), + SIMD4(39.2707, 47.0441, 38.2014, 47.3208), + SIMD4(38.2014, 47.3208, 39.7787, 47.8875), + SIMD4(39.7787, 47.8875, 40.0807, 49.5769), + SIMD4(40.0807, 49.5769, 37.4229, 50.4115), + SIMD4(37.4229, 50.4115, 35.5911, 50.3687), +SIMD4(35.5911, 50.3687, 35.3119, 51.0439), + SIMD4(35.3119, 51.0439, 34.2139, 51.2554), + SIMD4(34.2139, 51.2554, 34.3979, 51.7804), + SIMD4(34.3979, 51.7804, 33.7353, 52.3448), + SIMD4(33.7353, 52.3448, 31.7634, 52.1011), + SIMD4(31.7634, 52.1011, 31.2588, 53.0167), + SIMD4(31.2588, 53.0167, 32.6857, 53.4481), + SIMD4(32.6857, 53.4481, 30.7988, 54.7833), + SIMD4(30.7988, 54.7833, 30.8822, 55.5964), + SIMD4(30.8822, 55.5964, 28.1479, 56.1429), + SIMD4(28.1479, 56.1429, 27.352, 57.5281), + SIMD4(27.352, 57.5281, 27.777, 57.8567), + SIMD4(27.777, 57.8567, 27.4342, 58.7873), + SIMD4(27.4342, 58.7873, 28.058, 59.7815), + SIMD4(28.058, 59.7815, 30.1727, 59.9571), + SIMD4(30.1727, 59.9571, 28.5128, 60.6773), + SIMD4(28.5128, 60.6773, 27.7977, 60.5361), + SIMD4(27.7977, 60.5361, 31.534, 62.8854), + SIMD4(31.534, 62.8854, 29.9915, 63.7352), + SIMD4(29.9915, 63.7352, 30.5261, 64.0773), + SIMD4(30.5261, 64.0773, 29.6042, 64.9684), + SIMD4(29.6042, 64.9684, 30.0875, 65.7865), + SIMD4(30.0875, 65.7865, 29.0662, 66.8917), + SIMD4(29.0662, 66.8917, 29.9881, 67.6683), + SIMD4(29.9881, 67.6683, 28.6852, 68.1898), + SIMD4(28.6852, 68.1898, 28.7729, 68.84), + SIMD4(28.7729, 68.84, 28.4141, 68.9042), + SIMD4(28.4141, 68.9042, 31.9846, 69.9537), + SIMD4(31.9846, 69.9537, 33.0078, 69.7221), + SIMD4(33.0078, 69.7221, 32.0915, 69.6326), + SIMD4(32.0915, 69.6326, 32.3777, 69.4791), + SIMD4(32.3777, 69.4791, 33.4543, 69.4282), + SIMD4(33.4543, 69.4282, 33.1412, 69.0687), + SIMD4(33.1412, 69.0687, 35.8579, 69.1917), + SIMD4(35.8579, 69.1917, 40.9664, 67.7135), + SIMD4(40.9664, 67.7135, 41.189, 66.8262), + SIMD4(41.189, 66.8262, 38.6539, 66.069), + SIMD4(38.6539, 66.069, 31.8953, 67.1614), + SIMD4(31.8953, 67.1614, 34.6918, 65.9519), + SIMD4(34.6918, 65.9519, 34.4064, 65.3958), + SIMD4(34.4064, 65.3958, 35.0354, 64.4402), + SIMD4(35.0354, 64.4402, 37.3728, 63.8167), + SIMD4(37.3728, 63.8167, 38.0622, 64.091), + SIMD4(38.0622, 64.091, 36.5787, 64.791), + SIMD4(36.5787, 64.791, 36.8828, 65.1724), + SIMD4(36.8828, 65.1724, 39.758, 64.5771), + SIMD4(39.758, 64.5771, 40.4449, 64.7787), + SIMD4(40.4449, 64.7787, 39.8165, 65.5979), + SIMD4(39.8165, 65.5979, 42.2105, 66.5197), + SIMD4(42.2105, 66.5197, 44.1324, 66.0646), + SIMD4(44.1324, 66.0646, 44.4293, 66.9377), + SIMD4(44.4293, 66.9377, 43.7824, 67.2545), + SIMD4(43.7824, 67.2545, 44.2047, 68.2538), + SIMD4(44.2047, 68.2538, 43.3332, 68.6734), + SIMD4(20.9578, 55.2789, 20.5948, 54.9824), + SIMD4(20.5948, 54.9824, 22.5673, 55.0591), + SIMD4(22.5673, 55.0591, 22.6845, 54.5629), + SIMD4(22.6845, 54.5629, 19.6044, 54.4592), + SIMD4(19.6044, 54.4592, 20.9578, 55.2789), + SIMD4(33.5941, 46.0962, 34.6869, 45.977), + SIMD4(34.6869, 45.977, 35.4575, 45.3163), + SIMD4(35.4575, 45.3163, 36.575, 45.3936), + SIMD4(36.575, 45.3936, 35.7595, 45.0709), + SIMD4(35.7595, 45.0709, 33.6559, 44.4332), + SIMD4(33.6559, 44.4332, 33.5552, 45.0977), + SIMD4(33.5552, 45.0977, 32.508, 45.4038), + SIMD4(32.508, 45.4038, 33.5941, 46.0962), + SIMD4(28.2125, 45.4504, 29.7059, 45.2599), + SIMD4(29.7059, 45.2599, 29.5575, 44.8434), + SIMD4(29.5575, 44.8434, 28.8915, 44.9187), + SIMD4(28.8915, 44.9187, 28.5854, 43.7422), + SIMD4(28.5854, 43.7422, 27.0869, 44.1674), + SIMD4(27.0869, 44.1674, 25.4971, 43.6708), + SIMD4(25.4971, 43.6708, 22.919, 43.8345), + SIMD4(22.919, 43.8345, 22.7209, 44.6055), + SIMD4(22.7209, 44.6055, 21.3601, 44.8267), + SIMD4(21.3601, 44.8267, 20.7658, 45.5975), + SIMD4(20.7658, 45.5975, 20.2418, 46.1086), + SIMD4(20.2418, 46.1086, 21.152, 46.3043), + SIMD4(21.152, 46.3043, 22.2906, 47.7278), + SIMD4(22.2906, 47.7278, 23.1395, 48.0874), + SIMD4(23.1395, 48.0874, 24.9791, 47.7241), + SIMD4(24.9791, 47.7241, 26.7138, 48.2635), + SIMD4(26.7138, 48.2635, 28.0718, 46.9784), + SIMD4(28.0718, 46.9784, 28.2125, 45.4504), + SIMD4(-8.7771, 41.9411, -6.6183, 41.9424), + SIMD4(-6.6183, 41.9424, -6.2217, 41.5604), + SIMD4(-6.2217, 41.5604, -6.9285, 41.0091), + SIMD4(-6.9285, 41.0091, -6.9754, 39.7984), + SIMD4(-6.9754, 39.7984, -7.5357, 39.6616), + SIMD4(-7.5357, 39.6616, -6.9979, 39.0564), + SIMD4(-6.9979, 39.0564, -7.2815, 38.7146), + SIMD4(-7.2815, 38.7146, -6.9576, 38.1879), + SIMD4(-6.9576, 38.1879, -7.4062, 37.1794), + SIMD4(-7.4062, 37.1794, -8.9978, 37.0323), + SIMD4(-8.9978, 37.0323, -8.6683, 38.4243), + SIMD4(-8.6683, 38.4243, -9.2504, 38.6567), + SIMD4(-9.2504, 38.6567, -8.7916, 39.0782), + SIMD4(-8.7916, 39.0782, -9.4797, 38.7988), + SIMD4(-9.4797, 38.7988, -8.6846, 40.7525), + SIMD4(-8.6846, 40.7525, -8.7771, 41.9411), + SIMD4(23.6053, 51.5179, 24.0899, 50.5305), + SIMD4(24.0899, 50.5305, 22.7062, 49.6062), + SIMD4(22.7062, 49.6062, 22.8098, 49.0208), + SIMD4(22.8098, 49.0208, 18.9684, 49.3962), + SIMD4(18.9684, 49.3962, 17.7022, 50.3072), + SIMD4(17.7022, 50.3072, 16.5967, 50.1219), + SIMD4(16.5967, 50.1219, 16.36, 50.6214), + SIMD4(16.36, 50.6214, 14.8094, 50.859), + SIMD4(14.8094, 50.859, 14.6194, 52.5285), + SIMD4(14.6194, 52.5285, 14.1286, 52.8782), + SIMD4(14.1286, 52.8782, 14.5584, 53.8232), + SIMD4(14.5584, 53.8232, 14.1982, 53.919), + SIMD4(14.1982, 53.919, 17.843, 54.8167), + SIMD4(17.843, 54.8167, 18.9763, 54.3489), + SIMD4(18.9763, 54.3489, 23.3701, 54.2005), + SIMD4(23.3701, 54.2005, 23.9094, 52.9049), + SIMD4(23.9094, 52.9049, 23.1751, 52.2866), + SIMD4(23.1751, 52.2866, 23.6053, 51.5179), + SIMD4(20.6222, 69.0369, 20.1167, 69.0209), + SIMD4(20.1167, 69.0209, 19.9698, 68.3564), + SIMD4(19.9698, 68.3564, 18.303, 68.5554), + SIMD4(18.303, 68.5554, 17.9167, 67.9649), + SIMD4(17.9167, 67.9649, 16.7836, 67.895), + SIMD4(16.7836, 67.895, 15.4838, 66.306), + SIMD4(15.4838, 66.306, 14.5433, 66.1293), + SIMD4(14.5433, 66.1293, 14.4797, 65.3015), + SIMD4(14.4797, 65.3015, 13.6503, 64.5815), + SIMD4(13.6503, 64.5815, 14.0633, 64.0955), + SIMD4(14.0633, 64.0955, 12.1752, 63.5959), + SIMD4(12.1752, 63.5959, 12.1554, 61.7208), + SIMD4(12.1554, 61.7208, 12.8808, 61.3523), + SIMD4(12.8808, 61.3523, 12.2941, 61.0027), + SIMD4(12.2941, 61.0027, 12.4861, 60.1068), + SIMD4(12.4861, 60.1068, 11.6808, 59.5923), + SIMD4(11.6808, 59.5923, 11.6428, 58.9261), + SIMD4(11.6428, 58.9261, 10.8345, 59.1839), + SIMD4(10.8345, 59.1839, 10.5953, 59.7646), + SIMD4(10.5953, 59.7646, 10.1794, 59.0093), + SIMD4(10.1794, 59.0093, 9.5572, 59.1127), + SIMD4(9.5572, 59.1127, 8.1661, 58.1453), + SIMD4(8.1661, 58.1453, 6.7314, 58.0683), + SIMD4(6.7314, 58.0683, 5.5859, 58.6204), + SIMD4(5.5859, 58.6204, 5.6122, 59.0129), + SIMD4(5.6122, 59.0129, 6.3633, 59.0009), + SIMD4(6.3633, 59.0009, 5.8892, 59.0979), + SIMD4(5.8892, 59.0979, 6.4153, 59.5471), + SIMD4(6.4153, 59.5471, 5.1732, 59.1625), + SIMD4(5.1732, 59.1625, 5.2422, 59.5643), + SIMD4(5.2422, 59.5643, 6.9957, 60.512), + SIMD4(6.9957, 60.512, 5.1458, 59.6388), + SIMD4(5.1458, 59.6388, 5.6886, 60.1232), + SIMD4(5.6886, 60.1232, 5.1371, 60.4456), + SIMD4(5.1371, 60.4456, 5.6483, 60.688), + SIMD4(5.6483, 60.688, 5.1158, 60.636), + SIMD4(5.1158, 60.636, 5.0086, 61.0382), + SIMD4(5.0086, 61.0382, 7.6045, 61.2105), + SIMD4(7.6045, 61.2105, 5.1067, 61.1875), + SIMD4(5.1067, 61.1875, 4.9301, 61.8783), + SIMD4(4.9301, 61.8783, 6.7308, 61.8698), + SIMD4(6.7308, 61.8698, 5.1432, 62.1599), + SIMD4(5.1432, 62.1599, 8.0955, 62.7318), + SIMD4(8.0955, 62.7318, 6.735, 62.7207), + SIMD4(6.735, 62.7207, 7.5719, 63.0995), + SIMD4(7.5719, 63.0995, 8.6231, 62.8462), + SIMD4(8.6231, 62.8462, 8.158, 63.1615), + SIMD4(8.158, 63.1615, 8.5762, 63.6012), + SIMD4(8.5762, 63.6012, 10.7602, 63.4613), + SIMD4(10.7602, 63.4613, 11.1756, 63.8989), + SIMD4(11.1756, 63.8989, 11.4576, 64.003), + SIMD4(11.4576, 64.003, 9.5673, 63.7062), + SIMD4(9.5673, 63.7062, 12.9155, 65.3393), + SIMD4(12.9155, 65.3393, 12.1339, 65.2792), + SIMD4(12.1339, 65.2792, 12.7838, 66.1004), + SIMD4(12.7838, 66.1004, 14.0342, 66.2976), + SIMD4(14.0342, 66.2976, 13.1188, 66.2307), + SIMD4(13.1188, 66.2307, 13.2114, 66.6408), + SIMD4(13.2114, 66.6408, 15.6915, 67.5214), + SIMD4(15.6915, 67.5214, 14.7989, 67.8093), + SIMD4(14.7989, 67.8093, 17.5528, 68.4263), + SIMD4(17.5528, 68.4263, 16.5144, 68.5326), + SIMD4(16.5144, 68.5326, 18.2598, 69.4706), + SIMD4(18.2598, 69.4706, 19.687, 69.8047), + SIMD4(19.687, 69.8047, 19.6415, 69.424), + SIMD4(19.6415, 69.424, 20.3242, 69.9453), + SIMD4(20.3242, 69.9453, 20.1072, 69.3412), + SIMD4(20.1072, 69.3412, 20.7395, 69.5205), + SIMD4(20.7395, 69.5205, 20.6221, 69.9139), + SIMD4(20.6221, 69.9139, 21.9747, 69.8346), + SIMD4(21.9747, 69.8346, 21.3558, 70.2334), + SIMD4(21.3558, 70.2334, 22.6846, 70.3748), + SIMD4(22.6846, 70.3748, 23.3539, 69.9834), + SIMD4(23.3539, 69.9834, 24.7647, 71.0084), + SIMD4(24.7647, 71.0084, 25.7814, 70.8168), + SIMD4(25.7814, 70.8168, 25.0438, 70.109), + SIMD4(25.0438, 70.109, 26.5069, 70.9128), + SIMD4(26.5069, 70.9128, 26.5851, 70.41), + SIMD4(26.5851, 70.41, 26.9894, 70.5114), + SIMD4(26.9894, 70.5114, 27.5971, 71.0913), + SIMD4(27.5971, 71.0913, 28.3923, 70.9753), + SIMD4(28.3923, 70.9753, 27.898, 70.6779), + SIMD4(27.898, 70.6779, 28.2718, 70.668), + SIMD4(28.2718, 70.668, 28.193, 70.2486), + SIMD4(28.193, 70.2486, 28.8315, 70.864), + SIMD4(28.8315, 70.864, 30.9606, 70.3438), + SIMD4(30.9606, 70.3438, 28.7812, 70.1454), + SIMD4(28.7812, 70.1454, 30.9241, 69.6518), + SIMD4(30.9241, 69.6518, 28.9658, 69.022), + SIMD4(28.9658, 69.022, 29.1416, 69.6714), + SIMD4(29.1416, 69.6714, 27.7479, 70.0648), + SIMD4(27.7479, 70.0648, 26.0725, 69.6916), + SIMD4(26.0725, 69.6916, 24.9414, 68.5933), + SIMD4(24.9414, 68.5933, 22.4109, 68.7199), + SIMD4(22.4109, 68.7199, 21.5938, 69.2736), + SIMD4(21.5938, 69.2736, 20.6222, 69.0369), + SIMD4(19.2551, 70.0664, 19.6078, 70.0191), + SIMD4(19.6078, 70.0191, 18.232, 69.6768), + SIMD4(18.232, 69.6768, 19.2551, 70.0664), + SIMD4(17.503, 69.5962, 18.0768, 69.3958), + SIMD4(18.0768, 69.3958, 16.9602, 69.0694), + SIMD4(16.9602, 69.0694, 17.503, 69.5962), + SIMD4(15.7604, 68.5612, 16.5474, 68.7166), + SIMD4(16.5474, 68.7166, 15.0377, 68.2827), + SIMD4(15.0377, 68.2827, 14.2575, 68.1908), + SIMD4(14.2575, 68.1908, 16.1295, 69.2739), + SIMD4(16.1295, 69.2739, 15.7604, 68.5612), + SIMD4(5.9939, 50.7504, 5.031, 51.4691), + SIMD4(5.031, 51.4691, 3.4489, 51.5408), + SIMD4(3.4489, 51.5408, 4.2741, 51.4716), + SIMD4(4.2741, 51.4716, 3.9469, 51.8105), + SIMD4(3.9469, 51.8105, 5.0612, 52.9606), + SIMD4(5.0612, 52.9606, 7.1973, 53.2823), + SIMD4(7.1973, 53.2823, 6.8004, 51.9674), + SIMD4(6.8004, 51.9674, 5.9487, 51.8027), + SIMD4(5.9487, 51.8027, 5.9939, 50.7504), + SIMD4(19.1943, 43.5333, 20.3477, 42.8528), + SIMD4(20.3477, 42.8528, 19.6545, 42.6286), + SIMD4(19.6545, 42.6286, 19.3455, 41.9188), + SIMD4(19.3455, 41.9188, 18.4381, 42.5229), + SIMD4(18.4381, 42.5229, 19.1943, 43.5333), + SIMD4(26.6189, 48.2599, 27.5492, 48.4777), + SIMD4(27.5492, 48.4777, 29.1254, 47.9646), + SIMD4(29.1254, 47.9646, 30.1311, 46.4231), + SIMD4(30.1311, 46.4231, 29.5551, 46.4078), + SIMD4(29.5551, 46.4078, 28.9584, 46.4585), + SIMD4(28.9584, 46.4585, 28.2125, 45.4504), + SIMD4(28.2125, 45.4504, 28.0718, 46.9784), + SIMD4(28.0718, 46.9784, 26.6189, 48.2599), + SIMD4(21.5625, 42.2475, 22.2771, 42.3499), + SIMD4(22.2771, 42.3499, 23.0057, 41.7169), +SIMD4(23.0057, 41.7169, 22.7248, 41.1785), + SIMD4(22.7248, 41.1785, 21.5758, 40.8689), + SIMD4(21.5758, 40.8689, 20.7408, 40.9053), + SIMD4(20.7408, 40.9053, 20.4486, 41.5213), + SIMD4(20.4486, 41.5213, 21.5625, 42.2475), + SIMD4(6.1165, 50.121, 6.4848, 49.7078), + SIMD4(6.4848, 49.7078, 5.9289, 49.4775), + SIMD4(5.9289, 49.4775, 5.744, 49.9196), + SIMD4(5.744, 49.9196, 6.1165, 50.121), + SIMD4(22.7662, 54.3568, 22.5673, 55.0591), + SIMD4(22.5673, 55.0591, 21.2357, 55.2641), + SIMD4(21.2357, 55.2641, 21.0461, 56.0701), + SIMD4(21.0461, 56.0701, 24.841, 56.4112), + SIMD4(24.841, 56.4112, 26.7602, 55.2934), + SIMD4(26.7602, 55.2934, 25.8593, 54.9193), + SIMD4(25.8593, 54.9193, 25.6806, 54.1405), + SIMD4(25.6806, 54.1405, 23.5591, 53.9198), + SIMD4(23.5591, 53.9198, 22.7662, 54.3568), + SIMD4(26.5936, 55.6675, 24.841, 56.4112), + SIMD4(24.841, 56.4112, 21.0461, 56.0701), + SIMD4(21.0461, 56.0701, 21.7287, 57.571), + SIMD4(21.7287, 57.571, 22.5546, 57.7243), + SIMD4(22.5546, 57.7243, 23.9312, 57.0085), + SIMD4(23.9312, 57.0085, 24.3826, 57.25), + SIMD4(24.3826, 57.25, 24.3226, 57.8706), + SIMD4(24.3226, 57.8706, 25.111, 58.0634), + SIMD4(25.111, 58.0634, 27.8286, 57.2933), + SIMD4(27.8286, 57.2933, 27.6395, 56.8457), + SIMD4(27.6395, 56.8457, 28.1479, 56.1429), + SIMD4(28.1479, 56.1429, 26.5936, 55.6675), + SIMD4(20.3443, 42.8279, 20.8006, 43.2611), + SIMD4(20.8006, 43.2611, 21.7529, 42.6698), + SIMD4(21.7529, 42.6698, 21.5625, 42.2475), + SIMD4(21.5625, 42.2475, 20.5785, 41.8662), + SIMD4(20.5785, 41.8662, 20.064, 42.5473), + SIMD4(20.064, 42.5473, 20.3443, 42.8279), + SIMD4(7.0211, 45.9258, 8.4226, 46.446), + SIMD4(8.4226, 46.446, 9.0237, 45.8457), + SIMD4(9.0237, 45.8457, 9.3044, 46.4956), + SIMD4(9.3044, 46.4956, 10.0806, 46.228), + SIMD4(10.0806, 46.228, 10.4528, 46.8649), + SIMD4(10.4528, 46.8649, 12.1694, 47.0821), + SIMD4(12.1694, 47.0821, 13.7, 46.5203), + SIMD4(13.7, 46.5203, 13.3782, 46.2616), + SIMD4(13.3782, 46.2616, 13.8747, 45.6148), + SIMD4(13.8747, 45.6148, 12.2743, 45.446), + SIMD4(12.2743, 45.446, 12.305, 44.4294), + SIMD4(12.305, 44.4294, 14.5407, 42.2443), + SIMD4(14.5407, 42.2443, 16.1646, 41.8962), + SIMD4(16.1646, 41.8962, 15.9005, 41.5121), + SIMD4(15.9005, 41.5121, 18.4858, 40.1048), + SIMD4(18.4858, 40.1048, 18.3438, 39.8214), + SIMD4(18.3438, 39.8214, 16.9282, 40.4581), + SIMD4(16.9282, 40.4581, 16.5219, 39.7476), + SIMD4(16.5219, 39.7476, 17.1746, 38.9981), + SIMD4(17.1746, 38.9981, 15.7245, 37.9391), + SIMD4(15.7245, 37.9391, 16.21, 38.9411), + SIMD4(16.21, 38.9411, 15.6928, 39.9902), + SIMD4(15.6928, 39.9902, 11.1032, 42.4166), + SIMD4(11.1032, 42.4166, 10.0477, 44.02), + SIMD4(10.0477, 44.02, 8.7658, 44.4223), + SIMD4(8.7658, 44.4223, 7.4932, 43.7671), + SIMD4(7.4932, 43.7671, 7.6372, 44.1648), + SIMD4(7.6372, 44.1648, 6.9002, 44.3357), + SIMD4(6.9002, 44.3357, 6.6348, 45.0682), + SIMD4(6.6348, 45.0682, 7.1464, 45.3817), + SIMD4(7.1464, 45.3817, 7.0211, 45.9258), + SIMD4(15.5766, 38.2203, 15.1126, 36.6878), + SIMD4(15.1126, 36.6878, 12.7573, 37.5674), + SIMD4(12.7573, 37.5674, 12.4355, 37.8198), + SIMD4(12.4355, 37.8198, 12.7344, 38.1831), + SIMD4(12.7344, 38.1831, 15.5766, 38.2203), + SIMD4(9.632, 40.882, 9.5625, 39.166), + SIMD4(9.5625, 39.166, 8.6485, 38.9266), + SIMD4(8.6485, 38.9266, 8.5478, 39.8392), + SIMD4(8.5478, 39.8392, 8.2242, 40.9133), + SIMD4(8.2242, 40.9133, 9.2284, 41.2571), + SIMD4(9.2284, 41.2571, 9.632, 40.882), + SIMD4(-7.2187, 55.092, -8.1448, 54.4535), + SIMD4(-8.1448, 54.4535, -6.1757, 54.0535), + SIMD4(-6.1757, 54.0535, -6.325, 52.2467), + SIMD4(-6.325, 52.2467, -9.7373, 51.4737), + SIMD4(-9.7373, 51.4737, -10.1208, 51.6007), + SIMD4(-10.1208, 51.6007, -9.5988, 51.8744), + SIMD4(-9.5988, 51.8744, -10.3411, 51.7989), + SIMD4(-10.3411, 51.7989, -9.9097, 52.1229), + SIMD4(-9.9097, 52.1229, -10.3826, 52.1691), + SIMD4(-10.3826, 52.1691, -8.7834, 52.6796), + SIMD4(-8.7834, 52.6796, -9.9166, 52.5697), + SIMD4(-9.9166, 52.5697, -8.9301, 53.2071), + SIMD4(-8.9301, 53.2071, -10.0913, 53.4128), + SIMD4(-10.0913, 53.4128, -9.5782, 53.8054), + SIMD4(-9.5782, 53.8054, -10.0564, 54.2578), + SIMD4(-10.0564, 54.2578, -8.5456, 54.2412), + SIMD4(-8.5456, 54.2412, -8.1334, 54.6408), + SIMD4(-8.1334, 54.6408, -8.7639, 54.6812), + SIMD4(-8.7639, 54.6812, -8.2746, 55.1463), + SIMD4(-8.2746, 55.1463, -7.2187, 55.092), + SIMD4(-15.5431, 66.2285, -14.5959, 66.3815), + SIMD4(-14.5959, 66.3815, -15.1164, 66.1024), + SIMD4(-15.1164, 66.1024, -13.6179, 65.5193), + SIMD4(-13.6179, 65.5193, -13.5697, 65.0681), + SIMD4(-13.5697, 65.0681, -18.3028, 63.4542), + SIMD4(-18.3028, 63.4542, -22.6522, 63.8277), + SIMD4(-22.6522, 63.8277, -21.5906, 64.6264), + SIMD4(-21.5906, 64.6264, -24.0262, 64.8634), + SIMD4(-24.0262, 64.8634, -21.7637, 65.1737), + SIMD4(-21.7637, 65.1737, -22.4003, 65.1593), + SIMD4(-22.4003, 65.1593, -21.8444, 65.4474), + SIMD4(-21.8444, 65.4474, -24.4757, 65.5252), + SIMD4(-24.4757, 65.5252, -23.2854, 65.75), + SIMD4(-23.2854, 65.75, -23.8326, 65.8492), + SIMD4(-23.8326, 65.8492, -23.4525, 66.181), + SIMD4(-23.4525, 66.181, -22.4417, 65.9083), + SIMD4(-22.4417, 65.9083, -22.8892, 66.4406), + SIMD4(-22.8892, 66.4406, -21.4069, 66.0256), + SIMD4(-21.4069, 66.0256, -21.6584, 65.7236), + SIMD4(-21.6584, 65.7236, -21.1297, 65.2666), + SIMD4(-21.1297, 65.2666, -20.2075, 66.1001), + SIMD4(-20.2075, 66.1001, -19.4897, 65.7681), + SIMD4(-19.4897, 65.7681, -18.8459, 66.1839), + SIMD4(-18.8459, 66.1839, -18.1419, 65.7341), + SIMD4(-18.1419, 65.7341, -18.2972, 66.1574), + SIMD4(-18.2972, 66.1574, -17.5504, 65.9644), + SIMD4(-17.5504, 65.9644, -16.2493, 66.5229), + SIMD4(-16.2493, 66.5229, -15.5431, 66.2285), + SIMD4(22.1318, 48.4053, 22.8767, 47.9473), + SIMD4(22.8767, 47.9473, 21.1217, 46.2824), + SIMD4(21.1217, 46.2824, 18.3583, 45.753), + SIMD4(18.3583, 45.753, 17.3106, 45.9961), + SIMD4(17.3106, 45.9961, 16.0931, 46.8633), + SIMD4(16.0931, 46.8633, 16.551, 47.7474), + SIMD4(16.551, 47.7474, 18.7242, 47.7872), + SIMD4(18.7242, 47.7872, 20.6432, 48.5497), + SIMD4(20.6432, 48.5497, 22.1318, 48.4053), + SIMD4(23.4154, 38.9586, 24.5785, 38.0202), + SIMD4(24.5785, 38.0202, 24.212, 38.1175), + SIMD4(24.212, 38.1175, 22.8703, 38.8705), + SIMD4(22.8703, 38.8705, 23.4154, 38.9586), + SIMD4(23.8522, 35.5354, 26.2855, 35.3098), + SIMD4(26.2855, 35.3098, 24.7998, 34.9345), + SIMD4(24.7998, 34.9345, 23.5928, 35.2572), + SIMD4(23.5928, 35.2572, 23.8522, 35.5354), + SIMD4(26.3209, 41.7166, 26.6249, 41.4018), + SIMD4(26.6249, 41.4018, 26.1092, 40.7497), + SIMD4(26.1092, 40.7497, 23.7628, 40.7478), + SIMD4(23.7628, 40.7478, 24.3434, 40.1477), + SIMD4(24.3434, 40.1477, 23.7279, 40.3297), + SIMD4(23.7279, 40.3297, 23.9471, 39.9656), + SIMD4(23.9471, 39.9656, 22.6295, 40.4956), + SIMD4(22.6295, 40.4956, 23.3277, 39.1749), + SIMD4(23.3277, 39.1749, 22.5691, 38.8675), + SIMD4(22.5691, 38.8675, 23.967, 38.275), + SIMD4(23.967, 38.275, 24.0554, 37.7096), + SIMD4(24.0554, 37.7096, 23.5018, 38.0349), + SIMD4(23.5018, 38.0349, 23.0363, 37.8784), + SIMD4(23.0363, 37.8784, 23.4893, 37.4402), + SIMD4(23.4893, 37.4402, 22.7254, 37.5421), + SIMD4(22.7254, 37.5421, 23.1602, 36.4481), + SIMD4(23.1602, 36.4481, 21.94, 36.8918), + SIMD4(21.94, 36.8918, 21.138, 37.8541), + SIMD4(21.138, 37.8541, 21.4037, 38.1967), + SIMD4(21.4037, 38.1967, 23.1835, 38.1337), + SIMD4(23.1835, 38.1337, 21.1826, 38.3456), + SIMD4(21.1826, 38.3456, 20.7686, 38.8744), + SIMD4(20.7686, 38.8744, 21.1184, 39.03), + SIMD4(21.1184, 39.03, 20.3008, 39.3271), + SIMD4(20.3008, 39.3271, 20.0013, 39.7094), + SIMD4(20.0013, 39.7094, 20.9643, 40.8499), + SIMD4(20.9643, 40.8499, 24.0561, 41.5272), + SIMD4(24.0561, 41.5272, 25.9233, 41.3119), + SIMD4(25.9233, 41.3119, 26.3209, 41.7166), + SIMD4(9.524, 47.5242, 7.5654, 47.6065), + SIMD4(7.5654, 47.6065, 8.1349, 48.9736), + SIMD4(8.1349, 48.9736, 6.3443, 49.4527), + SIMD4(6.3443, 49.4527, 5.9487, 51.8027), + SIMD4(5.9487, 51.8027, 7.0196, 52.266), + SIMD4(7.0196, 52.266, 6.6916, 52.5302), + SIMD4(6.6916, 52.5302, 7.2064, 53.6545), + SIMD4(7.2064, 53.6545, 9.784, 53.5546), + SIMD4(9.784, 53.5546, 8.6449, 54.295), + SIMD4(8.6449, 54.295, 8.9572, 54.5383), + SIMD4(8.9572, 54.5383, 8.6703, 54.9034), + SIMD4(8.6703, 54.9034, 11.0644, 54.2805), + SIMD4(11.0644, 54.2805, 10.8546, 54.0098), + SIMD4(10.8546, 54.0098, 12.5754, 54.4674), + SIMD4(12.5754, 54.4674, 13.7242, 54.1532), + SIMD4(13.7242, 54.1532, 14.2589, 53.7296), + SIMD4(14.2589, 53.7296, 14.1286, 52.8782), + SIMD4(14.1286, 52.8782, 15.0166, 51.2527), + SIMD4(15.0166, 51.2527, 14.7665, 50.8183), + SIMD4(14.7665, 50.8183, 14.3197, 51.0378), + SIMD4(14.3197, 51.0378, 12.0898, 50.3018), + SIMD4(12.0898, 50.3018, 13.8147, 48.7669), + SIMD4(13.8147, 48.7669, 12.7604, 48.107), + SIMD4(12.7604, 48.107, 13.0144, 47.4781), + SIMD4(13.0144, 47.4781, 9.524, 47.5242), + SIMD4(9.4804, 42.8054, 9.1861, 41.3849), + SIMD4(9.1861, 41.3849, 8.7025, 42.0431), + SIMD4(8.7025, 42.0431, 8.7131, 42.5498), + SIMD4(8.7131, 42.5498, 9.4804, 42.8054), + SIMD4(7.6156, 47.5927, 6.9684, 47.4532), + SIMD4(6.9684, 47.4532, 5.97, 46.2147), + SIMD4(5.97, 46.2147, 6.7761, 46.4066), + SIMD4(6.7761, 46.4066, 7.1534, 45.4009), + SIMD4(7.1534, 45.4009, 6.6277, 45.118), + SIMD4(6.6277, 45.118, 6.8748, 44.392), + SIMD4(6.8748, 44.392, 7.6771, 44.0832), + SIMD4(7.6771, 44.0832, 6.494, 43.1693), + SIMD4(6.494, 43.1693, 3.9108, 43.5631), + SIMD4(3.9108, 43.5631, 3.0518, 42.9151), + SIMD4(3.0518, 42.9151, 3.2114, 42.4312), + SIMD4(3.2114, 42.4312, 2.6517, 42.3405), + SIMD4(2.6517, 42.3405, -1.4288, 43.0368), + SIMD4(-1.4288, 43.0368, -1.794, 43.4073), + SIMD4(-1.794, 43.4073, -1.081, 45.5324), + SIMD4(-1.081, 45.5324, -0.5485, 45.0006), + SIMD4(-0.5485, 45.0006, -0.7331, 45.3846), + SIMD4(-0.7331, 45.3846, -1.1463, 46.3114), + SIMD4(-1.1463, 46.3114, -2.0925, 46.865), + SIMD4(-2.0925, 46.865, -1.7425, 47.216), + SIMD4(-1.7425, 47.216, -4.3121, 47.8229), + SIMD4(-4.3121, 47.8229, -4.7208, 48.5399), + SIMD4(-4.7208, 48.5399, -1.3765, 48.6526), + SIMD4(-1.3765, 48.6526, -1.8564, 49.6838), + SIMD4(-1.8564, 49.6838, 0.4169, 49.4484), + SIMD4(0.4169, 49.4484, 0.1867, 49.703), + SIMD4(0.1867, 49.703, 1.5928, 50.2522), + SIMD4(1.5928, 50.2522, 1.6723, 50.885), + SIMD4(1.6723, 50.885, 2.5249, 51.0971), + SIMD4(2.5249, 51.0971, 4.1761, 49.9603), + SIMD4(4.1761, 49.9603, 4.8187, 50.1532), + SIMD4(4.8187, 50.1532, 5.5073, 49.5109), + SIMD4(5.5073, 49.5109, 8.1349, 48.9736), + SIMD4(8.1349, 48.9736, 7.6156, 47.5927), + SIMD4(24.1555, 65.8053, 23.7003, 66.2526), + SIMD4(23.7003, 66.2526, 23.9886, 66.8105), + SIMD4(23.9886, 66.8105, 23.4549, 67.4603), + SIMD4(23.4549, 67.4603, 23.6389, 67.9544), + SIMD4(23.6389, 67.9544, 20.6222, 69.0369), + SIMD4(20.6222, 69.0369, 21.5938, 69.2736), + SIMD4(21.5938, 69.2736, 22.4109, 68.7199), + SIMD4(22.4109, 68.7199, 24.9414, 68.5933), + SIMD4(24.9414, 68.5933, 26.5254, 69.915), + SIMD4(26.5254, 69.915, 29.1416, 69.6714), + SIMD4(29.1416, 69.6714, 28.4707, 68.4884), + SIMD4(28.4707, 68.4884, 29.9881, 67.6683), + SIMD4(29.9881, 67.6683, 29.0662, 66.8917), + SIMD4(29.0662, 66.8917, 30.0875, 65.7865), + SIMD4(30.0875, 65.7865, 29.6009, 65.002), +SIMD4(29.6009, 65.002, 30.5138, 64.2), + SIMD4(30.5138, 64.2, 30.2103, 63.8033), + SIMD4(30.2103, 63.8033, 31.534, 62.8854), + SIMD4(31.534, 62.8854, 29.2517, 61.2878), + SIMD4(29.2517, 61.2878, 27.6693, 60.499), + SIMD4(27.6693, 60.499, 22.9639, 59.8264), + SIMD4(22.9639, 59.8264, 23.1984, 60.0218), + SIMD4(23.1984, 60.0218, 22.4627, 60.0292), + SIMD4(22.4627, 60.0292, 22.585, 60.3806), + SIMD4(22.585, 60.3806, 21.436, 60.5964), + SIMD4(21.436, 60.5964, 21.606, 61.5916), + SIMD4(21.606, 61.5916, 21.1036, 62.6229), + SIMD4(21.1036, 62.6229, 21.5451, 63.2043), + SIMD4(21.5451, 63.2043, 25.2882, 64.8604), + SIMD4(25.2882, 64.8604, 25.3479, 65.4792), + SIMD4(25.3479, 65.4792, 24.1555, 65.8053), + SIMD4(27.352, 57.5281, 24.3226, 57.8706), + SIMD4(24.3226, 57.8706, 24.5291, 58.3542), + SIMD4(24.5291, 58.3542, 23.7676, 58.3608), + SIMD4(23.7676, 58.3608, 23.517, 59.1076), + SIMD4(23.517, 59.1076, 25.5093, 59.639), + SIMD4(25.5093, 59.639, 28.0125, 59.4843), + SIMD4(28.0125, 59.4843, 27.4342, 58.7873), + SIMD4(27.4342, 58.7873, 27.7785, 57.8707), + SIMD4(27.7785, 57.8707, 27.352, 57.5281), + SIMD4(22.6174, 58.6212, 23.3232, 58.4508), + SIMD4(23.3232, 58.4508, 21.9855, 57.9952), + SIMD4(21.9855, 57.9952, 21.8623, 58.4972), + SIMD4(21.8623, 58.4972, 22.6174, 58.6212), + SIMD4(12.5687, 55.7851, 11.8623, 54.7726), + SIMD4(11.8623, 54.7726, 11.0703, 55.6293), + SIMD4(11.0703, 55.6293, 12.2189, 56.1187), + SIMD4(12.2189, 56.1187, 12.5687, 55.7851), + SIMD4(9.7397, 54.8255, 8.6703, 54.9034), + SIMD4(8.6703, 54.9034, 8.1321, 55.5998), + SIMD4(8.1321, 55.5998, 8.164, 56.6069), + SIMD4(8.164, 56.6069, 9.2549, 57.0117), + SIMD4(9.2549, 57.0117, 8.2841, 56.8523), + SIMD4(8.2841, 56.8523, 9.5543, 57.2325), + SIMD4(9.5543, 57.2325, 10.61, 57.7369), + SIMD4(10.61, 57.7369, 10.2827, 56.6205), + SIMD4(10.2827, 56.6205, 10.9262, 56.4433), + SIMD4(10.9262, 56.4433, 9.5911, 55.4932), + SIMD4(9.5911, 55.4932, 9.7397, 54.8255), + SIMD4(10.6451, 55.6098, 10.7853, 55.1334), + SIMD4(10.7853, 55.1334, 9.9674, 55.2055), + SIMD4(9.9674, 55.2055, 9.8606, 55.5155), + SIMD4(9.8606, 55.5155, 10.6451, 55.6098), + SIMD4(18.8322, 49.5108, 16.9531, 48.5988), + SIMD4(16.9531, 48.5988, 14.9935, 49.0011), + SIMD4(14.9935, 49.0011, 14.1898, 48.5786), + SIMD4(14.1898, 48.5786, 12.0897, 50.2686), + SIMD4(12.0897, 50.2686, 12.9971, 50.4561), + SIMD4(12.9971, 50.4561, 14.9938, 51.0144), + SIMD4(14.9938, 51.0144, 16.36, 50.6214), + SIMD4(16.36, 50.6214, 16.6392, 50.1021), + SIMD4(16.6392, 50.1021, 17.7022, 50.3072), + SIMD4(17.7022, 50.3072, 18.8322, 49.5108), + SIMD4(32.7127, 35.171, 33.9365, 34.9715), + SIMD4(33.9365, 34.9715, 32.9418, 34.5759), + SIMD4(32.9418, 34.5759, 32.3172, 34.9533), + SIMD4(32.3172, 34.9533, 32.7127, 35.171), + SIMD4(13.5779, 45.5169, 15.3395, 45.467), + SIMD4(15.3395, 45.467, 15.6359, 46.2007), + SIMD4(15.6359, 46.2007, 16.4276, 46.5244), + SIMD4(16.4276, 46.5244, 17.8071, 45.7904), + SIMD4(17.8071, 45.7904, 18.9054, 45.9317), + SIMD4(18.9054, 45.9317, 19.4, 45.2125), + SIMD4(19.4, 45.2125, 19.0096, 44.9194), + SIMD4(19.0096, 44.9194, 15.7881, 45.179), + SIMD4(15.7881, 45.179, 17.5852, 42.9384), + SIMD4(17.5852, 42.9384, 15.9855, 43.5198), + SIMD4(15.9855, 43.5198, 14.5505, 45.2977), + SIMD4(14.5505, 45.2977, 13.8607, 44.8374), + SIMD4(13.8607, 44.8374, 13.5779, 45.5169), + SIMD4(28.0145, 41.969, 26.6153, 41.9649), + SIMD4(26.6153, 41.9649, 25.9233, 41.3119), + SIMD4(25.9233, 41.3119, 22.916, 41.3363), + SIMD4(22.916, 41.3363, 22.4721, 42.5433), + SIMD4(22.4721, 42.5433, 22.9769, 43.188), + SIMD4(22.9769, 43.188, 22.3696, 43.7813), + SIMD4(22.3696, 43.7813, 22.7051, 44.2378), + SIMD4(22.7051, 44.2378, 22.919, 43.8345), + SIMD4(22.919, 43.8345, 25.4971, 43.6708), + SIMD4(25.4971, 43.6708, 27.0869, 44.1674), + SIMD4(27.0869, 44.1674, 28.5854, 43.7422), + SIMD4(28.5854, 43.7422, 27.4848, 42.4681), + SIMD4(27.4848, 42.4681, 28.0145, 41.969), + SIMD4(19.3486, 44.8809, 19.48, 43.5952), + SIMD4(19.48, 43.5952, 18.9507, 43.5267), + SIMD4(18.9507, 43.5267, 18.4539, 42.5645), + SIMD4(18.4539, 42.5645, 17.6676, 42.8971), + SIMD4(17.6676, 42.8971, 15.7366, 44.7658), + SIMD4(15.7366, 44.7658, 15.7881, 45.179), + SIMD4(15.7881, 45.179, 19.3486, 44.8809), + SIMD4(4.2262, 51.3865, 5.7965, 51.1531), + SIMD4(5.7965, 51.1531, 5.6395, 50.8436), + SIMD4(5.6395, 50.8436, 6.3409, 50.4518), + SIMD4(6.3409, 50.4518, 5.5073, 49.5109), + SIMD4(5.5073, 49.5109, 2.5249, 51.0971), + SIMD4(2.5249, 51.0971, 4.2262, 51.3865), + SIMD4(31.7634, 52.1011, 30.7553, 51.8952), + SIMD4(30.7553, 51.8952, 30.5445, 51.265), + SIMD4(30.5445, 51.265, 25.7857, 51.9238), + SIMD4(25.7857, 51.9238, 23.6053, 51.5179), + SIMD4(23.6053, 51.5179, 23.1751, 52.2866), + SIMD4(23.1751, 52.2866, 23.9154, 52.7703), + SIMD4(23.9154, 52.7703, 23.4847, 53.9398), + SIMD4(23.4847, 53.9398, 25.7492, 54.157), + SIMD4(25.7492, 54.157, 25.6203, 54.4604), + SIMD4(25.6203, 54.4604, 26.7757, 55.2731), + SIMD4(26.7757, 55.2731, 26.5936, 55.6675), + SIMD4(26.5936, 55.6675, 28.032, 56.1333), + SIMD4(28.032, 56.1333, 30.4563, 55.7868), + SIMD4(30.4563, 55.7868, 30.9068, 55.57), + SIMD4(30.9068, 55.57, 31.0748, 54.4918), + SIMD4(31.0748, 54.4918, 32.7064, 53.4194), + SIMD4(32.7064, 53.4194, 31.2588, 53.0167), + SIMD4(31.2588, 53.0167, 31.7634, 52.1011), + SIMD4(9.5275, 47.2708, 13.0144, 47.4781), + SIMD4(13.0144, 47.4781, 12.8143, 48.1608), + SIMD4(12.8143, 48.1608, 14.9935, 49.0011), + SIMD4(14.9935, 49.0011, 16.9488, 48.5886), + SIMD4(16.9488, 48.5886, 17.0666, 47.7076), + SIMD4(17.0666, 47.7076, 16.4213, 47.6745), + SIMD4(16.4213, 47.6745, 16.4534, 47.0068), + SIMD4(16.4534, 47.0068, 14.5498, 46.3997), + SIMD4(14.5498, 46.3997, 12.4792, 46.6725), + SIMD4(12.4792, 46.6725, 12.1694, 47.0821), + SIMD4(12.1694, 47.0821, 10.1335, 46.8515), + SIMD4(10.1335, 46.8515, 9.5275, 47.2708), + SIMD4(19.3424, 41.8691, 19.7034, 42.6479), + SIMD4(19.7034, 42.6479, 20.4854, 42.2234), + SIMD4(20.4854, 42.2234, 20.9502, 40.4944), + SIMD4(20.9502, 40.4944, 20.0013, 39.7094), + SIMD4(20.0013, 39.7094, 19.3223, 40.4071), + SIMD4(19.3223, 40.4071, 19.3424, 41.8691), + ] +} diff --git a/Sources/Retrolemetry/Rendering.swift b/Sources/Retrolemetry/Rendering.swift new file mode 100644 index 0000000..b0f0d87 --- /dev/null +++ b/Sources/Retrolemetry/Rendering.swift @@ -0,0 +1,228 @@ +import AppKit +import SwiftUI + +/// The console window owns this state; hiding or sleeping must stop its animation clocks. +@MainActor +final class ConsoleRenderState: ObservableObject { + @Published var isRendering = false +} +enum ConsoleAnimationEpoch { + static let uptime = ProcessInfo.processInfo.systemUptime +} + +/// The native and SwiftUI layers share one start time and easing curve. +struct ConsoleTransitionMotion { + let start: Double + let duration: Double + let style: SceneTransitionStyle + let direction: Int + let incoming: Bool + + func uniforms(at time: Double) -> SIMD4 { + let t = min(1, max(0, (time - start) / duration)) + return SIMD4(Float(Self.ease(t)), Float(SceneTransitionStyle.allCases.firstIndex(of: style) ?? 0), incoming ? 1 : 0, direction >= 0 ? 1 : -1) + } + static func ease(_ t: Double) -> Double { + // Invert the x component of cubic(0.30, 0.02, 0.18, 1). + func curve(_ u: Double, _ a: Double, _ b: Double) -> Double { + 3 * (1-u) * (1-u) * u * a + 3 * (1-u) * u * u * b + u*u*u + } + var low = 0.0, high = 1.0 + for _ in 0..<20 { + let middle = (low + high) / 2 + if curve(middle, 0.30, 0.18) < t { low = middle } else { high = middle } + } + return t <= 0 ? 0 : t >= 1 ? 1 : curve((low+high)/2, 0.02, 1) + } +} + +/// Interpolate once and hand the exact same progress to text masks and native vectors. +struct ConsoleTransitionSurface: View, Animatable { + var progress: CGFloat + @ViewBuilder let content: (CGFloat) -> Content + var animatableData: CGFloat { get { progress } set { progress = newValue } } + var body: some View { content(progress).transaction { $0.animation = nil } } +} + +private struct ConsoleAnimationEnabledKey: EnvironmentKey { + static let defaultValue = false +} + +private struct ConsoleAnimationPausedKey: EnvironmentKey { + static let defaultValue = false +} + +private struct ConsoleFrameRateKey: EnvironmentKey { + static let defaultValue = 30.0 +} +private struct ConsoleGPUVectorsKey: EnvironmentKey { + static let defaultValue = false +} + +extension EnvironmentValues { + var consoleGPUVectors: Bool { + get { self[ConsoleGPUVectorsKey.self] } + set { self[ConsoleGPUVectorsKey.self] = newValue } + } + var consoleAnimationEnabled: Bool { + get { self[ConsoleAnimationEnabledKey.self] } + set { self[ConsoleAnimationEnabledKey.self] = newValue } + } + var consoleAnimationPaused: Bool { + get { self[ConsoleAnimationPausedKey.self] } + set { self[ConsoleAnimationPausedKey.self] = newValue } + } + var consoleFrameRate: Double { + get { self[ConsoleFrameRateKey.self] } + set { self[ConsoleFrameRateKey.self] = newValue } + } +} + +/// Put a clock around the moving element, never around a whole scene of text and graphs. +/// Layout previews keep their supplied time and do not create an animation clock. +struct ConsoleTimeline: View { + let time: Double + var interval: Double? = nil + @ViewBuilder let content: (Double) -> Content + @Environment(\.consoleAnimationEnabled) private var enabled + @Environment(\.consoleAnimationPaused) private var paused + @Environment(\.consoleFrameRate) private var frameRate + + var body: some View { + if enabled { + TimelineView(.animation(minimumInterval: interval ?? 1 / max(15, min(60, frameRate)), paused: paused)) { tick in + content(tick.date.timeIntervalSinceReferenceDate) + } + } else { + content(time) + } + } +} + +enum CRTTubeGeometry { + static func sourcePoint(for point: CGPoint, size: CGSize, strength: Double) -> CGPoint { + guard size.width > 0, size.height > 0 else { return point } + let x = point.x / size.width * 2 - 1 + let y = point.y / size.height * 2 - 1 + let amount = CGFloat(min(1, max(0, strength))) * 0.18 + return CGPoint( + x: (x * (1 + amount * y * y) + 1) * size.width / 2, + y: (y * (1 + amount * x * x) + 1) * size.height / 2 + ) + } +} + +/// Integrate the smoothed metric analytically. Animation reads this value without +/// writing SwiftUI state every frame (which used to redraw the scope twice). +struct SignalGridMotion { + struct Frame { + var travel = 0.0 + var wave = 0.0 + var metric = 0.0 + } + private var anchor = Frame() + private var time = 0.0 + private var target = 0.0 + private var response = SignalGridResponse.medium + private var animated = false + + init() {} + init(time: Double, metric: Double, response: SignalGridResponse, animated: Bool) { + self.time = time + anchor.metric = metric + target = metric + self.response = response + self.animated = animated + } + + func sample(at now: Double) -> Frame { + guard animated else { return anchor } + let elapsed = max(0, now - time) + let decay = exp(-elapsed * response.smoothingRate) + let integral = target * elapsed + (anchor.metric - target) * (1 - decay) / response.smoothingRate + return Frame( + travel: anchor.travel + (0.020 * elapsed + integral * 0.12) * response.multiplier, + wave: anchor.wave + (0.25 * elapsed + integral * 1.30) * response.multiplier, + metric: target + (anchor.metric - target) * decay + ) + } + + mutating func retarget(at now: Double, metric: Double, response: SignalGridResponse, animated: Bool) { + anchor = sample(at: now) + time = now + target = metric + if !animated { anchor.metric = metric } + self.response = response + self.animated = animated + } +} + +enum ConsoleMetalLibrary { + // The packager compiles this once. Loading the GPU library never happens per frame. + static let url: URL? = { + let resource = Bundle.main.url(forResource: "default", withExtension: "metallib") + let sidecar = Bundle.main.executableURL?.deletingLastPathComponent().appendingPathComponent("default.metallib") + guard let url = [resource, sidecar].compactMap({ $0 }).first(where: { + FileManager.default.fileExists(atPath: $0.path) + }) else { return nil } + return url + }() + static let library: ShaderLibrary? = url.map { ShaderLibrary(url: $0) } +} + +struct CRTTubeEffect: ViewModifier { + static var isAvailable: Bool { ConsoleMetalLibrary.library != nil } + let enabled: Bool + let strength: Double + var size = CGSize(width: 960, height: 540) + var opaqueBackground = true + + @ViewBuilder + func body(content: Content) -> some View { + if let library = ConsoleMetalLibrary.library, enabled, strength > 0.001 { + let amount = min(1, max(0, strength)) + content + .compositingGroup() + .distortionEffect( + library.crtTube(.float2(size), .float(amount)), + maxSampleOffset: CGSize(width: size.width * amount * 0.09, height: size.height * amount * 0.09) + ) + .clipped() + .background(opaqueBackground ? Color.black : Color.clear) + } else { + content + } + } +} + +/// Small reusable alpha textures replace hundreds of individual grain draws per frame. +enum CRTNoiseTextures { + struct Frame { + let phosphor: CGImage + let white: CGImage + } + + static let frames: [Frame] = (0..<12).compactMap { frame in + func texture(white: Bool) -> CGImage? { + guard let context = CGContext( + data: nil, width: 960, height: 540, + bitsPerComponent: 8, bytesPerRow: 960 * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue + ) else { return nil } + context.setShouldAntialias(false) + context.setFillColor(red: 1, green: 1, blue: 1, alpha: 1) + for index in 0..<820 where index.isMultiple(of: 5) == white { + let hash = (index &* 73_856_093) ^ (frame &* 19_349_663) + let positive = hash & 0x7fff_ffff + let x = (positive &* 37) % 960 + let y = (positive &* 91 + index &* 17) % 540 + let width = index.isMultiple(of: 7) ? 2.5 : 1.0 + context.fill(CGRect(x: Double(x), y: Double(y), width: width, height: 1)) + } + return context.makeImage() + } + guard let phosphor = texture(white: false), let white = texture(white: true) else { return nil } + return Frame(phosphor: phosphor, white: white) + } +} diff --git a/Sources/Retrolemetry/RetrolemetryApp.swift b/Sources/Retrolemetry/RetrolemetryApp.swift new file mode 100644 index 0000000..985414d --- /dev/null +++ b/Sources/Retrolemetry/RetrolemetryApp.swift @@ -0,0 +1,1026 @@ +import AppKit +import SwiftUI +import CoreGraphics +import ServiceManagement +import Sparkle + +@main +enum RetrolemetryApp { + @MainActor private static var retainedDelegate: AppDelegate? + + @MainActor + static func main() { + let application = NSApplication.shared + let delegate = AppDelegate() + retainedDelegate = delegate + application.delegate = delegate + application.run() + } +} + +struct OutputResolutionPreset: Identifiable { + let id: String + let title: String + let size: CGSize? + + static let matchDisplay = OutputResolutionPreset(id: "display", title: "Match selected display (Recommended)", size: nil) + static let custom = OutputResolutionPreset(id: "custom", title: "Custom size", size: nil) + static let all: [OutputResolutionPreset] = [ + matchDisplay, + .init(id: "960x540", title: "960 × 540 — novelty display", size: .init(width: 960, height: 540)), + .init(id: "1280x720", title: "1280 × 720 — HD Mac/display", size: .init(width: 1280, height: 720)), + .init(id: "1440x900", title: "1440 × 900 — Mac 16:10", size: .init(width: 1440, height: 900)), + .init(id: "1680x1050", title: "1680 × 1050 — Mac 16:10", size: .init(width: 1680, height: 1050)), + .init(id: "1920x1080", title: "1920 × 1080 — Full HD", size: .init(width: 1920, height: 1080)), + .init(id: "2560x1600", title: "2560 × 1600 — Mac Retina 16:10", size: .init(width: 2560, height: 1600)), + .init(id: "2560x1440", title: "2560 × 1440 — QHD", size: .init(width: 2560, height: 1440)), + .init(id: "3840x2160", title: "3840 × 2160 — 4K", size: .init(width: 3840, height: 2160)), + .init(id: "1024x768", title: "1024 × 768 — iPad 4:3", size: .init(width: 1024, height: 768)), + .init(id: "1366x1024", title: "1366 × 1024 — iPad landscape", size: .init(width: 1366, height: 1024)), + .init(id: "2048x1536", title: "2048 × 1536 — iPad Retina", size: .init(width: 2048, height: 1536)), + .init(id: "2732x2048", title: "2732 × 2048 — large iPad", size: .init(width: 2732, height: 2048)), + .init(id: "844x390", title: "844 × 390 — phone landscape", size: .init(width: 844, height: 390)), + .init(id: "932x430", title: "932 × 430 — large phone landscape", size: .init(width: 932, height: 430)), + custom + ] + + static func find(_ id: String) -> OutputResolutionPreset { + all.first(where: { $0.id == id }) ?? matchDisplay + } +} + +struct SettingsView: View { + @ObservedObject private var appUpdater = AppUpdater.shared + private enum Page: String, CaseIterable, Identifiable { + case general = "General" + case layout = "Layout Editor" + var id: String { rawValue } + } + + @ObservedObject private var layouts = LayoutStore.shared + @AppStorage("DockTelemetry.cycleDuration") private var cycleDuration = 30.0 + @AppStorage("DockTelemetry.automaticCycleEnabled") private var automaticCycleEnabled = true + @AppStorage("DockTelemetry.sceneOrder") private var sceneOrderRaw = SceneOrder.defaultValue + @AppStorage("DockTelemetry.coverMenuBar") private var coverMenuBar = true + @AppStorage("DockTelemetry.crtEnabled") private var crtEnabled = true + @AppStorage("DockTelemetry.animationFrameRate") private var animationFrameRate = 30.0 + @AppStorage("DockTelemetry.crtTubeEnabled") private var crtTubeEnabled = false + @AppStorage("DockTelemetry.crtTubeStrength") private var crtTubeStrength = 0.35 + @AppStorage("DockTelemetry.bloomStrength") private var bloomStrength = 0.72 + @AppStorage("DockTelemetry.scanlineStrength") private var scanlineStrength = 0.22 + @AppStorage("DockTelemetry.noiseStrength") private var noiseStrength = 0.32 + @AppStorage("DockTelemetry.vhsTrackingEnabled") private var vhsTrackingEnabled = true + @AppStorage("DockTelemetry.trackingLine1Thickness") private var trackingLine1Thickness = 1.5 + @AppStorage("DockTelemetry.trackingLine2Thickness") private var trackingLine2Thickness = 8.0 + @AppStorage("DockTelemetry.phosphorBackgroundTint") private var phosphorBackgroundTint = 0.12 + @AppStorage("DockTelemetry.visualStyle") private var visualStyleRaw = ConsoleStyle.phosphor.rawValue + @AppStorage("DockTelemetry.sceneTransitionStyle") private var transitionStyleRaw = SceneTransitionStyle.pan.rawValue + @AppStorage("DockTelemetry.marketSymbols") private var marketSymbols = MarketSymbols.defaultValue + @AppStorage("DockTelemetry.marketClock1") private var marketClock1 = "America/New_York" + @AppStorage("DockTelemetry.marketClock2") private var marketClock2 = "America/Los_Angeles" + @AppStorage("DockTelemetry.marketClock3") private var marketClock3 = "Europe/London" + @AppStorage("DockTelemetry.weatherForecastDays") private var weatherForecastDays = 5 + @AppStorage("DockTelemetry.outputResolutionPreset") private var outputResolutionPreset = OutputResolutionPreset.matchDisplay.id + @AppStorage("DockTelemetry.customOutputWidth") private var customOutputWidth = 960 + @AppStorage("DockTelemetry.customOutputHeight") private var customOutputHeight = 540 + @State private var selectedDisplayID = 0 + @State private var displaySelectionLoaded = false + @State private var displayRefresh = UUID() + @State private var launchAtLogin = false + @State private var launchError: String? + @State private var exportMessage: String? + @State private var marketKeyDraft = "" + @State private var marketKeyConfigured = false + @State private var marketCredentialMessage: String? + @State private var cycleDurationDraft = "" + @State private var typographyScene: ConsoleScene = .system + @State private var page: Page = .general + + private func typographyBinding(_ role: ConsoleFontRole) -> Binding { + Binding(get: { layouts.typography(for: typographyScene)[role] }, + set: { layouts.setFontScale($0, role: role, scene: typographyScene) }) + } + + private var screens: [NSScreen] { + _ = displayRefresh + return NSScreen.screens.sorted { + if $0.displayID == NSScreen.main?.displayID { return true } + if $1.displayID == NSScreen.main?.displayID { return false } + return $0.localizedName < $1.localizedName + } + } + + @ViewBuilder private var marketClockOptions: some View { + ForEach(MarketClockZone.options) { zone in + Text(zone.title).tag(zone.id) + } + } + + var body: some View { + VStack(spacing: 0) { + HStack { + Picker("Settings page", selection: $page) { + ForEach(Page.allCases) { page in + Text(page.rawValue).tag(page) + } + } + .labelsHidden() + .pickerStyle(.segmented) + .frame(width: 300) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + .background(.bar) + + Divider() + + if page == .general { + Form { + Section("Display") { + Picker("Default display", selection: $selectedDisplayID) { + Text("Automatic — smallest external display").tag(0) + ForEach(screens, id: \.displayID) { screen in + Text(screen.displayLabel).tag(Int(screen.displayID)) + } + } + .onChange(of: selectedDisplayID) { + guard displaySelectionLoaded else { return } + saveDisplaySelection(selectedDisplayID) + } + Toggle("Cover the menu bar on the dock display", isOn: $coverMenuBar) + Picker("Console size", selection: $outputResolutionPreset) { + ForEach(OutputResolutionPreset.all) { preset in + Text(preset.title).tag(preset.id) + } + } + if outputResolutionPreset == OutputResolutionPreset.custom.id { + HStack { + TextField("Width", value: $customOutputWidth, format: .number) + Text("×") + TextField("Height", value: $customOutputHeight, format: .number) + } + .frame(maxWidth: 320) + .onChange(of: customOutputWidth) { customOutputWidth = min(7680, max(320, customOutputWidth)) } + .onChange(of: customOutputHeight) { customOutputHeight = min(4320, max(240, customOutputHeight)) } + } + Text("The 960×540 layout scales proportionally and is centered without stretching. Match Display works best for Macs and iPad Sidecar. Phone presets work when another app exposes the phone to macOS as an external display.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Startup") { + Toggle("Launch Retrolemetry at login", isOn: Binding( + get: { launchAtLogin }, + set: { updateLaunchAtLogin($0) } + )) + if let launchError { + Text(launchError) + .font(.caption) + .foregroundStyle(.red) + } + } + Section("Updates") { + Toggle("Automatically check for updates", isOn: Binding( + get: { appUpdater.automaticallyChecks }, + set: { appUpdater.automaticallyChecks = $0 } + )) + .disabled(!appUpdater.available) + Button("Check for Updates…") { + appUpdater.controller.checkForUpdates(nil) + } + .disabled(!appUpdater.available || !appUpdater.canCheck) + Text("Updates are downloaded securely and verified before installation. Installing an update keeps your preferences and layouts.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Automatic scenes") { + Toggle("Automatically cycle scenes", isOn: $automaticCycleEnabled) + Picker("Change scene every", selection: $cycleDuration) { + Text("15 sec").tag(15.0) + Text("30 sec").tag(30.0) + Text("60 sec").tag(60.0) + Text("3 min").tag(180.0) + } + .pickerStyle(.segmented) + .disabled(!automaticCycleEnabled) + HStack { + TextField("Custom seconds", text: $cycleDurationDraft) + .frame(width: 130) + .onSubmit { applyCustomInterval() } + Button("Apply Interval") { applyCustomInterval() } + Text("5–3600 seconds") + .font(.caption) + .foregroundStyle(.secondary) + } + .disabled(!automaticCycleEnabled) + Picker("Scene transition", selection: $transitionStyleRaw) { + ForEach(SceneTransitionStyle.allCases) { style in + Text(style.title).tag(style.rawValue) + } + } + .pickerStyle(.segmented) + Text("Slideshow order") + .font(.headline) + ForEach(Array(SceneOrder.parse(sceneOrderRaw).enumerated()), id: \.element) { index, scene in + HStack { + Text("\(index + 1). \(scene.title)") + .font(.system(.body, design: .monospaced)) + Spacer() + Button { moveSceneOrder(at: index, by: -1) } label: { + Image(systemName: "chevron.up") + } + .disabled(index == 0) + Button { moveSceneOrder(at: index, by: 1) } label: { + Image(systemName: "chevron.down") + } + .disabled(index == ConsoleScene.allCases.count - 1) + } + } + Text("When disabled, horizontal mouse scrolling and keys 1–4 still change scenes.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Live market data") { + TextField("Symbols", text: $marketSymbols) + .font(.system(.body, design: .monospaced)) + HStack { + Button("Apply Symbols") { applyMarketSymbols() } + Text("Up to 12 symbols; the first five appear in ticker A and the next five in ticker B.") + .font(.caption) + .foregroundStyle(.secondary) + } + SecureField(marketKeyConfigured ? "Paste a replacement Finnhub API key" : "Finnhub API key", text: $marketKeyDraft) + HStack { + Button(marketKeyConfigured ? "Replace API Key" : "Save API Key") { saveMarketKey() } + .disabled(marketKeyDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + if marketKeyConfigured { + Button("Remove API Key", role: .destructive) { removeMarketKey() } + } + Text(marketKeyConfigured ? "KEYCHAIN: CONFIGURED" : "KEYCHAIN: NOT CONFIGURED") + .font(.system(.caption2, design: .monospaced).weight(.bold)) + .foregroundStyle(marketKeyConfigured ? Color.green : Color.secondary) + } + if let marketCredentialMessage { + Text(marketCredentialMessage) + .font(.caption) + .foregroundStyle(.secondary) + } + Text("The API key is stored in macOS Keychain, never in preferences or settings backups. Quotes are requested directly from Finnhub every 12 seconds.") + .font(.caption) + .foregroundStyle(.secondary) + Picker("Clock 1", selection: $marketClock1) { marketClockOptions } + Picker("Clock 2", selection: $marketClock2) { marketClockOptions } + Picker("Clock 3", selection: $marketClock3) { marketClockOptions } + Text("World clocks automatically follow each location's daylight-saving rules.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Weather forecast") { + WeatherRegionPicker() + Text("Automatic chooses Israel, North America or Europe from the existing location permission. Manual selection works without permission and changes only the radar map, not your local hourly/daily forecast.") + .font(.caption).foregroundStyle(.secondary) + Stepper("Daily outlook: \(weatherForecastDays) days", value: $weatherForecastDays, in: 3...7) + Text("The weather screen always shows the next 12 hourly points plus the selected number of daily forecast rows.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Typography") { + Toggle("Apply to all views", isOn: $layouts.globalTypographyEnabled) + if !layouts.globalTypographyEnabled { + Picker("View", selection: $typographyScene) { + ForEach(ConsoleScene.allCases, id: \.self) { Text($0.tabTitle).tag($0) } + } + .pickerStyle(.segmented) + } + ForEach(ConsoleFontRole.allCases, id: \.self) { role in + LabeledContent(role.title) { + Slider(value: typographyBinding(role), in: (role == .primary ? 0.75 : 0.65)...3.0).frame(width: 240) + Text("\(Int(layouts.typography(for: typographyScene)[role] * 100))%") + .monospacedDigit().frame(width: 44) + } + } + Text("Dark texts controls all dim, less-phosphorescent text—including labels and titles. Main text controls bright labels and names.") + .font(.caption).foregroundStyle(.secondary) + } + Section("Visual style") { + Toggle("Synthwave colors", isOn: Binding( + get: { visualStyleRaw == ConsoleStyle.synthwave.rawValue }, + set: { visualStyleRaw = $0 ? ConsoleStyle.synthwave.rawValue : ConsoleStyle.phosphor.rawValue } + )) + HStack { + Text(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? "CYAN / MAGENTA / MIDNIGHT" : "GREEN PHOSPHOR / BLACK") + .font(.system(.caption, design: .monospaced).weight(.bold)) + Spacer() + Circle() + .fill(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? Color.cyan : Color.green) + .frame(width: 10, height: 10) + Circle() + .fill(visualStyleRaw == ConsoleStyle.synthwave.rawValue ? Color.pink : Color.green.opacity(0.45)) + .frame(width: 10, height: 10) + } + if visualStyleRaw == ConsoleStyle.phosphor.rawValue { + LabeledContent("Green background tint") { + Slider(value: $phosphorBackgroundTint, in: 0...1) + .frame(width: 220) + } + Text("Zero is true black; maximum adds a deep green phosphor wash.") + .font(.caption) + .foregroundStyle(.secondary) + } + Toggle("Bloom, scanlines, noise, and vignette", isOn: $crtEnabled) + if crtEnabled { + LabeledContent("Bloom") { + Slider(value: $bloomStrength, in: 0...1).frame(width: 220) + } + LabeledContent("Scanlines") { + Slider(value: $scanlineStrength, in: 0...1).frame(width: 220) + } + LabeledContent("Noise") { + Slider(value: $noiseStrength, in: 0...1).frame(width: 220) + } + Toggle("Moving VHS tracking lines", isOn: $vhsTrackingEnabled) + if vhsTrackingEnabled { + LabeledContent("Line 1 thickness") { + Slider(value: $trackingLine1Thickness, in: 0.5...18).frame(width: 220) + } + Text(String(format: "%.1f px", trackingLine1Thickness)) + .font(.system(.caption2, design: .monospaced)) + .foregroundStyle(.secondary) + LabeledContent("Line 2 thickness") { + Slider(value: $trackingLine2Thickness, in: 1...36).frame(width: 220) + } + Text(String(format: "%.1f px", trackingLine2Thickness)) + .font(.system(.caption2, design: .monospaced)) + .foregroundStyle(.secondary) + } + } + Toggle("CRT tube curvature", isOn: $crtTubeEnabled) + .disabled(!CRTTubeEffect.isAvailable) + LabeledContent("Curvature strength") { + Slider(value: $crtTubeStrength, in: 0...1).frame(width: 220) + Text("\(Int(crtTubeStrength * 100))%") + .monospacedDigit().frame(width: 40, alignment: .trailing) + } + .disabled(!crtTubeEnabled || !CRTTubeEffect.isAvailable) + if !CRTTubeEffect.isAvailable { + Text("Use a packaged app build to enable CRT curvature.") + .font(.caption).foregroundStyle(.secondary) + } + Text("Curves every live scene. The layout editor stays flat for precise positioning.") + .font(.caption) + .foregroundStyle(.secondary) + Text("The selected style applies to every telemetry, weather, and vector scene.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Performance") { + Picker("Animation frame rate", selection: $animationFrameRate) { + Text("15 fps — lower CPU use").tag(15.0) + Text("30 fps — balanced").tag(30.0) + Text("60 fps — smoother, higher CPU use").tag(60.0) + } + Text("Vectors and CRT effects use small native GPU layers; text and readings do not redraw every animation frame. CPU, GPU, memory, and network update once a second; battery power every 5 seconds and disk space every 30 seconds. Hidden or sleeping output does not render scenes.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section("Settings backup") { + Button("Export Settings Backup…") { exportSettings() } + if let exportMessage { + Text(exportMessage).font(.caption).foregroundStyle(.secondary) + } + Text("Exports layouts, module visibility, display choice, market symbols, typography, slideshow, visual style, CRT, and radar calibration. API keys are never exported.") + .font(.caption) + .foregroundStyle(.secondary) + } + Section { + Text("Keys 1–4 choose a scene. Press 0 or A to resume cycling when automatic scenes are enabled. Horizontal mouse scrolling always moves between scenes.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .formStyle(.grouped) + } else { + LayoutEditorView() + } + } + .frame(minWidth: 1040, maxWidth: .infinity, minHeight: 720, maxHeight: .infinity, alignment: .top) + .onAppear { + displaySelectionLoaded = false + if let restored = DisplayPreference.savedScreen() { + selectedDisplayID = Int(restored.displayID) + } else { + selectedDisplayID = 0 + } + DispatchQueue.main.async { displaySelectionLoaded = true } + launchAtLogin = SMAppService.mainApp.status == .enabled + marketKeyConfigured = MarketKeychain.apiKey() != nil + cycleDurationDraft = String(format: "%.0f", cycleDuration) + } + .onChange(of: cycleDuration) { + cycleDurationDraft = String(format: "%.0f", cycleDuration) + } + .onReceive(NotificationCenter.default.publisher(for: NSApplication.didChangeScreenParametersNotification)) { _ in + displayRefresh = UUID() + } + } + + private func saveDisplaySelection(_ id: Int) { + guard id != 0, + let screen = NSScreen.screens.first(where: { Int($0.displayID) == id }) else { + DisplayPreference.clear() + return + } + DisplayPreference.save(screen) + } + + private func applyMarketSymbols() { + let parsed = MarketSymbols.parse(marketSymbols) + marketSymbols = (parsed.isEmpty ? MarketSymbols.parse(MarketSymbols.defaultValue) : parsed).joined(separator: ", ") + NotificationCenter.default.post(name: .marketConfigurationDidChange, object: nil) + marketCredentialMessage = "Market symbols updated." + } + + private func applyCustomInterval() { + guard let value = Double(cycleDurationDraft.trimmingCharacters(in: .whitespacesAndNewlines)) else { + cycleDurationDraft = String(format: "%.0f", cycleDuration) + return + } + cycleDuration = min(3600, max(5, value)) + cycleDurationDraft = String(format: "%.0f", cycleDuration) + } + + private func moveSceneOrder(at index: Int, by offset: Int) { + var scenes = SceneOrder.parse(sceneOrderRaw) + let destination = index + offset + guard scenes.indices.contains(index), scenes.indices.contains(destination) else { return } + scenes.swapAt(index, destination) + sceneOrderRaw = SceneOrder.encode(scenes) + } + + private func saveMarketKey() { + do { + try MarketKeychain.save(apiKey: marketKeyDraft) + marketKeyDraft = "" + marketKeyConfigured = true + marketCredentialMessage = "Finnhub API key saved securely." + } catch { + marketCredentialMessage = "Could not save the API key: \(error.localizedDescription)" + } + } + + private func removeMarketKey() { + MarketKeychain.delete() + marketKeyDraft = "" + marketKeyConfigured = false + marketCredentialMessage = "Finnhub API key removed." + } + + private func updateLaunchAtLogin(_ enabled: Bool) { + launchError = nil + do { + if enabled { + try SMAppService.mainApp.register() + } else { + try SMAppService.mainApp.unregister() + } + launchAtLogin = SMAppService.mainApp.status == .enabled + } catch { + launchAtLogin = SMAppService.mainApp.status == .enabled + launchError = "macOS could not update Login Items: \(error.localizedDescription)" + } + } + + private func exportSettings() { + let panel = NSSavePanel() + panel.title = "Export Retrolemetry Settings" + panel.nameFieldStringValue = "Retrolemetry-Settings-Backup.plist" + let completion: (NSApplication.ModalResponse) -> Void = { response in + guard response == .OK, let url = panel.url else { return } + saveSettingsBackup(to: url) + } + if let parent = NSApp.keyWindow { + panel.beginSheetModal(for: parent, completionHandler: completion) + } else { + completion(panel.runModal()) + } + } + + private func saveSettingsBackup(to url: URL) { + let bundleID = Bundle.main.bundleIdentifier ?? "io.github.SamSpring.Retrolemetry" + var values = UserDefaults.standard.persistentDomain(forName: bundleID) ?? [:] + values = values.filter { $0.key.hasPrefix("DockTelemetry.") } + values["DockTelemetry.backupFormat"] = 1 + values["DockTelemetry.backupCreatedAt"] = Date() + do { + let data = try PropertyListSerialization.data(fromPropertyList: values, format: .xml, options: 0) + try data.write(to: url, options: .atomic) + exportMessage = "Saved \(url.lastPathComponent)" + } catch { + exportMessage = "Export failed: \(error.localizedDescription)" + } + } +} + +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { + private let appUpdater = AppUpdater.shared + private var controller: DisplayWindowController? + private var settingsController: SettingsWindowController? + private var statusItem: NSStatusItem? + private weak var consoleMenuItem: NSMenuItem? + private weak var styleMenuItem: NSMenuItem? + + func applicationDidFinishLaunching(_ notification: Notification) { + migrateLegacyPreferences() + // Keep the legacy key namespace so early-build settings survive the public rename. + UserDefaults.standard.register(defaults: [ + "DockTelemetry.cycleDuration": 30.0, + "DockTelemetry.automaticCycleEnabled": true, + "DockTelemetry.sceneOrder": SceneOrder.defaultValue, + "DockTelemetry.coverMenuBar": true, + "DockTelemetry.crtEnabled": true, + "DockTelemetry.animationFrameRate": 30.0, + "DockTelemetry.crtTubeEnabled": false, + "DockTelemetry.crtTubeStrength": 0.35, + "DockTelemetry.signalDisplayMode": SignalDisplayMode.spinning.rawValue, + "DockTelemetry.bloomStrength": 0.80466796875, + "DockTelemetry.scanlineStrength": 0.8629296875, + "DockTelemetry.noiseStrength": 0.82953125, + "DockTelemetry.vhsTrackingEnabled": true, + "DockTelemetry.trackingLine1Thickness": 1.5, + "DockTelemetry.trackingLine2Thickness": 8.0, + "DockTelemetry.phosphorBackgroundTint": 0.3661328125, + "DockTelemetry.globeWidthCorrection": 1.10, + "DockTelemetry.globeHeightCorrection": 0.9254256185, + "DockTelemetry.radarWidthCorrection": 1.10, + "DockTelemetry.radarHeightCorrection": 0.9254256185, + "DockTelemetry.radarTargetMode": RadarTargetMode.precipitation.rawValue, + "DockTelemetry.radarTargetPulse": true, + "DockTelemetry.signalSynthwaveGrid": false, + "DockTelemetry.signalGridAnimationEnabled": true, + "DockTelemetry.signalGridMetric": SignalGridMetric.cpu.rawValue, + "DockTelemetry.signalGridPattern": SignalGridPattern.recede.rawValue, + "DockTelemetry.signalGridResponse": SignalGridResponse.medium.rawValue, + "DockTelemetry.layoutSnapEnabled": false, + "DockTelemetry.layoutSnapStep": 10.0, + "DockTelemetry.outputResolutionPreset": OutputResolutionPreset.matchDisplay.id, + "DockTelemetry.customOutputWidth": 960, + "DockTelemetry.customOutputHeight": 540, + "DockTelemetry.fontScale": 1.45, + "DockTelemetry.secondaryFontScale": 1.0, + "DockTelemetry.auxiliaryFontScale": 1.0, + "DockTelemetry.sceneTransitionStyle": SceneTransitionStyle.pan.rawValue, + "DockTelemetry.marketSymbols": MarketSymbols.defaultValue, + "DockTelemetry.marketClock1": "America/New_York", + "DockTelemetry.marketClock2": "America/Los_Angeles", + "DockTelemetry.marketClock3": "Europe/London", + "DockTelemetry.weatherForecastDays": 5, + "DockTelemetry.visualStyle": ConsoleStyle.phosphor.rawValue + ]) + NSApp.setActivationPolicy(.accessory) + installStatusItem() + controller = DisplayWindowController() + controller?.show() + installSignalToggle() + appUpdater.start() + } + + private func migrateLegacyPreferences() { + let defaults = UserDefaults.standard + for domainName in ["com.sam.docktelemetry", "DockTelemetry"] { + guard let legacyValues = defaults.persistentDomain(forName: domainName) else { continue } + for (key, value) in legacyValues where key.hasPrefix("DockTelemetry.") { + if defaults.object(forKey: key) == nil { + defaults.set(value, forKey: key) + } + } + } + } + + func applicationShouldRestoreState(_ app: NSApplication) -> Bool { false } + + private func installStatusItem() { + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) + let icon = NSImage( + systemSymbolName: "waveform.path.ecg", + accessibilityDescription: "Retrolemetry" + ) ?? NSImage( + systemSymbolName: "waveform", + accessibilityDescription: "Retrolemetry" + ) + icon?.isTemplate = true + item.button?.image = icon + item.button?.imagePosition = .imageOnly + item.button?.toolTip = "Retrolemetry" + + let menu = NSMenu() + let toggle = NSMenuItem(title: "Hide Console", action: #selector(toggleConsole), keyEquivalent: "d") + toggle.target = self + toggle.keyEquivalentModifierMask = [.command, .shift] + menu.addItem(toggle) + consoleMenuItem = toggle + let move = NSMenuItem(title: "Move to Preferred Display", action: #selector(moveConsole), keyEquivalent: "") + move.target = self + menu.addItem(move) + menu.addItem(.separator()) + let style = NSMenuItem(title: "Synthwave Colors", action: #selector(toggleVisualStyle), keyEquivalent: "s") + style.target = self + style.keyEquivalentModifierMask = [.command, .shift] + menu.addItem(style) + styleMenuItem = style + let settings = NSMenuItem(title: "Settings…", action: #selector(showSettings), keyEquivalent: ",") + settings.target = self + menu.addItem(settings) + let update = NSMenuItem(title: "Check for Updates…", action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "") + update.target = appUpdater.controller + menu.addItem(update) + menu.addItem(.separator()) + let quitItem = NSMenuItem(title: "Quit Retrolemetry", action: #selector(quit), keyEquivalent: "q") + quitItem.target = self + menu.addItem(quitItem) + menu.delegate = self + item.menu = menu + statusItem = item + updateConsoleMenuItem() + updateStyleMenuItem() + } + + private func installSignalToggle() { + signal(SIGUSR1, SIG_IGN) + signal(SIGUSR2, SIG_IGN) + let displaySource = DispatchSource.makeSignalSource(signal: SIGUSR1, queue: .main) + displaySource.setEventHandler { [weak self] in self?.toggleConsole() } + displaySource.resume() + let styleSource = DispatchSource.makeSignalSource(signal: SIGUSR2, queue: .main) + styleSource.setEventHandler { [weak self] in self?.toggleVisualStyle() } + styleSource.resume() + SignalHolder.shared.displaySource = displaySource + SignalHolder.shared.styleSource = styleSource + } + + @objc private func toggleConsole() { + controller?.toggle() + updateConsoleMenuItem() + } + @objc private func moveConsole() { controller?.moveToPreferredDisplay(force: true) } + @objc private func toggleVisualStyle() { + let defaults = UserDefaults.standard + let isSynthwave = defaults.string(forKey: "DockTelemetry.visualStyle") == ConsoleStyle.synthwave.rawValue + defaults.set( + isSynthwave ? ConsoleStyle.phosphor.rawValue : ConsoleStyle.synthwave.rawValue, + forKey: "DockTelemetry.visualStyle" + ) + updateStyleMenuItem() + } + + func menuWillOpen(_ menu: NSMenu) { + updateConsoleMenuItem() + updateStyleMenuItem() + } + + private func updateConsoleMenuItem() { + consoleMenuItem?.title = controller?.isRequestedVisible == true ? "Hide Console" : "Show Console" + } + + private func updateStyleMenuItem() { + let isSynthwave = UserDefaults.standard.string(forKey: "DockTelemetry.visualStyle") == ConsoleStyle.synthwave.rawValue + styleMenuItem?.state = isSynthwave ? .on : .off + } + + @objc private func showSettings() { + NSApp.activate(ignoringOtherApps: true) + if settingsController == nil { + settingsController = SettingsWindowController() + } + settingsController?.show() + } + @objc private func quit() { NSApp.terminate(nil) } +} + +private final class SignalHolder { + static let shared = SignalHolder() + var displaySource: DispatchSourceSignal? + var styleSource: DispatchSourceSignal? +} + +@MainActor +final class DisplayWindowController { + private let window: ConsoleWindow + private let renderState = ConsoleRenderState() + private var screenObserver: NSObjectProtocol? + private var defaultsObserver: NSObjectProtocol? + private var visibilityObserver: NSObjectProtocol? + private var sleepObservers: [NSObjectProtocol] = [] + private var displaySleeping = false + private var lastWindowSettings: [String: AnyHashable] = [:] + private var requestedVisible = true + + var isRequestedVisible: Bool { requestedVisible } + + init() { + let root = AdaptiveConsoleRoot(renderState: renderState) + window = ConsoleWindow( + contentRect: NSRect(x: 0, y: 0, width: 960, height: 540), + styleMask: [.borderless], + backing: .buffered, + defer: false + ) + window.contentView = NSHostingView(rootView: root) + window.backgroundColor = .black + window.isOpaque = true + window.hasShadow = false + window.level = Self.consoleLevel + window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary] + window.isMovableByWindowBackground = false + window.setContentSize(NSSize(width: 960, height: 540)) + + screenObserver = NotificationCenter.default.addObserver( + forName: NSApplication.didChangeScreenParametersNotification, + object: nil, + queue: .main + ) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in owner.displayConfigurationChanged() } + } + defaultsObserver = NotificationCenter.default.addObserver( + forName: UserDefaults.didChangeNotification, + object: nil, + queue: .main + ) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in + owner.applyWindowLevel() + let settings = owner.windowSettingsSnapshot() + guard settings != owner.lastWindowSettings else { return } + owner.lastWindowSettings = settings + owner.moveToPreferredDisplay(force: true) + } + } + visibilityObserver = NotificationCenter.default.addObserver( + forName: NSWindow.didChangeOcclusionStateNotification, object: window, queue: .main + ) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in owner.updateRenderingState() } + } + let workspaceCenter = NSWorkspace.shared.notificationCenter + for name in [NSWorkspace.screensDidSleepNotification, NSWorkspace.willSleepNotification] { + sleepObservers.append(workspaceCenter.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in + owner.displaySleeping = true + owner.updateRenderingState() + } + }) + } + for name in [NSWorkspace.screensDidWakeNotification, NSWorkspace.didWakeNotification] { + sleepObservers.append(workspaceCenter.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in + owner.displaySleeping = false + owner.updateRenderingState() + } + }) + } + applyWindowLevel() + lastWindowSettings = windowSettingsSnapshot() + } + + deinit { + if let screenObserver { NotificationCenter.default.removeObserver(screenObserver) } + if let defaultsObserver { NotificationCenter.default.removeObserver(defaultsObserver) } + if let visibilityObserver { NotificationCenter.default.removeObserver(visibilityObserver) } + for observer in sleepObservers { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + } + + func show() { + requestedVisible = true + if moveToPreferredDisplay(force: false) { + window.orderFrontRegardless() + } else { + window.orderOut(nil) + } + updateRenderingState() + } + + func toggle() { + if window.isVisible || requestedVisible { + requestedVisible = false + window.orderOut(nil) + updateRenderingState() + } else { + show() + } + } + + @discardableResult + func moveToPreferredDisplay(force: Bool) -> Bool { + guard let target = preferredScreen() else { + window.orderOut(nil) + updateRenderingState() + return false + } + if force || window.screen?.displayID != target.displayID || !window.isVisible { + let frame = target.frame + let size = outputSize(for: target) + let origin = NSPoint( + x: frame.midX - size.width / 2, + y: frame.midY - size.height / 2 + ) + window.setFrame(NSRect(origin: origin, size: size), display: true) + } + if requestedVisible { window.orderFrontRegardless() } + updateRenderingState() + return true + } + + private func updateRenderingState() { + let visible = requestedVisible && window.isVisible && window.occlusionState.contains(.visible) && !displaySleeping + if renderState.isRendering != visible { renderState.isRendering = visible } + } + + private func displayConfigurationChanged() { + guard requestedVisible else { return } + _ = moveToPreferredDisplay(force: true) + } + + private func applyWindowLevel() { + let level: NSWindow.Level = UserDefaults.standard.bool(forKey: "DockTelemetry.coverMenuBar") + ? Self.consoleLevel + : .normal + if window.level != level { window.level = level } + } + + private func windowSettingsSnapshot() -> [String: AnyHashable] { + let keys = [DisplayPreference.idKey, "DockTelemetry.preferredDisplayName", + "DockTelemetry.preferredDisplayWidth", "DockTelemetry.preferredDisplayHeight", + "DockTelemetry.outputResolutionPreset", "DockTelemetry.customOutputWidth", + "DockTelemetry.customOutputHeight"] + return Dictionary(uniqueKeysWithValues: keys.compactMap { key in + guard let value = UserDefaults.standard.object(forKey: key) as? AnyHashable else { return nil } + return (key, value) + }) + } + + private func outputSize(for screen: NSScreen) -> NSSize { + let defaults = UserDefaults.standard + let preset = OutputResolutionPreset.find(defaults.string(forKey: "DockTelemetry.outputResolutionPreset") ?? "display") + guard preset.id != OutputResolutionPreset.matchDisplay.id else { return screen.frame.size } + + let requested: CGSize + if preset.id == OutputResolutionPreset.custom.id { + requested = CGSize( + width: min(7680, max(320, defaults.integer(forKey: "DockTelemetry.customOutputWidth"))), + height: min(4320, max(240, defaults.integer(forKey: "DockTelemetry.customOutputHeight"))) + ) + } else { + requested = preset.size ?? CGSize(width: 960, height: 540) + } + let fit = min(1, screen.frame.width / requested.width, screen.frame.height / requested.height) + return NSSize(width: requested.width * fit, height: requested.height * fit) + } + + private static var consoleLevel: NSWindow.Level { + NSWindow.Level(rawValue: NSWindow.Level.mainMenu.rawValue + 1) + } + + private func preferredScreen() -> NSScreen? { + let stored = UserDefaults.standard.integer(forKey: DisplayPreference.idKey) + if stored != 0 { + return DisplayPreference.savedScreen() + } + + let external = NSScreen.screens.filter { CGDisplayIsBuiltin($0.displayID) == 0 } + return external.min(by: { ($0.frame.width * $0.frame.height) < ($1.frame.width * $1.frame.height) }) + ?? NSScreen.main + ?? NSScreen.screens.first + } +} + +private struct AdaptiveConsoleRoot: View { + @ObservedObject var renderState: ConsoleRenderState + var body: some View { + GeometryReader { proxy in + let scale = min(proxy.size.width / 960, proxy.size.height / 540) + ZStack { + Color.black + ConsoleView(renderState: renderState) + .frame(width: 960, height: 540) + .scaleEffect(scale) + .position(x: proxy.size.width / 2, y: proxy.size.height / 2) + } + .frame(width: proxy.size.width, height: proxy.size.height) + .clipped() + } + .background(Color.black) + } +} + +@MainActor +final class SettingsWindowController: NSObject, NSWindowDelegate { + private let window: NSWindow + + override init() { + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 1040, height: 720), + styleMask: [.titled, .closable, .resizable], + backing: .buffered, + defer: false + ) + super.init() + window.title = "Retrolemetry Settings" + window.identifier = NSUserInterfaceItemIdentifier("Retrolemetry.Settings") + window.contentView = NSHostingView(rootView: SettingsView()) + window.contentMinSize = NSSize(width: 1040, height: 720) + window.isReleasedWhenClosed = false + window.delegate = self + } + + func show() { + window.center() + window.makeKeyAndOrderFront(nil) + } +} + +enum DisplayPreference { + static let idKey = "DockTelemetry.preferredDisplayID" + private static let nameKey = "DockTelemetry.preferredDisplayName" + private static let widthKey = "DockTelemetry.preferredDisplayWidth" + private static let heightKey = "DockTelemetry.preferredDisplayHeight" + + static func save(_ screen: NSScreen) { + let defaults = UserDefaults.standard + defaults.set(Int(screen.displayID), forKey: idKey) + defaults.set(screen.localizedName, forKey: nameKey) + defaults.set(Int(screen.frame.width.rounded()), forKey: widthKey) + defaults.set(Int(screen.frame.height.rounded()), forKey: heightKey) + } + + static func clear() { + let defaults = UserDefaults.standard + [idKey, nameKey, widthKey, heightKey].forEach { defaults.removeObject(forKey: $0) } + } + + static func savedScreen() -> NSScreen? { + let defaults = UserDefaults.standard + let storedID = CGDirectDisplayID(defaults.integer(forKey: idKey)) + guard storedID != 0 else { return nil } + + if let idMatch = NSScreen.screens.first(where: { $0.displayID == storedID }), + matchesSavedIdentity(idMatch) { + return idMatch + } + guard let restored = restoredScreen() else { return nil } + save(restored) + return restored + } + + static func restoredScreen() -> NSScreen? { + let defaults = UserDefaults.standard + let name = defaults.string(forKey: nameKey) + let width = defaults.integer(forKey: widthKey) + let height = defaults.integer(forKey: heightKey) + + let exactMatches = NSScreen.screens.filter { + $0.localizedName == name && hasSize($0, width: width, height: height) + } + if exactMatches.count == 1 { return exactMatches[0] } + + if let name, !name.isEmpty { + let nameMatches = NSScreen.screens.filter { $0.localizedName == name } + if nameMatches.count == 1 { return nameMatches[0] } + } + + guard width > 0, height > 0 else { return nil } + let sizeMatches = NSScreen.screens.filter { hasSize($0, width: width, height: height) } + return sizeMatches.count == 1 ? sizeMatches[0] : nil + } + + private static func matchesSavedIdentity(_ screen: NSScreen) -> Bool { + let defaults = UserDefaults.standard + if let name = defaults.string(forKey: nameKey), !name.isEmpty { + return screen.localizedName == name + } + let width = defaults.integer(forKey: widthKey) + let height = defaults.integer(forKey: heightKey) + guard width > 0, height > 0 else { return true } + return hasSize(screen, width: width, height: height) + } + + private static func hasSize(_ screen: NSScreen, width: Int, height: Int) -> Bool { + Int(screen.frame.width.rounded()) == width && Int(screen.frame.height.rounded()) == height + } +} + +private final class ConsoleWindow: NSWindow { + override var canBecomeKey: Bool { true } +} + +extension NSScreen { + var displayID: CGDirectDisplayID { + (deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value ?? 0 + } + + var displayLabel: String { + let role = CGDisplayIsBuiltin(displayID) != 0 ? "Built-in" : "External" + return "\(localizedName) — \(Int(frame.width))×\(Int(frame.height)) (\(role))" + } +} diff --git a/Sources/DockTelemetry/Telemetry.swift b/Sources/Retrolemetry/Telemetry.swift similarity index 58% rename from Sources/DockTelemetry/Telemetry.swift rename to Sources/Retrolemetry/Telemetry.swift index 408fbe0..146f88d 100644 --- a/Sources/DockTelemetry/Telemetry.swift +++ b/Sources/Retrolemetry/Telemetry.swift @@ -10,6 +10,38 @@ struct TelemetrySnapshot { var networkOut: Double = 0 var uptime: TimeInterval = ProcessInfo.processInfo.systemUptime var load: (Double, Double, Double) = (0, 0, 0) + var gpu: Double? + var power = PowerReading() + var memoryCapacity: CapacityReading? + var diskCapacity: CapacityReading? +} + +/// Byte counts and the displayed percentage always describe the same capacity. +struct CapacityReading: Equatable { + let totalBytes: Double + let usedBytes: Double + var freeBytes: Double { totalBytes - usedBytes } + var fractionUsed: Double { usedBytes / totalBytes } + + init?(totalBytes: Double, usedBytes: Double) { + guard totalBytes.isFinite, totalBytes > 0, usedBytes.isFinite, + usedBytes >= 0, usedBytes <= totalBytes else { return nil } + self.totalBytes = totalBytes + self.usedBytes = usedBytes + } + + static func memory(active: UInt64, wired: UInt64, compressed: UInt64, + pageSize: UInt64, physicalBytes: UInt64) -> Self? { + guard pageSize > 0 else { return nil } + return Self(totalBytes: Double(physicalBytes), + usedBytes: (Double(active) + Double(wired) + Double(compressed)) * Double(pageSize)) + } +} + +func capacityAmount(_ bytes: Double?) -> String { + guard let bytes, bytes.isFinite, bytes >= 0 else { return "N/A" } + if bytes >= 1_000_000_000_000 { return String(format: "%.2f TB", bytes / 1_000_000_000_000) } + return String(format: "%.1f GB", bytes / 1_000_000_000) } @MainActor @@ -18,15 +50,23 @@ final class TelemetryModel: ObservableObject { @Published private(set) var cpuHistory: [Double] = Array(repeating: 0, count: 96) @Published private(set) var memoryHistory: [Double] = Array(repeating: 0, count: 96) @Published private(set) var networkHistory: [Double] = Array(repeating: 0, count: 96) + // Keep actual bytes/second for the duplex plot, rather than clipping to a fixed speed. + @Published private(set) var networkReceiveHistory: [Double] = Array(repeating: 0, count: 96) + @Published private(set) var networkTransmitHistory: [Double] = Array(repeating: 0, count: 96) + @Published private(set) var gpuHistory: [Double?] = Array(repeating: nil, count: 96) private var timer: Timer? private var previousCPU: (idle: UInt64, total: UInt64)? private var previousNetwork: (input: UInt64, output: UInt64, time: TimeInterval)? + private var lastDiskSample = Date.distantPast + private var lastPowerSample = Date.distantPast + private let hardware = HardwareMetricsReader() init() { sample() timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in - Task { @MainActor in self?.sample() } + guard let owner = self else { return } + Task { @MainActor in owner.sample() } } timer?.tolerance = 0.12 } @@ -34,25 +74,40 @@ final class TelemetryModel: ObservableObject { deinit { timer?.invalidate() } private func sample() { - snapshot.cpu = cpuUsage() - snapshot.memory = memoryUsage() - snapshot.disk = diskUsage() + var next = snapshot + next.cpu = cpuUsage() + next.memoryCapacity = memoryCapacity() + if let capacity = next.memoryCapacity { next.memory = capacity.fractionUsed } + next.gpu = hardware.gpuUsage() + if Date().timeIntervalSince(lastPowerSample) >= 5 { + next.power = hardware.powerReading() + lastPowerSample = Date() + } + if Date().timeIntervalSince(lastDiskSample) >= 30 { + next.diskCapacity = diskCapacity() + if let capacity = next.diskCapacity { next.disk = capacity.fractionUsed } + lastDiskSample = Date() + } let network = networkRates() - snapshot.networkIn = network.input - snapshot.networkOut = network.output - snapshot.uptime = ProcessInfo.processInfo.systemUptime + next.networkIn = network.input + next.networkOut = network.output + next.uptime = ProcessInfo.processInfo.systemUptime var averages = [Double](repeating: 0, count: 3) if getloadavg(&averages, 3) == 3 { - snapshot.load = (averages[0], averages[1], averages[2]) + next.load = (averages[0], averages[1], averages[2]) } + snapshot = next append(snapshot.cpu, to: &cpuHistory) append(snapshot.memory, to: &memoryHistory) + append(snapshot.gpu, to: &gpuHistory) append(min(1, (snapshot.networkIn + snapshot.networkOut) / 12_000_000), to: &networkHistory) + append(snapshot.networkIn, to: &networkReceiveHistory) + append(snapshot.networkOut, to: &networkTransmitHistory) } - private func append(_ value: Double, to history: inout [Double]) { + private func append(_ value: Value, to history: inout [Value]) { history.append(value) if history.count > 96 { history.removeFirst(history.count - 96) } } @@ -79,7 +134,7 @@ final class TelemetryModel: ObservableObject { return min(1, max(0, 1 - Double(idleDelta) / Double(totalDelta))) } - private func memoryUsage() -> Double { + private func memoryCapacity() -> CapacityReading? { var stats = vm_statistics64_data_t() var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) let result: kern_return_t = withUnsafeMutablePointer(to: &stats) { @@ -87,18 +142,18 @@ final class TelemetryModel: ObservableObject { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) } } - guard result == KERN_SUCCESS else { return snapshot.memory } - let used = Double(stats.active_count + stats.wire_count + stats.compressor_page_count) - let available = used + Double(stats.inactive_count + stats.free_count + stats.speculative_count) - return available > 0 ? min(1, used / available) : 0 + guard result == KERN_SUCCESS else { return nil } + return .memory(active: UInt64(stats.active_count), wired: UInt64(stats.wire_count), + compressed: UInt64(stats.compressor_page_count), pageSize: UInt64(vm_kernel_page_size), + physicalBytes: ProcessInfo.processInfo.physicalMemory) } - private func diskUsage() -> Double { + private func diskCapacity() -> CapacityReading? { guard let values = try? FileManager.default.attributesOfFileSystem(forPath: "/"), let total = values[.systemSize] as? NSNumber, let free = values[.systemFreeSize] as? NSNumber, - total.doubleValue > 0 else { return snapshot.disk } - return 1 - (free.doubleValue / total.doubleValue) + total.doubleValue > 0 else { return nil } + return CapacityReading(totalBytes: total.doubleValue, usedBytes: total.doubleValue - free.doubleValue) } private func networkRates() -> (input: Double, output: Double) { diff --git a/Sources/Retrolemetry/TelemetryPanels.swift b/Sources/Retrolemetry/TelemetryPanels.swift new file mode 100644 index 0000000..7b44286 --- /dev/null +++ b/Sources/Retrolemetry/TelemetryPanels.swift @@ -0,0 +1,178 @@ +import SwiftUI +import AppKit + +struct CapacityMetricContents: View { + @Environment(\.consoleTypography) private var typography + let label: String + let value: String + let capacity: CapacityReading? + let fit: Double + let capacityFit: Double + + var body: some View { + GeometryReader { geometry in + // Reserve the main text's actual width before distributing space to + // the side values; equal-width columns would silently shrink the percentage. + let titleWidth = (label as NSString).size(withAttributes: [.font: NSFont.monospacedSystemFont(ofSize: 13 * fit * typography.secondary, weight: .bold)]).width + let valueWidth = (value as NSString).size(withAttributes: [.font: NSFont.monospacedSystemFont(ofSize: 31 * fit * typography.primary, weight: .bold)]).width + let centerWidth = min(geometry.size.width * 0.55, max(titleWidth, valueWidth) + 6) + // Keep the compact side readings beside the bottom of the main value, + // so their headings sit close above their amounts rather than high up. + HStack(alignment: .bottom, spacing: 8 * fit) { + CapacitySideReading(title: "USED", bytes: capacity?.usedBytes, fit: capacityFit) + VStack(spacing: 8 * fit) { + Text(label).consoleFont(13 * fit, role: .secondary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.5) + Text(value).consoleFont(31 * fit, role: .primary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.45) + } + .frame(width: centerWidth) + CapacitySideReading(title: "FREE", bytes: capacity?.freeBytes, fit: capacityFit) + } + .frame(width: geometry.size.width, height: geometry.size.height) + } + } + +} + +struct CapacitySideReading: View { + let title: String + let bytes: Double? + let fit: Double + + static func compactAmount(_ bytes: Double?) -> String { + // Keep number and unit adjacent in one scalable text run. Even a thin + // space looks wide in the large monospaced readouts. N/A stays unchanged. + capacityAmount(bytes).replacingOccurrences(of: " ", with: "") + } + + var body: some View { + VStack(spacing: 1 * fit) { + Text(title).consoleFont(13 * 0.8 * fit, role: .dark, weight: .bold) + Text(Self.compactAmount(bytes)).consoleFont(20 * 0.8 * fit, role: .dark, weight: .bold) + } + .consoleDimmed() + .lineLimit(1).minimumScaleFactor(0.4) + .frame(maxWidth: .infinity) + } +} + +/// Shared header keeps every graph's trace below its title and current reading. +struct DataGraphHeader: View { + let label: String + let value: String + var valueColor: Color? = nil + + private var title: some View { + Text(label).consoleFont(13, role: .secondary, weight: .bold) + .lineLimit(1).minimumScaleFactor(0.25) + } + private var reading: some View { + Text(value).consoleFont(18, role: .primary, weight: .bold) + .foregroundStyle(valueColor ?? phosphor) + .lineLimit(1).minimumScaleFactor(0.25) + } + + var body: some View { + VStack(spacing: 0) { + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + title.fixedSize() + Spacer(minLength: 4) + reading.fixedSize() + } + VStack(alignment: .leading, spacing: 2) { + title + reading + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 9).padding(.vertical, 6) + .fixedSize(horizontal: false, vertical: true) + Rectangle().fill(dimPhosphor.opacity(0.72)).frame(height: 1) + } + } +} + +/// Same bytes/second scale on both sides; no fixed-speed ceiling or RX/TX summing. +enum NetworkHistoryGeometry { + static func scale(receive: [Double], transmit: [Double]) -> Double { + max(1_000, (receive + transmit).filter { $0.isFinite && $0 >= 0 }.max() ?? 0) + } + + static func segments(_ rates: [Double], in rect: CGRect, scale: Double, transmit: Bool) -> [[CGPoint]] { + guard rect.width > 0, rect.height > 0, scale.isFinite, scale > 0 else { return [] } + let values = rates.map { rate -> Double? in + rate.isFinite && rate >= 0 ? min(1, rate / scale) : nil + } + let segments = UsageHistoryGeometry.segments(values, in: rect) + return transmit ? segments : segments.map { $0.map { CGPoint(x: $0.x, y: rect.maxY + rect.minY - $0.y) } } + } +} + +struct NetworkTrafficPanel: View { + let transmit: Double + let receiveHistory: [Double] + let transmitHistory: [Double] + @AppStorage("DockTelemetry.visualStyle") private var styleRaw = ConsoleStyle.phosphor.rawValue + @Environment(\.consoleTypography) private var typography + + private var transmitColor: Color { + styleRaw == ConsoleStyle.synthwave.rawValue + ? Color(red: 1, green: 0.18, blue: 0.72) : phosphor + } + + var body: some View { + VStack(spacing: 0) { + DataGraphHeader(label: "NETWORK TX // 96 SEC", value: byteRate(transmit), valueColor: transmitColor) + Canvas { context, size in + guard size.width > 0, size.height > 4 else { return } + let mid = size.height / 2 + let inset = min(6, size.height / 8) + let top = CGRect(x: 0, y: inset, width: size.width, height: mid - inset) + let bottom = CGRect(x: 0, y: mid, width: size.width, height: mid - inset) + let scale = NetworkHistoryGeometry.scale(receive: receiveHistory, transmit: transmitHistory) + drawGrid(context: &context, size: size, columns: 12, rows: 4) + var center = Path() + center.move(to: CGPoint(x: 0, y: mid)) + center.addLine(to: CGPoint(x: size.width, y: mid)) + context.stroke(center, with: .color(phosphor.opacity(0.55)), lineWidth: 1) + draw(transmitHistory, in: top, scale: scale, transmit: true, color: transmitColor, context: &context) + draw(receiveHistory, in: bottom, scale: scale, transmit: false, color: phosphor, context: &context) + // Fixed-position legends are inside the clipped plot, never over its header. + if size.height >= 44 { + let fontSize = min(9 * typography.secondary, size.height / 7) + context.draw(Text("TX ↑").font(.system(size: fontSize, weight: .bold, design: .monospaced)) + .foregroundStyle(transmitColor), at: CGPoint(x: 5, y: 3), anchor: .topLeading) + context.draw(Text("RX ↓").font(.system(size: fontSize, weight: .bold, design: .monospaced)) + .foregroundStyle(phosphor), at: CGPoint(x: 5, y: size.height - 3), anchor: .bottomLeading) + } + } + .clipped() + } + .overlay(Rectangle().stroke(dimPhosphor, lineWidth: 1)) + .clipped() + .help("Last 96 samples, about 96 seconds. TX uploads rise above the center; RX downloads extend below it. Both use the same automatically scaled bytes/second range.") + } + + private func draw(_ values: [Double], in rect: CGRect, scale: Double, transmit: Bool, + color: Color, context: inout GraphicsContext) { + let baseline = transmit ? rect.maxY : rect.minY + for points in NetworkHistoryGeometry.segments(values, in: rect, scale: scale, transmit: transmit) { + guard let first = points.first, let last = points.last else { continue } + var line = Path() + line.move(to: first) + for point in points.dropFirst() { line.addLine(to: point) } + var fill = line + fill.addLine(to: CGPoint(x: last.x, y: baseline)) + fill.addLine(to: CGPoint(x: first.x, y: baseline)) + fill.closeSubpath() + context.fill(fill, with: .color(color.opacity(0.16))) + if points.count == 1 { + context.fill(Path(ellipseIn: CGRect(x: first.x - 1, y: first.y - 1, width: 2, height: 2)), with: .color(color)) + } else { + context.stroke(line, with: .color(color), lineWidth: 1.6) + } + } + } +} diff --git a/Sources/DockTelemetry/Theme.swift b/Sources/Retrolemetry/Theme.swift similarity index 100% rename from Sources/DockTelemetry/Theme.swift rename to Sources/Retrolemetry/Theme.swift diff --git a/Sources/Retrolemetry/Typography.swift b/Sources/Retrolemetry/Typography.swift new file mode 100644 index 0000000..e6ed589 --- /dev/null +++ b/Sources/Retrolemetry/Typography.swift @@ -0,0 +1,113 @@ +import SwiftUI + +enum ConsoleFontRole: String, CaseIterable { + case primary, dark, secondary, other, frameHeader, frameFooter + static let allCases: [Self] = [.primary, .dark, .secondary, .frameHeader, .frameFooter] + var title: String { + switch self { + case .primary: "Metrics / stats" + case .dark: "Dark texts" + case .secondary: "Main text" + case .other: "Module text" + case .frameHeader: "Frame header" + case .frameFooter: "Frame footer" + } + } +} + +struct ConsoleTypography: Codable, Equatable { + private var legacyPrimary: Double + private var legacySecondary: Double + private var legacyOther: Double + var groups: [String: Double] = [:] + + init(primary: Double = 1, secondary: Double = 1, other: Double = 1, groups: [String: Double] = [:]) { + legacyPrimary = primary; legacySecondary = secondary; legacyOther = other; self.groups = groups + } + var primary: Double { self[.primary] } + var secondary: Double { self[.secondary] } + var other: Double { self[.other] } + + private func inherited(_ role: ConsoleFontRole) -> Double { + switch role { + case .primary: legacyPrimary + case .dark, .secondary: legacySecondary + case .other, .frameHeader, .frameFooter: legacyOther + } + } + static func resolvedRole(_ role: ConsoleFontRole, dimmed: Bool) -> ConsoleFontRole { + dimmed ? .dark : role + } + func scale(_ role: ConsoleFontRole, fallback: ConsoleFontRole? = nil, dimmed: Bool = false) -> Double { + groups[Self.resolvedRole(role, dimmed: dimmed).rawValue] ?? inherited(fallback ?? role) + } + + subscript(_ role: ConsoleFontRole) -> Double { + get { scale(role) } + set { groups[role.rawValue] = newValue } + } + func font(_ size: Double, role: ConsoleFontRole, weight: Font.Weight = .regular, fallback: ConsoleFontRole? = nil, dimmed: Bool = false) -> Font { + .system(size: size * scale(role, fallback: fallback, dimmed: dimmed), weight: weight, design: .monospaced) + } + + // Decode old three-slider exports without migrating preferences or altering their appearance. + private enum CodingKeys: String, CodingKey { case primary, secondary, other, groups } + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + legacyPrimary = try c.decode(Double.self, forKey: .primary) + legacySecondary = try c.decode(Double.self, forKey: .secondary) + legacyOther = try c.decode(Double.self, forKey: .other) + groups = try c.decodeIfPresent([String: Double].self, forKey: .groups) ?? [:] + groups = groups.filter { $0.value.isFinite && (0.65...3).contains($0.value) } + } + func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(legacyPrimary, forKey: .primary) + try c.encode(legacySecondary, forKey: .secondary) + try c.encode(legacyOther, forKey: .other) + if !groups.isEmpty { try c.encode(groups, forKey: .groups) } + } +} + +private struct ConsoleTypographyKey: EnvironmentKey { + static let defaultValue = ConsoleTypography() +} +private struct ConsoleDimTextKey: EnvironmentKey { + static let defaultValue = false +} +extension EnvironmentValues { + var consoleTypography: ConsoleTypography { + get { self[ConsoleTypographyKey.self] } + set { self[ConsoleTypographyKey.self] = newValue } + } + var consoleDimText: Bool { + get { self[ConsoleDimTextKey.self] } + set { self[ConsoleDimTextKey.self] = newValue } + } +} +private struct ConsoleFontModifier: ViewModifier { + @Environment(\.consoleTypography) private var typography + @Environment(\.consoleDimText) private var dimmed + let size: Double + let role: ConsoleFontRole + let weight: Font.Weight + let fallback: ConsoleFontRole? + func body(content: Content) -> some View { content.font(typography.font(size, role: role, weight: weight, fallback: fallback, dimmed: dimmed)) } +} +/// Pair the muted palette with its typography group. Dim appearance takes precedence +/// over a label's semantic role, including when inherited by a whole row/container. +private struct ConsoleDimTextModifier: ViewModifier { + let enabled: Bool + func body(content: Content) -> some View { + content.foregroundStyle(enabled ? dimPhosphor : phosphor) + .environment(\.consoleDimText, enabled) + } +} +extension View { + func consoleFont(_ size: Double, role: ConsoleFontRole, weight: Font.Weight = .regular, fallback: ConsoleFontRole? = nil) -> some View { + modifier(ConsoleFontModifier(size: size, role: role, weight: weight, fallback: fallback)) + } + func consoleDimmed(_ enabled: Bool = true) -> some View { + modifier(ConsoleDimTextModifier(enabled: enabled)) + } +} diff --git a/Sources/Retrolemetry/VectorDisplay.swift b/Sources/Retrolemetry/VectorDisplay.swift new file mode 100644 index 0000000..373166d --- /dev/null +++ b/Sources/Retrolemetry/VectorDisplay.swift @@ -0,0 +1,251 @@ +import AppKit +import MetalKit +import SwiftUI + +/// A tiny fixed-coordinate vector layer. Static text/telemetry stays in SwiftUI; +/// the GPU calculates line positions instead of tessellating Canvas paths at 30fps. +struct VectorConfiguration { + var uniforms = VectorUniforms() + var history: [Float] = Array(repeating: -1, count: 96) + var targets: [SIMD4] = [] + var metric = 0.0 + var response = SignalGridResponse.medium + var animated = true + var scene: ConsoleScene + var transition: ConsoleTransitionMotion? + var transitionProgress: Float? + var radarRegion: RadarRegion? + + @MainActor + init(scene: ConsoleScene, layouts: LayoutStore, snapshot: TelemetrySnapshot, + gpuHistory: [Double?], weather: WeatherSnapshot, tubeStrength: Double, bloom: Double, location: GlobeCoordinate? = nil) { + self.scene = scene + let defaults = UserDefaults.standard + func value(_ key: String, _ fallback: Double) -> Double { + (defaults.object(forKey: "DockTelemetry." + key) as? NSNumber)?.doubleValue ?? fallback + } + func color(_ color: Color) -> SIMD4 { + let c = NSColor(color).usingColorSpace(.sRGB) ?? .green + return SIMD4(Float(c.redComponent), Float(c.greenComponent), Float(c.blueComponent), Float(c.alphaComponent)) + } + uniforms.primary = color(phosphor) + uniforms.secondary = color(dimPhosphor) + uniforms.style = SIMD4(Float(scene.rawValue), Float(tubeStrength), Float(bloom), 0) + let module: String + switch scene { + case .system: module = "globe" + case .radar: module = "radar" + case .signal: module = "scope" + case .fullMetrics: return + } + let frame = layouts.frame(scene, module) + guard frame.visible else { return } + uniforms.rect = SIMD4(Float(frame.x), Float(frame.y), Float(frame.width), Float(frame.height)) + switch scene { + case .system: + uniforms.shape = SIMD4(Float(value("globeWidthCorrection", 1.10)), Float(value("globeHeightCorrection", 0.9254)), 0, 0) + let activity = TradingRegionActivity(at: Date()) + uniforms.globe = SIMD4(activity.us ? 1 : 0, activity.europe ? 1 : 0, activity.asia ? 1 : 0, Float(GlobeCoastlines.degrees.count)) + if let location { + uniforms.location = SIMD4(Float(location.longitude * .pi / 180), Float(location.latitude * .pi / 180), 1, 0) + } + case .radar: + radarRegion = weather.radarRegion + let mode = RadarTargetMode(rawValue: defaults.string(forKey: "DockTelemetry.radarTargetMode") ?? "") ?? .precipitation + let modes: [RadarTargetMode] = [.precipitation, .temperature, .wind, .decorative] + targets = radarTargets(for: weather, mode: mode).map { + mode == .decorative ? SIMD4(Float($0.radius), Float($0.angle), Float($0.intensity), 0) + : SIMD4($0.mapPosition.x, $0.mapPosition.y, Float($0.intensity), Float($0.heading)) + } + uniforms.shape = SIMD4(Float(value("radarWidthCorrection", 1.10)), Float(value("radarHeightCorrection", 0.9254)), + Float(modes.firstIndex(of: mode) ?? 0), Float(value("radarTargetPulse", 1))) + uniforms.style.w = Float(targets.count) + uniforms.extra.z = Float(radarRegion.map { RadarMapGeometry.segments(for: $0).count } ?? 0) + uniforms.extra.w = Float(radarRegion.map { RadarMapGeometry.countrySegmentCount(for: $0) } ?? 0) + case .signal: + let selected = SignalGridMetric(rawValue: defaults.string(forKey: "DockTelemetry.signalGridMetric") ?? "") ?? .cpu + switch selected { + case .cpu: metric = snapshot.cpu + case .gpu: metric = snapshot.gpu ?? 0 + case .network: metric = min(1, (snapshot.networkIn + snapshot.networkOut) / 12_000_000) + case .disk: metric = snapshot.disk + } + response = SignalGridResponse(rawValue: defaults.string(forKey: "DockTelemetry.signalGridResponse") ?? "") ?? .medium + animated = value("signalGridAnimationEnabled", 1) > 0.5 + let pattern = SignalGridPattern(rawValue: defaults.string(forKey: "DockTelemetry.signalGridPattern") ?? "") ?? .recede + uniforms.shape = SIMD4(Float(value("signalSynthwaveGrid", 0)), + Float(SignalGridPattern.allCases.firstIndex(of: pattern) ?? 0), + defaults.string(forKey: "DockTelemetry.signalDisplayMode") == SignalDisplayMode.gpuHorizon.rawValue ? 1 : 0, + Float(response.multiplier)) + let typography = layouts.typography(for: scene) + uniforms.extra.x = Float(max(typography.primary, typography.secondary)) + for (index, sample) in gpuHistory.suffix(96).enumerated() { + history[index] = sample.flatMap { $0.isFinite && (0...1).contains($0) ? Float($0) : nil } ?? -1 + } + case .fullMetrics: break + } + } + + var visible: Bool { uniforms.rect.z > 0 && uniforms.rect.w > 0 } + var segmentCount: Int { + switch scene { + case .system: 128 + 7 * 96 + GlobeGeometry.meridianCount * 72 + 24 + GlobeCoastlines.degrees.count + 4 * 32 + case .radar: 4 * 96 + 12 + 16 + Int(uniforms.extra.z) + targets.count * 32 + case .signal: (uniforms.shape.x > 0.5 ? 21 * 64 + 16 * 80 + 1 : 26) + (uniforms.shape.z > 0.5 ? 287 : 4 * 360) + case .fullMetrics: 0 + } + } +} + +struct VectorUniforms { + var rect = SIMD4(repeating: 0) + var primary = SIMD4(0.34, 1, 0.43, 1) + var secondary = SIMD4(0.34, 1, 0.43, 0.48) + var style = SIMD4(repeating: 0) // scene, tube, bloom, target count + var shape = SIMD4(1, 1, 0, 0) + var motion = SIMD4(repeating: 0) // time, travel, wave, metric + var extra = SIMD4(1, 0, 0, 0) + var globe = SIMD4(repeating: 0) + var location = SIMD4(repeating: 0) + var transition = SIMD4(-1, 0, 1, 1) +} + +struct VectorDisplay: NSViewRepresentable { + let configuration: VectorConfiguration + let paused: Bool + let frameRate: Double + static var isAvailable: Bool { VectorGPU.shared != nil } + + func makeCoordinator() -> Renderer { Renderer() } + func makeNSView(context: Context) -> MTKView { + let view = VectorMetalView(frame: .zero, device: VectorGPU.shared?.device) + view.clearColor = MTLClearColorMake(0, 0, 0, 0) + view.colorPixelFormat = .bgra8Unorm + view.framebufferOnly = true + view.autoResizeDrawable = false + // Retain crisp curves at Retina density, but never allocate a 4K vector buffer. + view.drawableSize = CGSize(width: 1920, height: 1080) + view.layer?.isOpaque = false + view.delegate = context.coordinator + updateNSView(view, context: context) + return view + } + func updateNSView(_ view: MTKView, context: Context) { + context.coordinator.update(configuration, paused: paused) + let moves = configuration.transition != nil || configuration.scene != .signal || configuration.uniforms.shape.z < 0.5 + || (configuration.uniforms.shape.x > 0.5 && configuration.animated) + let fps = moves ? max(15, min(60, Int(frameRate))) : 1 + if view.preferredFramesPerSecond != fps { view.preferredFramesPerSecond = fps } + let shouldPause = paused || !configuration.visible || !moves || configuration.transitionProgress != nil + if view.isPaused != shouldPause { view.isPaused = shouldPause } + if shouldPause { view.draw() } + } + static func dismantleNSView(_ view: MTKView, coordinator: Renderer) { + view.isPaused = true + view.delegate = nil + } + + final class Renderer: NSObject, MTKViewDelegate { + private var configuration: VectorConfiguration? + private let inFlight = DispatchSemaphore(value: 2) + private var motion = SignalGridMotion() + private var wasPaused = false + + func update(_ next: VectorConfiguration, paused: Bool) { + let now = ProcessInfo.processInfo.systemUptime + if configuration?.scene != next.scene { + motion = SignalGridMotion(time: now, metric: next.metric, response: next.response, animated: next.animated && !paused) + } else if configuration?.metric != next.metric || configuration?.response != next.response || configuration?.animated != next.animated || wasPaused != paused { + motion.retarget(at: now, metric: next.metric, response: next.response, animated: next.animated && !paused) + } + wasPaused = paused + configuration = next + } + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} + func draw(in view: MTKView) { + guard var c = configuration, let gpu = VectorGPU.shared, + inFlight.wait(timeout: .now()) == .success else { return } + guard let pass = view.currentRenderPassDescriptor, let drawable = view.currentDrawable, + let command = gpu.queue.makeCommandBuffer(), + let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { + inFlight.signal(); return + } + if c.visible { + let now = ProcessInfo.processInfo.systemUptime + let frame = motion.sample(at: now) + let elapsed = now - ConsoleAnimationEpoch.uptime + c.uniforms.motion = SIMD4( + Float(elapsed.truncatingRemainder(dividingBy: 2 * .pi * 100)), + Float(frame.travel.truncatingRemainder(dividingBy: 20)), + Float(frame.wave.truncatingRemainder(dividingBy: 2 * .pi * 100)), + Float(frame.metric) + ) + c.uniforms.extra.y = Float((elapsed * 42).truncatingRemainder(dividingBy: 360)) + c.uniforms.transition = c.transition?.uniforms(at: now) ?? SIMD4(-1, 0, 1, 1) + if let progress = c.transitionProgress { c.uniforms.transition.x = progress } + encoder.setRenderPipelineState(gpu.pipeline) + encoder.setVertexBytes(&c.uniforms, length: MemoryLayout.stride, index: 0) + c.history.withUnsafeBytes { encoder.setVertexBytes($0.baseAddress!, length: $0.count, index: 1) } + encoder.setVertexBuffer(gpu.coastlines, offset: 0, index: 3) + encoder.setVertexBuffer(gpu.radarMaps[c.radarRegion ?? .israel], offset: 0, index: 4) + let segments = c.segmentCount + if c.targets.isEmpty { + var empty = SIMD4(repeating: 0) + encoder.setVertexBytes(&empty, length: MemoryLayout>.stride, index: 2) + } else { + c.targets.withUnsafeBytes { encoder.setVertexBytes($0.baseAddress!, length: $0.count, index: 2) } + } + encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: segments * 6, instanceCount: c.uniforms.style.z > 0 ? 3 : 1) + } + encoder.endEncoding() + command.present(drawable) + let semaphore = inFlight + command.addCompletedHandler { _ in semaphore.signal() } + command.commit() + } + } +} + +private final class VectorMetalView: MTKView { + override func layout() { + super.layout() + if isPaused, bounds.width > 0, bounds.height > 0 { draw() } + } + override var isOpaque: Bool { false } + override func hitTest(_ point: NSPoint) -> NSView? { nil } +} + +private final class VectorGPU { + static let shared: VectorGPU? = { + guard let device = MTLCreateSystemDefaultDevice(), let url = ConsoleMetalLibrary.url, + let library = try? device.makeLibrary(URL: url), + let vertex = library.makeFunction(name: "consoleVectorVertex"), + let fragment = library.makeFunction(name: "consoleVectorFragment"), + let queue = device.makeCommandQueue(), + let coastlines = GlobeGeometry.coastlines.withUnsafeBytes({ device.makeBuffer(bytes: $0.baseAddress!, length: $0.count, options: .storageModeShared) }) else { return nil } + var radarMaps: [RadarRegion: MTLBuffer] = [:] + for region in RadarRegion.allCases { + guard let map = RadarMapGeometry.segments(for: region).withUnsafeBytes({ device.makeBuffer(bytes: $0.baseAddress!, length: $0.count, options: .storageModeShared) }) else { return nil } + radarMaps[region] = map + } + let descriptor = MTLRenderPipelineDescriptor() + descriptor.vertexFunction = vertex; descriptor.fragmentFunction = fragment + let attachment = descriptor.colorAttachments[0]! + attachment.pixelFormat = .bgra8Unorm + attachment.isBlendingEnabled = true + attachment.sourceRGBBlendFactor = .one; attachment.sourceAlphaBlendFactor = .one + attachment.destinationRGBBlendFactor = .oneMinusSourceAlpha; attachment.destinationAlphaBlendFactor = .oneMinusSourceAlpha + guard let pipeline = try? device.makeRenderPipelineState(descriptor: descriptor) else { return nil } + return VectorGPU(device: device, queue: queue, pipeline: pipeline, coastlines: coastlines, radarMaps: radarMaps) + }() + let device: MTLDevice + let queue: MTLCommandQueue + let pipeline: MTLRenderPipelineState + let coastlines: MTLBuffer + let radarMaps: [RadarRegion: MTLBuffer] + private init(device: MTLDevice, queue: MTLCommandQueue, pipeline: MTLRenderPipelineState, coastlines: MTLBuffer, radarMaps: [RadarRegion: MTLBuffer]) { + self.device = device; self.queue = queue; self.pipeline = pipeline + self.coastlines = coastlines + self.radarMaps = radarMaps + } +} diff --git a/Sources/Retrolemetry/Weather.swift b/Sources/Retrolemetry/Weather.swift new file mode 100644 index 0000000..87f1532 --- /dev/null +++ b/Sources/Retrolemetry/Weather.swift @@ -0,0 +1,336 @@ +import Foundation +import Combine +import OSLog +@preconcurrency import CoreLocation + +struct HourlyWeatherPoint { + let time: Date + let temperature: Double + let precipitationChance: Double + let condition: String +} + +struct DailyWeatherPoint { + let date: Date + let low: Double + let high: Double + let precipitationChance: Double + let condition: String +} + +struct WeatherSnapshot { + var coordinate: GlobeCoordinate? + var location = "AWAITING LOCATION" + var condition = "WEATHER OFFLINE" + var temperature = 0.0 + var apparentTemperature = 0.0 + var humidity = 0.0 + var windSpeed = 0.0 + var precipitation = 0.0 + var temperatureForecast: [Double] = Array(repeating: 0, count: 12) + var precipitationForecast: [Double] = Array(repeating: 0, count: 12) + var hourlyForecast: [HourlyWeatherPoint] = [] + var dailyForecast: [DailyWeatherPoint] = [] + var updatedAt: Date? + var status = "LOCATION PERMISSION REQUIRED" + var radarWeather: [RadarWeatherPoint] = [] + var radarUpdatedAt: Date? + var radarStatus = "REGIONAL FORECAST PENDING" + var radarRegion: RadarRegion? + var localForecastIsAvailable: Bool { updatedAt.map { Date().timeIntervalSince($0) < 3600 } ?? false } +} + +@MainActor +final class WeatherLocation: ObservableObject { + static let shared = WeatherLocation() + @Published var coordinate: GlobeCoordinate? +} + +@MainActor +final class WeatherModel: NSObject, ObservableObject, CLLocationManagerDelegate { + @Published private(set) var snapshot = WeatherSnapshot() + + private let locationManager = CLLocationManager() + private var refreshTimer: Timer? + private var coordinate: CLLocationCoordinate2D? + private var regionalRequestInFlight = false + private var regionalTask: Task? + private var localTask: Task? + private var regionObserver: AnyCancellable? + private let defaults: UserDefaults + + init(preview: Bool = false, defaults: UserDefaults = .standard) { + self.defaults = defaults + super.init() + if preview { + let now = Date() + snapshot = WeatherSnapshot(coordinate: GlobeCoordinate(latitude: 32, longitude: 35), + location: "STATIC WEATHER PREVIEW", condition: "PARTLY CLOUDY", temperature: 24, + apparentTemperature: 25, humidity: 0.58, windSpeed: 12, + temperatureForecast: (0..<12).map { 0.4 + sin(Double($0)*0.3)*0.2 }, + precipitationForecast: (0..<12).map { 0.2 + sin(Double($0)*0.3)*0.1 }, + hourlyForecast: (0..<12).map { HourlyWeatherPoint(time: now.addingTimeInterval(Double($0)*3600), temperature: 24+sin(Double($0)*0.3)*5, precipitationChance: 0.2, condition: "PARTLY CLOUDY") }, + dailyForecast: (0..<7).map { DailyWeatherPoint(date: now.addingTimeInterval(Double($0)*86400), low: 18+Double($0%2), high: 25+Double($0%3), precipitationChance: 0.2, condition: "PARTLY CLOUDY") }, status: "SYNTHETIC QA DATA") + let selection = WeatherRegionSelection(rawValue: defaults.string(forKey: WeatherRegionSelection.preferenceKey) ?? "") ?? .automatic + let region = selection.resolve(coordinate: snapshot.coordinate) ?? .israel + snapshot.radarRegion = region + snapshot.updatedAt = now + snapshot.radarWeather = RadarWeatherPoint.preview(at: now, region: region) + snapshot.radarUpdatedAt = now + snapshot.radarStatus = "SYNTHETIC FORECAST PREVIEW" + return + } + locationManager.delegate = self + locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers + requestLocation() + regionObserver = NotificationCenter.default.publisher(for: WeatherRegionSelection.changed).sink { [weak self] _ in + Task { @MainActor in self?.refreshRegionalForecast() } + } + refreshRegionalForecast() + refreshTimer = Timer.scheduledTimer(withTimeInterval: 15 * 60, repeats: true) { [weak self] _ in + guard let owner = self else { return } + Task { @MainActor in owner.refresh(); owner.refreshRegionalForecast() } + } + refreshTimer?.tolerance = 60 + } + + deinit { refreshTimer?.invalidate(); regionalTask?.cancel(); localTask?.cancel() } + + private func refreshRegionalForecast() { + let selection = WeatherRegionSelection(rawValue: defaults.string(forKey: WeatherRegionSelection.preferenceKey) ?? "") ?? .automatic + let region = selection.resolve(coordinate: snapshot.coordinate) + if region != snapshot.radarRegion { + regionalTask?.cancel() + regionalTask = nil + regionalRequestInFlight = false + snapshot.radarRegion = region + snapshot.radarWeather = [] + snapshot.radarUpdatedAt = nil + } + guard let region else { + snapshot.radarStatus = snapshot.coordinate == nil ? "ALLOW LOCATION OR SELECT MAP" : "SELECT A SUPPORTED MAP REGION" + return + } + if let updated = snapshot.radarUpdatedAt, Date().timeIntervalSince(updated) < 15 * 60 { return } + guard !regionalRequestInFlight else { return } + regionalRequestInFlight = true + regionalTask = Task { [weak self] in + guard let self else { return } + defer { if !Task.isCancelled { self.regionalRequestInFlight = false } } + do { + var request = URLRequest(url: RegionalWeatherFeed.url(for: region)) + request.timeoutInterval = 25 + let (data, response) = try await URLSession.shared.data(for: request) + guard !Task.isCancelled, self.snapshot.radarRegion == region else { return } + guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } + self.snapshot.radarWeather = try RegionalWeatherFeed.decode(data, region: region) + self.snapshot.radarUpdatedAt = Date() + self.snapshot.radarStatus = "OPEN-METEO // FORECAST" + } catch { + guard !Task.isCancelled, self.snapshot.radarRegion == region else { return } + self.snapshot.radarStatus = self.snapshot.radarWeather.isEmpty + ? "REGIONAL FORECAST OFFLINE" : "FORECAST OFFLINE // LAST UPDATE" + } + } + } + + private func requestLocation() { + switch locationManager.authorizationStatus { + case .authorized, .authorizedAlways: + snapshot.status = "LOCATING" + locationManager.requestLocation() + case .notDetermined: + snapshot.status = "REQUESTING LOCATION" + locationManager.requestWhenInUseAuthorization() + case .denied, .restricted: + localTask?.cancel() + coordinate = nil + snapshot.coordinate = nil + WeatherLocation.shared.coordinate = nil + snapshot.updatedAt = nil + snapshot.hourlyForecast = [] + snapshot.dailyForecast = [] + snapshot.status = "ENABLE LOCATION IN SYSTEM SETTINGS" + refreshRegionalForecast() + @unknown default: + snapshot.status = "LOCATION UNAVAILABLE" + } + } + + nonisolated func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + Task { @MainActor [weak self] in self?.requestLocation() } + } + + nonisolated func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let location = locations.last else { return } + let latitude = location.coordinate.latitude + let longitude = location.coordinate.longitude + Task { @MainActor [weak self] in self?.applyLocation(latitude: latitude, longitude: longitude) } + } + + private func applyLocation(latitude: Double, longitude: Double) { + coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + snapshot.coordinate = GlobeCoordinate(latitude: latitude, longitude: longitude) + WeatherLocation.shared.coordinate = snapshot.coordinate + snapshot.location = "LOCAL WEATHER" + refresh() + refreshRegionalForecast() + } + + nonisolated func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { + Task { @MainActor [weak self] in self?.snapshot.status = "LOCATION UNAVAILABLE" } + } + + private func refresh() { + guard let coordinate else { + requestLocation() + return + } + snapshot.status = "UPDATING FORECAST" + + localTask?.cancel() + localTask = Task { [weak self] in + do { + let payload = try await LocalWeatherFeed.fetch(latitude: coordinate.latitude, longitude: coordinate.longitude) + guard !Task.isCancelled else { return } + self?.apply(payload) + } catch { + guard !Task.isCancelled else { return } + let status = WeatherFeedFailure.status(for: error) + self?.snapshot.status = status + // Log only the failure class/code: no URL, coordinate, response body or credential. + Logger(subsystem: "io.github.SamSpring.Retrolemetry", category: "Weather") + .error("Local forecast failed: \(status, privacy: .public)") + } + } + } + + private func apply(_ payload: OpenMeteoResponse) { + let currentTimestamp = Int(Date().timeIntervalSince1970) + let hourlyCount = [ + payload.hourly.time.count, + payload.hourly.temperature2m.count, + payload.hourly.precipitationProbability.count, + payload.hourly.weatherCode.count + ].min() ?? 0 + let validHourlyTimes = payload.hourly.time.prefix(hourlyCount) + let hourlyStart = validHourlyTimes.firstIndex(where: { $0 >= currentTimestamp - 1800 }) ?? 0 + let hourlyEnd = min(hourlyCount, hourlyStart + 12) + let hourlyRange = hourlyStart.. [Double] { + guard let low = values.min(), let high = values.max() else { return [] } + let span = max(2, high - low) + return values.map { 0.12 + (($0 - low) / span) * 0.76 } + } + + private func weatherCondition(_ code: Int) -> String { + switch code { + case 0: "CLEAR SKY" + case 1, 2: "PARTLY CLOUDY" + case 3: "OVERCAST" + case 45, 48: "FOG" + case 51...57: "DRIZZLE" + case 61...67: "RAIN" + case 71...77: "SNOW" + case 80...82: "RAIN SHOWERS" + case 85, 86: "SNOW SHOWERS" + case 95...99: "THUNDERSTORM" + default: "MIXED CONDITIONS" + } + } +} + +struct OpenMeteoResponse: Decodable { + let current: Current + let hourly: Hourly + let daily: Daily + + struct Current: Decodable { + let temperature2m: Double + let apparentTemperature: Double + let relativeHumidity2m: Double + let precipitation: Double + let weatherCode: Int + let windSpeed10m: Double + + enum CodingKeys: String, CodingKey { + case temperature2m = "temperature_2m" + case apparentTemperature = "apparent_temperature" + case relativeHumidity2m = "relative_humidity_2m" + case precipitation + case weatherCode = "weather_code" + case windSpeed10m = "wind_speed_10m" + } + } + + struct Hourly: Decodable { + let time: [Int] + let temperature2m: [Double] + let precipitationProbability: [Double] + let weatherCode: [Int] + + enum CodingKeys: String, CodingKey { + case time + case temperature2m = "temperature_2m" + case precipitationProbability = "precipitation_probability" + case weatherCode = "weather_code" + } + } + + struct Daily: Decodable { + let time: [Int] + let weatherCode: [Int] + let temperature2mMax: [Double] + let temperature2mMin: [Double] + let precipitationProbabilityMax: [Double] + + enum CodingKeys: String, CodingKey { + case time + case weatherCode = "weather_code" + case temperature2mMax = "temperature_2m_max" + case temperature2mMin = "temperature_2m_min" + case precipitationProbabilityMax = "precipitation_probability_max" + } + } +} diff --git a/Sources/Retrolemetry/WeatherFeed.swift b/Sources/Retrolemetry/WeatherFeed.swift new file mode 100644 index 0000000..34d2e35 --- /dev/null +++ b/Sources/Retrolemetry/WeatherFeed.swift @@ -0,0 +1,62 @@ +import Foundation + +enum WeatherFeedFailure: Error { + case http(Int) + case invalidResponse + + static func status(for error: Error) -> String { + if case let Self.http(code) = error { return "WEATHER PROVIDER // HTTP \(code)" } + if error is DecodingError { return "WEATHER DATA INCOMPLETE" } + if let error = error as? URLError { return "WEATHER CONNECTION // \(error.code.rawValue)" } + return "WEATHER FEED UNAVAILABLE" + } + + static func canRetry(_ error: Error) -> Bool { + if case let Self.http(code) = error { return [500, 502, 503, 504].contains(code) } + guard let error = error as? URLError else { return false } + return [.timedOut, .networkConnectionLost, .cannotConnectToHost, .dnsLookupFailed].contains(error.code) + } +} + +enum LocalWeatherFeed { + static func url(latitude: Double, longitude: Double) throws -> URL { + guard latitude.isFinite, longitude.isFinite, (-90...90).contains(latitude), (-180...180).contains(longitude) else { + throw URLError(.badURL) + } + var components = URLComponents(string: "https://api.open-meteo.com/v1/forecast")! + components.queryItems = [ + URLQueryItem(name: "latitude", value: String(latitude)), + URLQueryItem(name: "longitude", value: String(longitude)), + URLQueryItem(name: "current", value: "temperature_2m,apparent_temperature,relative_humidity_2m,precipitation,weather_code,wind_speed_10m"), + URLQueryItem(name: "hourly", value: "temperature_2m,precipitation_probability,weather_code"), + URLQueryItem(name: "daily", value: "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"), + URLQueryItem(name: "forecast_days", value: "7"), + URLQueryItem(name: "timeformat", value: "unixtime"), + URLQueryItem(name: "timezone", value: "auto") + ] + guard let url = components.url else { throw URLError(.badURL) } + return url + } + + /// At most three attempts, with no polling loop or persistent retry timer. + static func fetch(latitude: Double, longitude: Double, session: URLSession = .shared, + retryDelays: [Double] = [3, 12]) async throws -> OpenMeteoResponse { + let url = try url(latitude: latitude, longitude: longitude) + let delays = Array(retryDelays.prefix(2)) + for attempt in 0...delays.count { + try Task.checkCancellation() + do { + let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) + let (data, response) = try await session.data(for: request) + guard let response = response as? HTTPURLResponse else { throw WeatherFeedFailure.invalidResponse } + guard response.statusCode == 200 else { throw WeatherFeedFailure.http(response.statusCode) } + return try JSONDecoder().decode(OpenMeteoResponse.self, from: data) + } catch { + try Task.checkCancellation() + guard attempt < delays.count, WeatherFeedFailure.canRetry(error), delays[attempt].isFinite else { throw error } + try await Task.sleep(nanoseconds: UInt64(max(0, min(60, delays[attempt])) * 1_000_000_000)) + } + } + throw WeatherFeedFailure.invalidResponse + } +} diff --git a/Sources/Retrolemetry/WeatherRegion.swift b/Sources/Retrolemetry/WeatherRegion.swift new file mode 100644 index 0000000..f204c0e --- /dev/null +++ b/Sources/Retrolemetry/WeatherRegion.swift @@ -0,0 +1,65 @@ +import Foundation +import SwiftUI + +enum RadarRegion: String, CaseIterable, Identifiable { + case israel, northAmerica, europe + var id: String { rawValue } + var title: String { + switch self { case .israel: "Israel"; case .northAmerica: "North America"; case .europe: "Europe" } + } + var screenTitle: String { + switch self { case .israel: "ISRAEL"; case .northAmerica: "N AMERICA"; case .europe: "EUROPE" } + } + var sites: [RadarWeatherSite] { + switch self { + case .israel: RadarWeatherSite.all + case .northAmerica: [ + .init(name: "SEATTLE", latitude: 47.6062, longitude: -122.3321), + .init(name: "LOS ANGELES", latitude: 34.0522, longitude: -118.2437), + .init(name: "CHICAGO", latitude: 41.8781, longitude: -87.6298), + .init(name: "NEW YORK", latitude: 40.7128, longitude: -74.0060), + .init(name: "TORONTO", latitude: 43.6532, longitude: -79.3832), + .init(name: "MEXICO CITY", latitude: 19.4326, longitude: -99.1332) + ] + case .europe: [ + .init(name: "LONDON", latitude: 51.5074, longitude: -0.1278), + .init(name: "PARIS", latitude: 48.8566, longitude: 2.3522), + .init(name: "BERLIN", latitude: 52.5200, longitude: 13.4050), + .init(name: "MADRID", latitude: 40.4168, longitude: -3.7038), + .init(name: "ROME", latitude: 41.9028, longitude: 12.4964), + .init(name: "WARSAW", latitude: 52.2297, longitude: 21.0122) + ] + } + } +} + +enum WeatherRegionSelection: String, CaseIterable, Identifiable { + case automatic, israel, northAmerica, europe + static let preferenceKey = "DockTelemetry.weatherRadarRegion" + static let changed = Notification.Name("Retrolemetry.weatherRadarRegionChanged") + var id: String { rawValue } + var title: String { self == .automatic ? "Automatic (location)" : (RadarRegion(rawValue: rawValue)?.title ?? "Automatic") } + + func resolve(coordinate: GlobeCoordinate?) -> RadarRegion? { + if self != .automatic { return RadarRegion(rawValue: rawValue) } + guard let coordinate else { return nil } + let lat = coordinate.latitude, lon = coordinate.longitude + // Local coverage tests: no reverse-geocoding service or extra permission. + if (29.3...33.6).contains(lat), (34...36).contains(lon) { return .israel } + if (8...85).contains(lat), (-170 ... -49).contains(lon) { return .northAmerica } + if (34...72).contains(lat), (-25...45).contains(lon) { return .europe } + return nil + } +} + +struct WeatherRegionPicker: View { + @AppStorage(WeatherRegionSelection.preferenceKey) private var selection = WeatherRegionSelection.automatic.rawValue + var body: some View { + Picker("Map region", selection: $selection) { + ForEach(WeatherRegionSelection.allCases) { Text($0.title).tag($0.rawValue) } + } + .onChange(of: selection) { + NotificationCenter.default.post(name: WeatherRegionSelection.changed, object: nil) + } + } +} diff --git a/Tests/RetrolemetryTests/ConsoleBehaviorTests.swift b/Tests/RetrolemetryTests/ConsoleBehaviorTests.swift new file mode 100644 index 0000000..0232a6f --- /dev/null +++ b/Tests/RetrolemetryTests/ConsoleBehaviorTests.swift @@ -0,0 +1,137 @@ +import XCTest +@testable import Retrolemetry + +final class ConsoleBehaviorTests: XCTestCase { + func testTypographyLoadsWithoutMigratingOrChangingSavedLayout() async { + await MainActor.run { + let suite = "RetrolemetryTests.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set(1.8, forKey: "DockTelemetry.fontScale") + defaults.set(1.35, forKey: "DockTelemetry.secondaryFontScale") + defaults.set(2.0, forKey: "DockTelemetry.auxiliaryFontScale") + let frame = ModuleFrame(x: 500, y: 63, width: 230, height: 255, visible: false) + let saved = try! JSONEncoder().encode(["globe": frame]) + defaults.set(saved, forKey: "DockTelemetry.layout.v5.0") + let initial = defaults.persistentDomain(forName: suite)! as NSDictionary + let store = LayoutStore(defaults: defaults) + XCTAssertTrue(store.globalTypographyEnabled) + XCTAssertEqual(store.typography(for: .signal), ConsoleTypography(primary: 1.8, secondary: 1.35, other: 2)) + XCTAssertEqual(store.frame(.system, "globe"), frame) + XCTAssertEqual(initial, defaults.persistentDomain(forName: suite)! as NSDictionary) + store.globalTypographyEnabled = false + store.setFontScale(0.9, role: .primary, scene: .signal) + XCTAssertEqual(store.typography(for: .signal).primary, 0.9) + XCTAssertEqual(store.typography(for: .system).primary, 1.8) + XCTAssertEqual(defaults.data(forKey: "DockTelemetry.layout.v5.0"), saved) + let reload = LayoutStore(defaults: defaults) + XCTAssertEqual(reload.typography(for: .signal).primary, 0.9) + store.globalTypographyEnabled = true + store.setFontScale(2, role: .secondary, scene: .radar) + XCTAssertEqual(store.typography(for: .system).secondary, 2) + store.globalTypographyEnabled = false + XCTAssertEqual(store.typography(for: .signal).primary, 0.9) + } + } + + func testTypographyReaches300PercentAndPersistsWithoutMovingModules() async { + await MainActor.run { + let suite = "RetrolemetryTests.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let store = LayoutStore(defaults: defaults) + let frame = store.frame(.signal, "ioReadout") + for role in ConsoleFontRole.allCases { + store.setFontScale(3, role: role, scene: .signal) + XCTAssertEqual(store.typography(for: .signal)[role], 3) + store.setFontScale(5, role: role, scene: .signal) + XCTAssertEqual(store.typography(for: .signal)[role], 3) + } + store.globalTypographyEnabled = false + store.setFontScale(2.7, role: .secondary, scene: .radar) + let reload = LayoutStore(defaults: defaults) + XCTAssertEqual(reload.typography(for: .radar).secondary, 2.7) + XCTAssertEqual(reload.typography(for: .signal).primary, 3) + XCTAssertEqual(reload.frame(.signal, "ioReadout"), frame) + } + } + + func testHiddenModuleKeepsFrameAndCanBeRestored() async { + await MainActor.run { + let suite = "RetrolemetryTests.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let store = LayoutStore(defaults: defaults) + let before = store.frame(.system, "globe") + store.setVisible(false, scene: .system, module: "globe") + let hidden = store.frame(.system, "globe") + XCTAssertFalse(hidden.visible) + XCTAssertEqual(hidden.x, before.x); XCTAssertEqual(hidden.width, before.width) + store.setVisible(true, scene: .system, module: "globe") + XCTAssertEqual(store.frame(.system, "globe"), before) + } + } + + func testTickerSelectionUsesResizedFrameAndTypography() { + let frame = ModuleFrame(x: 130, y: 280, width: 420, height: 180) + for scale in [0.65, 1, 2.0, 3.0] { + let typography = ConsoleTypography(primary: scale, secondary: scale, other: scale) + let top = frame.y + 7 + MarketTickerGeometry.headerHeight(typography) + 7 + let rowHeight = (frame.height - 14 - MarketTickerGeometry.headerHeight(typography) - 19) / 5 + for row in 0..<5 { + let p = CGPoint(x: frame.x+20, y: top + Double(row)*(rowHeight+3) + rowHeight/2) + XCTAssertEqual(MarketTickerGeometry.row(at: p, frame: frame, typography: typography), row) + } + XCTAssertNil(MarketTickerGeometry.row(at: CGPoint(x: frame.x, y: frame.y+3), frame: frame, typography: typography)) + } + } + + func testStockFocusAndAutomaticRotationCanBeRestored() async { + await MainActor.run { + let model = MarketModel(preview: true) + model.focus("RGTI"); XCTAssertEqual(model.focusedSymbol, "RGTI") + model.focus("NOT-IN-PORTFOLIO"); XCTAssertEqual(model.focusedSymbol, "RGTI") + model.focus("OKLO"); XCTAssertEqual(model.focusedSymbol, "OKLO") + model.focus("OKLO"); XCTAssertNil(model.focusedSymbol) + } + } + + func testGlobeCoversBothHemispheresAndProjectionIsRound() { + let longitudes = (0.. 0 }.count, 8) + XCTAssertEqual(longitudes.filter { cos($0) < 0 }.count, 8) + XCTAssertGreaterThan(GlobeCoastlines.degrees.count, 500) + XCTAssertLessThan(GlobeCoastlines.degrees.count, 1200) + for latitude in stride(from: -80.0, through: 80, by: 20) { + let p = GlobeGeometry.project(latitude: latitude, longitude: 35, rotation: 2) + XCTAssertEqual(p.x*p.x+p.y*p.y+p.z*p.z, 1, accuracy: 1e-10) + } + XCTAssertLessThan(GlobeGeometry.project(latitude: 45, longitude: 0, rotation: 0).y, 0) + XCTAssertNil(GlobeCoordinate(latitude: .nan, longitude: 0)) + } + + func testTradingHoursRespectDSTWeekendsAndLunch() { + func date(_ text: String) -> Date { ISO8601DateFormatter().date(from: text)! } + XCTAssertFalse(TradingRegionActivity.newYork.isScheduledOpen(at: date("2026-03-06T14:29:00Z"))) + XCTAssertTrue(TradingRegionActivity.newYork.isScheduledOpen(at: date("2026-03-06T14:30:00Z"))) + XCTAssertTrue(TradingRegionActivity.newYork.isScheduledOpen(at: date("2026-03-09T13:30:00Z"))) + XCTAssertFalse(TradingRegionActivity.newYork.isScheduledOpen(at: date("2026-10-10T14:00:00Z"))) + XCTAssertTrue(TradingRegionActivity.tokyo.isScheduledOpen(at: date("2026-10-13T02:29:00Z"))) + XCTAssertFalse(TradingRegionActivity.tokyo.isScheduledOpen(at: date("2026-10-13T02:30:00Z"))) + XCTAssertTrue(TradingRegionActivity.tokyo.isScheduledOpen(at: date("2026-10-13T03:30:00Z"))) + XCTAssertFalse(TradingRegionActivity.tokyo.isScheduledOpen(at: date("2026-10-13T06:30:00Z"))) + } + + func testNativeTransitionStartsInPlaceAndFinishesOnTarget() { + for style in SceneTransitionStyle.allCases { + let incoming = ConsoleTransitionMotion(start: 100, duration: style.duration, style: style, direction: -1, incoming: true) + XCTAssertEqual(incoming.uniforms(at: 100).x, 0) + XCTAssertEqual(incoming.uniforms(at: 105).x, 1) + XCTAssertEqual(incoming.uniforms(at: 100).w, -1) + } + XCTAssertEqual(ConsoleTransitionMotion.ease(0), 0) + XCTAssertEqual(ConsoleTransitionMotion.ease(1), 1) + let samples = (0...100).map { ConsoleTransitionMotion.ease(Double($0)/100) } + XCTAssertEqual(samples, samples.sorted()) + } +} diff --git a/Tests/RetrolemetryTests/DarkTypographyTests.swift b/Tests/RetrolemetryTests/DarkTypographyTests.swift new file mode 100644 index 0000000..38dd1bf --- /dev/null +++ b/Tests/RetrolemetryTests/DarkTypographyTests.swift @@ -0,0 +1,79 @@ +import XCTest +import AppKit +import SwiftUI +@testable import Retrolemetry + +final class DarkTypographyTests: XCTestCase { + func testDimAppearanceOverridesEverySemanticRole() { + let typography = ConsoleTypography(groups: ["primary": 2.8, "dark": 1.4, "secondary": 3, + "frameHeader": 2.2, "frameFooter": 2.5]) + for role in ConsoleFontRole.allCases { + XCTAssertEqual(ConsoleTypography.resolvedRole(role, dimmed: true), .dark) + XCTAssertEqual(typography.scale(role, dimmed: true), 1.4) + XCTAssertEqual(typography.scale(role), typography[role]) + } + XCTAssertEqual(ConsoleFontRole.secondary.title, "Main text") + // Only the displayed name changes; existing saved/exported keys stay valid. + XCTAssertEqual(ConsoleFontRole.secondary.rawValue, "secondary") + } + + func testLegacyDimTextKeepsItsOriginalScaleUntilDarkIsAdjusted() { + var typography = ConsoleTypography(primary: 1.8, secondary: 1.35, other: 2) + XCTAssertEqual(typography.scale(.secondary, dimmed: true), 1.35) + XCTAssertEqual(typography.scale(.secondary, fallback: .primary, dimmed: true), 1.8) + XCTAssertEqual(typography.scale(.secondary, fallback: .other, dimmed: true), 2) + typography[.secondary] = 3 + XCTAssertEqual(typography.scale(.secondary, dimmed: true), 1.35) + typography[.dark] = 0.8 + XCTAssertEqual(typography.scale(.secondary, fallback: .other, dimmed: true), 0.8) + XCTAssertEqual(typography.secondary, 3) + XCTAssertEqual(typography.primary, 1.8) + } + + func testTickerHeaderAndClickGeometryFollowDarkNotMain() { + var typography = ConsoleTypography(groups: ["dark": 2, "secondary": 0.8]) + XCTAssertEqual(MarketTickerGeometry.headerHeight(typography), 22) + typography[.secondary] = 3 + XCTAssertEqual(MarketTickerGeometry.headerHeight(typography), 22) + typography[.dark] = 3 + XCTAssertEqual(MarketTickerGeometry.headerHeight(typography), 33) + } + + @MainActor + func testActualDimTextIgnoresMainSliderAndRespondsToDark() { + func measured(main: Double, dark: Double, dimmed: Bool) -> NSSize { + let root = Text("PORTFOLIO / LAST CHANGE") + .consoleFont(12, role: .secondary) + .consoleDimmed(dimmed) + .fixedSize() + .environment(\.consoleTypography, ConsoleTypography(groups: ["secondary": main, "dark": dark])) + return NSHostingView(rootView: root).fittingSize + } + let dimSmall = measured(main: 0.8, dark: 1.4, dimmed: true) + let dimLargeMain = measured(main: 3, dark: 1.4, dimmed: true) + XCTAssertGreaterThan(dimSmall.width, 0) + XCTAssertEqual(dimSmall.width, dimLargeMain.width, accuracy: 0.1) + XCTAssertEqual(dimSmall.height, dimLargeMain.height, accuracy: 0.1) + XCTAssertGreaterThan(measured(main: 0.8, dark: 3, dimmed: true).height, dimSmall.height) + let bright = measured(main: 1.4, dark: 0.8, dimmed: false) + XCTAssertEqual(bright.height, measured(main: 1.4, dark: 3, dimmed: false).height, accuracy: 0.1) + XCTAssertGreaterThan(measured(main: 3, dark: 0.8, dimmed: false).height, bright.height) + } + + @MainActor + func testDimContainerOverridesNestedExplicitFontRoles() { + func measured(dark: Double, primary: Double) -> NSSize { + let root = HStack { + Text("LAST").consoleFont(12, role: .secondary) + Text("USD 123.45").consoleFont(12, role: .primary) + } + .consoleDimmed() + .fixedSize() + .environment(\.consoleTypography, ConsoleTypography(groups: ["primary": primary, "secondary": 3, "dark": dark])) + return NSHostingView(rootView: root).fittingSize + } + let original = measured(dark: 1, primary: 1) + XCTAssertEqual(original.width, measured(dark: 1, primary: 3).width, accuracy: 0.1) + XCTAssertGreaterThan(measured(dark: 2, primary: 1).height, original.height) + } +} diff --git a/Tests/RetrolemetryTests/HardwareMetricsTests.swift b/Tests/RetrolemetryTests/HardwareMetricsTests.swift new file mode 100644 index 0000000..7166a56 --- /dev/null +++ b/Tests/RetrolemetryTests/HardwareMetricsTests.swift @@ -0,0 +1,49 @@ +import XCTest +@testable import Retrolemetry + +final class HardwareMetricsTests: XCTestCase { + func testGPUCounterUsesPercentAndAllowsRealZero() { + XCTAssertEqual(HardwareMetricsReader.gpuUsage(statistics: ["Device Utilization %": 68]), 0.68) + XCTAssertEqual(HardwareMetricsReader.gpuUsage(statistics: ["Device Utilization %": 0]), 0) + XCTAssertEqual(HardwareMetricsReader.gpuUsage(statistics: ["Device Utilization %": 100]), 1) + } + + func testGPUCounterRejectsMissingAndInvalidRatherThanInventingZero() { + for stats: [String: Any] in [[:], ["systemLoad": 8], ["Device Utilization %": -1], + ["Device Utilization %": 101], ["Device Utilization %": "busy"], + ["Device Utilization %": Double.nan]] { + XCTAssertNil(HardwareMetricsReader.gpuUsage(statistics: stats)) + } + } + + func testBatteryUnitsAndSignedCurrent() { + XCTAssertEqual(HardwareMetricsReader.volts(12161), 12.161) + XCTAssertEqual(HardwareMetricsReader.amps(-850), -0.85) + let unsignedDischarge = NSNumber(value: UInt64(bitPattern: Int64(-850))) + XCTAssertEqual(HardwareMetricsReader.amps(unsignedDischarge), -0.85) + let reading = PowerReading(voltage: 12, current: -0.85) + XCTAssertEqual(reading.watts!, 10.2, accuracy: 0.0001) + XCTAssertEqual(reading.status, "BATTERY DISCHARGE") + XCTAssertEqual(PowerReading(voltage: 12, current: 0, onACPower: true).watts, 0) + } + + func testUnavailablePowerIsNotReportedAsZero() { + XCTAssertNil(PowerReading().watts) + XCTAssertNil(PowerReading(voltage: 12).watts) + XCTAssertNil(PowerReading(current: 1).watts) + XCTAssertNil(HardwareMetricsReader.volts(0)) + XCTAssertNil(HardwareMetricsReader.volts(200_000)) + XCTAssertNil(HardwareMetricsReader.amps(200_000)) + XCTAssertEqual(PowerReading().status, "SENSOR UNAVAILABLE") + } + + func testHistoryDoesNotBridgeMissingOrInvalidSamples() { + let rect = CGRect(x: 10, y: 20, width: 100, height: 50) + let segments = UsageHistoryGeometry.segments([0, 1, nil, 0.5, .nan, 0.25], in: rect) + XCTAssertEqual(segments.map(\.count), [2, 1, 1]) + XCTAssertEqual(segments[0], [CGPoint(x: 10, y: 70), CGPoint(x: 30, y: 20)]) + XCTAssertEqual(segments[1][0], CGPoint(x: 70, y: 45)) + XCTAssertTrue(UsageHistoryGeometry.segments([nil, nil], in: rect).isEmpty) + XCTAssertTrue(UsageHistoryGeometry.segments([], in: rect).isEmpty) + } +} diff --git a/Tests/RetrolemetryTests/LayoutTests.swift b/Tests/RetrolemetryTests/LayoutTests.swift new file mode 100644 index 0000000..638378f --- /dev/null +++ b/Tests/RetrolemetryTests/LayoutTests.swift @@ -0,0 +1,49 @@ +import XCTest +@testable import Retrolemetry + +final class LayoutTests: XCTestCase { + func testMetricsDefaultsFitWithoutOverlap() { + let modules = LayoutDefaults.modules(for: .fullMetrics) + let frames = LayoutDefaults.frames(for: .fullMetrics) + XCTAssertEqual(modules.count, 13) + XCTAssertEqual(Set(modules.map(\.id)).count, modules.count) + XCTAssertEqual(Set(modules.map(\.id)), Set(frames.keys)) + for (id, frame) in frames { + XCTAssertTrue(frame.visible, id) + XCTAssertGreaterThanOrEqual(frame.x, 15, id) + XCTAssertGreaterThanOrEqual(frame.y, 45, id) + XCTAssertLessThanOrEqual(frame.rect.maxX, 945, id) + XCTAssertLessThanOrEqual(frame.rect.maxY, 505, id) + for (otherID, other) in frames where otherID != id { + XCTAssertFalse(frame.rect.intersects(other.rect), "\(id) overlaps \(otherID)") + } + } + } + + func testCustomFramesAndVisibilityArePreserved() { + let custom = ModuleFrame(x: 35, y: 90, width: 340, height: 220, visible: false) + let merged = LayoutDefaults.merging(["graphCPU": custom], for: .fullMetrics) + XCTAssertEqual(merged["graphCPU"], custom) + for id in ["metricGPU", "metricPower", "graphGPU"] { XCTAssertEqual(merged[id]?.visible, false) } + } + + func testUntouchedLegacyDefaultsCanAdoptExpandedLayout() { + let old = ModuleFrame(x: 28, y: 55, width: 217, height: 116) + let merged = LayoutDefaults.merging(["metricCPU": old], for: .fullMetrics) + XCTAssertEqual(merged, LayoutDefaults.frames(for: .fullMetrics)) + } + + func testNewModuleChoicesSurviveReload() { + var saved = LayoutDefaults.frames(for: .fullMetrics) + saved["metricGPU"]?.visible = false + saved["graphGPU"]?.x = 320 + XCTAssertEqual(LayoutDefaults.merging(saved, for: .fullMetrics), saved) + } + + func testUnrelatedSceneFramesAndPickerSelectionsArePreserved() { + let custom = ModuleFrame(x: 30, y: 70, width: 370, height: 370) + XCTAssertEqual(LayoutDefaults.merging(["radar": custom], for: .radar)["radar"], custom) + XCTAssertEqual(SignalDisplayMode(rawValue: "memoryHorizon"), .gpuHorizon) + XCTAssertEqual(SignalGridMetric(rawValue: "gpuProxy"), .gpu) + } +} diff --git a/Tests/RetrolemetryTests/PackagingTests.swift b/Tests/RetrolemetryTests/PackagingTests.swift new file mode 100644 index 0000000..b0c6ef3 --- /dev/null +++ b/Tests/RetrolemetryTests/PackagingTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import Retrolemetry + +final class PackagingTests: XCTestCase { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + + func testOnlyLocationResourceCapabilityIsDeclared() throws { + let data = try Data(contentsOf: root.appendingPathComponent("Resources/Retrolemetry.entitlements")) + let plist = try XCTUnwrap(PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Bool]) + XCTAssertEqual(plist, ["com.apple.security.personal-information.location": true]) + } + + func testBothSigningModesIncludeLocationEntitlements() throws { + let script = try String(contentsOf: root.appendingPathComponent("scripts/package_app.sh"), encoding: .utf8) + let signingCommands = script.split(separator: "\n").filter { $0.contains("codesign --force") } + XCTAssertEqual(signingCommands.count, 2) + for command in signingCommands { + XCTAssertTrue(command.contains("--entitlements Resources/Retrolemetry.entitlements")) + } + XCTAssertTrue(script.contains("Print :com.apple.security.personal-information.location")) + } +} diff --git a/Tests/RetrolemetryTests/RadarWeatherTests.swift b/Tests/RetrolemetryTests/RadarWeatherTests.swift new file mode 100644 index 0000000..eaf2cdd --- /dev/null +++ b/Tests/RetrolemetryTests/RadarWeatherTests.swift @@ -0,0 +1,75 @@ +import XCTest +@testable import Retrolemetry + +final class RadarWeatherTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_790_000_200) + + private func fixture(rain: Any = 30.0, temperature: Any = 24.0, wind: Any = 12.0) throws -> Data { + let hour = floor(now.timeIntervalSince1970 / 3600) * 3600 + let payloads: [[String: Any]] = RadarWeatherSite.all.map { site in + ["latitude": site.latitude, "longitude": site.longitude, + "current": ["time": now.timeIntervalSince1970, "temperature_2m": temperature, + "wind_speed_10m": wind, "wind_direction_10m": 270.0], + "hourly": ["time": [hour-3600, hour, hour+3600], "precipitation_probability": [80.0, rain, 90.0]]] + } + return try JSONSerialization.data(withJSONObject: payloads) + } + + func testBatchedForecastUsesCorrectLocationAndCurrentHour() throws { + let result = try RegionalWeatherFeed.decode(fixture(), at: now) + XCTAssertEqual(result.count, 6) + XCTAssertEqual(result.map(\.site), RadarWeatherSite.all) + XCTAssertEqual(result[2].site.name, "TEL AVIV") + XCTAssertEqual(result[2].rainChance, 0.3) + XCTAssertEqual(result[2].windDirection, 270) + XCTAssertEqual(result[2].readout(for: .wind), "12 KM/H") + XCTAssertEqual(result[2].readout(for: .precipitation), "30%") + } + + func testMissingAndInvalidValuesAreNotInventedZeroes() throws { + let missing = try RegionalWeatherFeed.decode(fixture(rain: NSNull(), temperature: NSNull(), wind: NSNull()), at: now) + XCTAssertNil(missing[0].rainChance); XCTAssertNil(missing[0].windSpeed) + XCTAssertEqual(missing[0].readout(for: .temperature), "N/A") + let invalid = try RegionalWeatherFeed.decode(fixture(rain: 110.0, temperature: -200.0, wind: -1.0), at: now) + XCTAssertNil(invalid[0].rainChance); XCTAssertNil(invalid[0].temperature); XCTAssertNil(invalid[0].windSpeed) + let zero = try RegionalWeatherFeed.decode(fixture(rain: 0.0, wind: 0.0), at: now) + XCTAssertEqual(zero[0].rainChance, 0); XCTAssertEqual(zero[0].windSpeed, 0) + } + + func testStaleOrMismatchedBatchCannotMasqueradeAsLiveWeather() throws { + XCTAssertThrowsError(try RegionalWeatherFeed.decode(fixture(), at: now.addingTimeInterval(7200))) + var payloads = try JSONSerialization.jsonObject(with: fixture()) as! [[String: Any]] + payloads[0]["latitude"] = 0.0 + XCTAssertThrowsError(try RegionalWeatherFeed.decode(JSONSerialization.data(withJSONObject: payloads), at: now)) + XCTAssertThrowsError(try RegionalWeatherFeed.decode(Data("[]".utf8), at: now)) + let offline = WeatherSnapshot() + XCTAssertTrue(radarTargets(for: offline, mode: .precipitation).isEmpty) + XCTAssertEqual(radarTargets(for: offline, mode: .decorative).count, 7) + } + + func testMapProjectionAndTargetsUseSameGeography() { + XCTAssertGreaterThan(RadarMapGeometry.segments.count, 100) + XCTAssertLessThan(RadarMapGeometry.segments.count, 300) + let north = RadarMapGeometry.position(latitude: 33.2, longitude: 35.5) + let south = RadarMapGeometry.position(latitude: 29.6, longitude: 34.9) + XCTAssertLessThan(north.y, south.y) + for edge in RadarMapGeometry.segments { + for value in [edge.x, edge.y, edge.z, edge.w] { XCTAssertTrue(value.isFinite); XCTAssertLessThan(abs(value), 1) } + } + var snapshot = WeatherSnapshot() + snapshot.radarWeather = RadarWeatherPoint.preview() + snapshot.radarUpdatedAt = Date() + let targets = radarTargets(for: snapshot, mode: .wind) + XCTAssertEqual(targets.count, 6) + let site = RadarWeatherSite.all[2] + XCTAssertEqual(targets[2].mapPosition, RadarMapGeometry.position(latitude: site.latitude, longitude: site.longitude)) + XCTAssertEqual(targets[2].heading, (snapshot.radarWeather[2].windDirection ?? 0) + 90) + } + + func testBatchRequestDoesNotSendPersonalLocationOrCredentials() { + let params = URLComponents(url: RegionalWeatherFeed.url, resolvingAgainstBaseURL: false)!.queryItems! + XCTAssertEqual(params.first { $0.name == "latitude" }?.value?.split(separator: ",").count, 6) + XCTAssertFalse(params.contains { ["apikey", "token"].contains($0.name) }) + XCTAssertEqual(params.first { $0.name == "wind_speed_unit" }?.value, "kmh") + } +} diff --git a/Tests/RetrolemetryTests/RegionTypographyTests.swift b/Tests/RetrolemetryTests/RegionTypographyTests.swift new file mode 100644 index 0000000..e41440a --- /dev/null +++ b/Tests/RetrolemetryTests/RegionTypographyTests.swift @@ -0,0 +1,101 @@ +import XCTest +import AppKit +@testable import Retrolemetry + +final class RegionTypographyTests: XCTestCase { + func testAutomaticRegionAndManualOverrideWithoutLocation() { + func place(_ lat: Double, _ lon: Double) -> GlobeCoordinate? { GlobeCoordinate(latitude: lat, longitude: lon) } + XCTAssertEqual(WeatherRegionSelection.automatic.resolve(coordinate: place(32.0853,34.7818)), .israel) + XCTAssertEqual(WeatherRegionSelection.automatic.resolve(coordinate: place(47.6062,-122.3321)), .northAmerica) + XCTAssertEqual(WeatherRegionSelection.automatic.resolve(coordinate: place(19.4326,-99.1332)), .northAmerica) + XCTAssertEqual(WeatherRegionSelection.automatic.resolve(coordinate: place(51.5074,-0.1278)), .europe) + XCTAssertNil(WeatherRegionSelection.automatic.resolve(coordinate: nil)) + XCTAssertNil(WeatherRegionSelection.automatic.resolve(coordinate: place(35.6762,139.6503))) + XCTAssertEqual(WeatherRegionSelection.europe.resolve(coordinate: nil), .europe) + XCTAssertEqual(WeatherRegionSelection.northAmerica.resolve(coordinate: place(32.1,34.8)), .northAmerica) + XCTAssertFalse(WeatherSnapshot().localForecastIsAvailable) + XCTAssertTrue(WeatherSnapshot(updatedAt: Date()).localForecastIsAvailable) + XCTAssertFalse(WeatherSnapshot(updatedAt: Date().addingTimeInterval(-7200)).localForecastIsAvailable) + } + + func testAllMapsAndSamplesShareBoundedProjection() { + for region in RadarRegion.allCases { + XCTAssertEqual(region.sites.count, 6) + XCTAssertGreaterThan(RadarMapGeometry.segments(for: region).count, 100) + XCTAssertLessThan(RadarMapGeometry.segments(for: region).count, 1600) + for edge in RadarMapGeometry.segments(for: region) { + for value in [edge.x,edge.y,edge.z,edge.w] { XCTAssertTrue(value.isFinite); XCTAssertLessThan(abs(value), 1.1) } + } + var snapshot = WeatherSnapshot() + snapshot.radarRegion = region + snapshot.radarWeather = RadarWeatherPoint.preview(region: region) + snapshot.radarUpdatedAt = Date() + let targets = radarTargets(for: snapshot, mode: .temperature) + XCTAssertEqual(targets.count, 6) + for (site, target) in zip(region.sites, targets) { + XCTAssertEqual(target.mapPosition, RadarMapGeometry.position(latitude: site.latitude, longitude: site.longitude, region: region)) + } + let parts = URLComponents(url: RegionalWeatherFeed.url(for: region), resolvingAgainstBaseURL: false)! + XCTAssertEqual(parts.queryItems?.first { $0.name == "latitude" }?.value, region.sites.map { String($0.latitude) }.joined(separator: ",")) + } + } + + func testFiveIndependentGroupsKeepLegacyAppearanceAndBackups() throws { + XCTAssertEqual(ConsoleFontRole.allCases.count, 5) + let data = Data("{\"primary\":1.8,\"secondary\":1.35,\"other\":2}".utf8) + var typography = try JSONDecoder().decode(ConsoleTypography.self, from: data) + XCTAssertEqual(typography.scale(.dark, fallback: .other), 2) + XCTAssertEqual(typography.scale(.secondary, fallback: .primary), 1.8) + XCTAssertEqual(typography[.frameHeader], 2) + XCTAssertEqual(typography[.frameFooter], 2) + typography[.secondary] = 2.4 + XCTAssertEqual(typography.scale(.secondary, fallback: .primary), 2.4) + XCTAssertEqual(typography.scale(.dark, fallback: .other), 2) + typography[.dark] = 0.85 + typography[.frameHeader] = 3 + XCTAssertEqual(typography.primary, 1.8) + XCTAssertEqual(typography[.frameFooter], 2) + XCTAssertEqual(typography.scale(.dark, fallback: .other), 0.85) + XCTAssertEqual(try JSONDecoder().decode(ConsoleTypography.self, from: JSONEncoder().encode(typography)), typography) + } + + func testGlobalAndPerViewFontGroupsPersistWithoutRewritingOldValues() async { + await MainActor.run { + let suite = "RetrolemetryTests.\(UUID())", defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set(1.8, forKey: "DockTelemetry.fontScale") + defaults.set(1.35, forKey: "DockTelemetry.secondaryFontScale") + defaults.set(2.0, forKey: "DockTelemetry.auxiliaryFontScale") + let before = defaults.persistentDomain(forName: suite)! as NSDictionary + let store = LayoutStore(defaults: defaults) + XCTAssertEqual(before, defaults.persistentDomain(forName: suite)! as NSDictionary) + let frame = store.frame(.radar,"radar") + store.setFontScale(2.5,role:.dark,scene:.radar) + store.setFontScale(3,role:.frameHeader,scene:.radar) + XCTAssertEqual(store.typography(for:.signal)[.dark],2.5) + XCTAssertEqual(store.typography(for:.signal)[.frameFooter],2) + store.globalTypographyEnabled = false + store.setFontScale(1.1,role:.frameFooter,scene:.radar) + let reload = LayoutStore(defaults:defaults) + XCTAssertEqual(reload.typography(for:.radar)[.frameFooter],1.1) + XCTAssertEqual(reload.typography(for:.system)[.frameFooter],2) + XCTAssertEqual(reload.frame(.radar,"radar"),frame) + XCTAssertEqual(defaults.double(forKey:"DockTelemetry.fontScale"),1.8) + XCTAssertEqual(defaults.double(forKey:"DockTelemetry.secondaryFontScale"),1.35) + } + } + + @MainActor + func testDoubleClickDoesNotRunSingleClickAction() async throws { + let view = HorizontalScrollView(frame: CGRect(x:0,y:0,width:960,height:540)) + var single = 0, double = 0 + view.onClick = { _ in single += 1 } + view.onDoubleClick = { double += 1 } + for count in [1,2] { + let event = NSEvent.mouseEvent(with:.leftMouseDown,location:NSPoint(x:40,y:40),modifierFlags:[],timestamp:ProcessInfo.processInfo.systemUptime,windowNumber:0,context:nil,eventNumber:count,clickCount:count,pressure:1)! + view.mouseDown(with:event) + } + try await Task.sleep(for:.seconds(NSEvent.doubleClickInterval+0.1)) + XCTAssertEqual(single,0); XCTAssertEqual(double,1) + } +} diff --git a/Tests/RetrolemetryTests/RenderingTests.swift b/Tests/RetrolemetryTests/RenderingTests.swift new file mode 100644 index 0000000..38f4049 --- /dev/null +++ b/Tests/RetrolemetryTests/RenderingTests.swift @@ -0,0 +1,76 @@ +import XCTest +@testable import Retrolemetry + +final class RenderingTests: XCTestCase { + func testGridAdvancesWithoutFrameStateWrites() { + let motion = SignalGridMotion(time: 100, metric: 0.75, response: .medium, animated: true) + let frame = motion.sample(at: 110) + XCTAssertEqual(frame.travel, 1.1, accuracy: 0.00001) + XCTAssertEqual(frame.wave, 12.25, accuracy: 0.00001) + XCTAssertEqual(frame.metric, 0.75, accuracy: 0.00001) + } + + func testGridRetargetingIsContinuousAndReflectsLoad() { + var motion = SignalGridMotion(time: 100, metric: 0.1, response: .high, animated: true) + let before = motion.sample(at: 102) + motion.retarget(at: 102, metric: 0.9, response: .high, animated: true) + let after = motion.sample(at: 102) + XCTAssertEqual(before.travel, after.travel) + XCTAssertEqual(before.wave, after.wave) + XCTAssertEqual(before.metric, after.metric, accuracy: 0.0000001) + XCTAssertGreaterThan(motion.sample(at: 103).metric, 0.89) + XCTAssertGreaterThan(motion.sample(at: 103).wave - after.wave, before.wave / 2) + } + + func testGridPauseDoesNotAccumulateMotion() { + var motion = SignalGridMotion(time: 100, metric: 0.5, response: .medium, animated: true) + motion.retarget(at: 102, metric: 0.5, response: .medium, animated: false) + let paused = motion.sample(at: 102) + XCTAssertEqual(motion.sample(at: 200).wave, paused.wave) + motion.retarget(at: 200, metric: 0.5, response: .medium, animated: true) + XCTAssertEqual(motion.sample(at: 200).wave, paused.wave) + XCTAssertGreaterThan(motion.sample(at: 201).wave, paused.wave) + } + + func testMetalUniformLayout() { + XCTAssertEqual(MemoryLayout.stride, 48) + XCTAssertEqual(MemoryLayout.alignment, 16) + XCTAssertEqual(MemoryLayout.stride, 160) + XCTAssertEqual(MemoryLayout.alignment, 16) + } + + func testRadarMapSegmentCountsMatchNativeBuffers() async { + await MainActor.run { + let suite = "RetrolemetryTests.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let store = LayoutStore(defaults: defaults) + for region in RadarRegion.allCases { + let configuration = VectorConfiguration(scene: .radar, layouts: store, + snapshot: TelemetrySnapshot(), gpuHistory: [], weather: WeatherSnapshot(radarRegion: region), tubeStrength: 0.35, bloom: 0.7) + XCTAssertEqual(configuration.uniforms.extra.z, Float(RadarMapGeometry.segments(for: region).count)) + XCTAssertEqual(configuration.uniforms.extra.w, Float(RadarMapGeometry.countrySegmentCount(for: region))) + XCTAssertEqual(configuration.segmentCount, 412 + RadarMapGeometry.segments(for: region).count + configuration.targets.count * 32) + } + XCTAssertEqual(MemoryLayout>.stride, 16) + } + } + + func testVectorHistoryPreservesZeroAndUnavailableGaps() async { + await MainActor.run { + let configuration = VectorConfiguration( + scene: .signal, layouts: LayoutStore.shared, + snapshot: TelemetrySnapshot(), gpuHistory: [0, .nan, nil, 1, 1.5], + weather: WeatherSnapshot(), tubeStrength: 0.35, bloom: 0.8 + ) + XCTAssertEqual(Array(configuration.history.prefix(5)), [0, -1, -1, 1, -1]) + XCTAssertEqual(configuration.history.count, 96) + let saved = LayoutStore.shared.frame(.signal, "scope") + XCTAssertEqual(configuration.visible, saved.visible) + if saved.visible { + XCTAssertEqual(configuration.uniforms.rect.x, Float(saved.x)) + XCTAssertEqual(configuration.uniforms.rect.z, Float(saved.width)) + } + } + } +} diff --git a/Tests/RetrolemetryTests/TelemetryPanelTests.swift b/Tests/RetrolemetryTests/TelemetryPanelTests.swift new file mode 100644 index 0000000..81e25e8 --- /dev/null +++ b/Tests/RetrolemetryTests/TelemetryPanelTests.swift @@ -0,0 +1,188 @@ +import XCTest +import SwiftUI +import AppKit +@testable import Retrolemetry + +final class TelemetryPanelTests: XCTestCase { + func testCompactCapacityUnitsKeepPrecisionAndUseLessSpace() { + XCTAssertEqual(CapacitySideReading.compactAmount(32_600_000_000), "32.6GB") + XCTAssertEqual(CapacitySideReading.compactAmount(19_200_000_000), "19.2GB") + XCTAssertEqual(CapacitySideReading.compactAmount(2_500_000_000_000), "2.50TB") + XCTAssertEqual(CapacitySideReading.compactAmount(nil), "N/A") + XCTAssertEqual(CapacitySideReading.compactAmount(.nan), "N/A") + let attributes: [NSAttributedString.Key: Any] = [.font: NSFont.monospacedSystemFont(ofSize: 20, weight: .bold)] + let compact = (CapacitySideReading.compactAmount(32_600_000_000) as NSString).size(withAttributes: attributes) + let original = (capacityAmount(32_600_000_000) as NSString).size(withAttributes: attributes) + XCTAssertLessThan(compact.width, original.width) + XCTAssertFalse(CapacitySideReading.compactAmount(19_200_000_000).contains(where: \.isWhitespace)) + } + + @MainActor + func testCapacitySideTypeIsTwentyPercentSmallerWithCloseLabel() { + let actual = NSHostingView(rootView: + CapacitySideReading(title: "USED", bytes: 32_600_000_000, fit: 1) + .fixedSize() + .environment(\.consoleTypography, ConsoleTypography()) + ).fittingSize + let expected = NSHostingView(rootView: + VStack(spacing: 1) { + Text("USED").font(.system(size: 13 * 0.8, weight: .bold, design: .monospaced)) + Text("32.6GB").font(.system(size: 20 * 0.8, weight: .bold, design: .monospaced)) + }.fixedSize() + ).fittingSize + XCTAssertGreaterThan(actual.width, 0) + XCTAssertEqual(actual.width, expected.width, accuracy: 0.1) + XCTAssertEqual(actual.height, expected.height, accuracy: 0.1) + } + + @MainActor + func testCapacitySideReadingsFollowDarkTextNotMetricsSlider() { + func measured(dark: Double, primary: Double) -> NSSize { + let root = CapacitySideReading(title: "USED", bytes: 32_600_000_000, fit: 1) + .fixedSize() + .environment(\.consoleTypography, ConsoleTypography(groups: ["primary": primary, "secondary": 3, "dark": dark])) + return NSHostingView(rootView: root).fittingSize + } + let original = measured(dark: 1, primary: 1) + let largerMetrics = measured(dark: 1, primary: 3) + XCTAssertGreaterThan(original.width, 0) + XCTAssertEqual(original.width, largerMetrics.width, accuracy: 0.1) + XCTAssertEqual(original.height, largerMetrics.height, accuracy: 0.1) + XCTAssertGreaterThan(measured(dark: 2, primary: 1).width, original.width) + XCTAssertGreaterThan(measured(dark: 2, primary: 1).height, original.height) + } + + func testCapacityCountsAndPercentageAgree() throws { + let reading = try XCTUnwrap(CapacityReading(totalBytes: 1_000_000_000_000, usedBytes: 970_000_000_000)) + XCTAssertEqual(reading.freeBytes, 30_000_000_000) + XCTAssertEqual(reading.usedBytes + reading.freeBytes, reading.totalBytes) + XCTAssertEqual(reading.fractionUsed, 0.97) + XCTAssertEqual(capacityAmount(reading.usedBytes), "970.0 GB") + XCTAssertEqual(capacityAmount(reading.freeBytes), "30.0 GB") + XCTAssertEqual(capacityAmount(2_500_000_000_000), "2.50 TB") + XCTAssertEqual(capacityAmount(0), "0.0 GB") + } + + func testMemoryUsesHostPageSizeAndPhysicalTotal() throws { + for pageSize: UInt64 in [4096, 16384] { + let reading = try XCTUnwrap(CapacityReading.memory(active: 100, wired: 200, compressed: 300, + pageSize: pageSize, physicalBytes: 1000 * pageSize)) + XCTAssertEqual(reading.usedBytes, Double(600 * pageSize)) + XCTAssertEqual(reading.freeBytes, Double(400 * pageSize)) + XCTAssertEqual(reading.fractionUsed, 0.6) + } + } + + func testInvalidCapacityIsUnavailableNotZero() { + for (total, used): (Double, Double) in [(0, 0), (-1, 0), (100, -1), (100, 101), (.nan, 10), (100, .infinity)] { + XCTAssertNil(CapacityReading(totalBytes: total, usedBytes: used)) + } + XCTAssertNil(CapacityReading.memory(active: 1, wired: 1, compressed: 1, pageSize: 0, physicalBytes: 100)) + XCTAssertEqual(capacityAmount(nil), "N/A") + XCTAssertEqual(capacityAmount(.nan), "N/A") + } + + func testDuplexGraphHasCommonScaleWithoutOldSpeedCeiling() { + let scale = NetworkHistoryGeometry.scale(receive: [0, 20_000_000], transmit: [0, 5_000_000]) + XCTAssertEqual(scale, 20_000_000) + let top = CGRect(x: 0, y: 0, width: 100, height: 50) + let bottom = CGRect(x: 0, y: 50, width: 100, height: 50) + let tx = NetworkHistoryGeometry.segments([0, 5_000_000], in: top, scale: scale, transmit: true)[0] + let rx = NetworkHistoryGeometry.segments([0, 20_000_000], in: bottom, scale: scale, transmit: false)[0] + XCTAssertEqual(tx, [CGPoint(x: 0, y: 50), CGPoint(x: 100, y: 37.5)]) + XCTAssertEqual(rx, [CGPoint(x: 0, y: 50), CGPoint(x: 100, y: 100)]) + // The same byte rate has the same height, reflected across the center. + let equalRX = NetworkHistoryGeometry.segments([0, 5_000_000], in: bottom, scale: scale, transmit: false)[0] + XCTAssertEqual(50 - tx[1].y, equalRX[1].y - 50) + } + + func testDuplexGraphZerosAndInvalidSamples() { + XCTAssertEqual(NetworkHistoryGeometry.scale(receive: [], transmit: [.nan, -1]), 1000) + let rect = CGRect(x: 10, y: 20, width: 100, height: 50) + let segments = NetworkHistoryGeometry.segments([0, 1000, .nan, 500, -1, 250], in: rect, scale: 1000, transmit: true) + XCTAssertEqual(segments.map(\.count), [2, 1, 1]) + XCTAssertEqual(segments[0].first, CGPoint(x: 10, y: 70)) + XCTAssertTrue(segments.flatMap { $0 }.allSatisfy { + $0.x.isFinite && $0.y.isFinite && (rect.minX...rect.maxX).contains($0.x) && (rect.minY...rect.maxY).contains($0.y) + }) + XCTAssertTrue(NetworkHistoryGeometry.segments([], in: rect, scale: 1000, transmit: false).isEmpty) + XCTAssertTrue(NetworkHistoryGeometry.segments([100], in: .zero, scale: 1000, transmit: false).isEmpty) + } + + func testNetworkReadoutKeepsSavedIDAndCustomFrame() { + let saved = ModuleFrame(x: 630, y: 401, width: 290, height: 98, visible: true) + let merged = LayoutDefaults.merging(["statusTX": saved], for: .fullMetrics) + XCTAssertEqual(merged["statusTX"], saved) + XCTAssertTrue(LayoutDefaults.modules(for: .fullMetrics).contains { $0.id == "statusTX" }) + } + + @MainActor + func testLiveCapacitySamplesAndSeparateHistoriesAreConsistent() throws { + let model = TelemetryModel() + let memory = try XCTUnwrap(model.snapshot.memoryCapacity) + let disk = try XCTUnwrap(model.snapshot.diskCapacity) + XCTAssertEqual(memory.totalBytes, Double(ProcessInfo.processInfo.physicalMemory)) + XCTAssertEqual(model.snapshot.memory, memory.fractionUsed) + XCTAssertEqual(model.snapshot.disk, disk.fractionUsed) + XCTAssertEqual(memory.usedBytes + memory.freeBytes, memory.totalBytes) + XCTAssertEqual(disk.usedBytes + disk.freeBytes, disk.totalBytes) + XCTAssertEqual(model.networkReceiveHistory.count, 96) + XCTAssertEqual(model.networkTransmitHistory.count, 96) + XCTAssertEqual(model.networkReceiveHistory.last, model.snapshot.networkIn) + XCTAssertEqual(model.networkTransmitHistory.last, model.snapshot.networkOut) + } + + /// Synthetic panel-only captures: no production preferences, API keys, location or network requests. + @MainActor + func testNativePanelsRenderAtAllTextSizesAndThemes() throws { + let suite = "RetrolemetryTests.Panels.\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + let oldPalette = ThemeRuntime.palette + defer { defaults.removePersistentDomain(forName: suite); ThemeRuntime.palette = oldPalette } + let rx = (0..<96).map { 150_000 + max(0, sin(Double($0) * 0.29)) * 20_000_000 } + let tx = (0..<96).map { 90_000 + max(0, cos(Double($0) * 0.41)) * 9_000_000 } + let cpu = (0..<96).map { 0.4 + sin(Double($0) * 0.2) * 0.15 } + for style in ConsoleStyle.allCases { + defaults.set(style.rawValue, forKey: "DockTelemetry.visualStyle") + ThemeRuntime.palette = style.palette + for scale in [1.0, 2.0, 3.0] { + let root = VStack(spacing: 14) { + HStack(spacing: 14) { + LargeMetricTile(label: "MEMORY", value: "076%", level: 0.76, showsCapacity: true, + capacity: CapacityReading(totalBytes: 32_000_000_000, usedBytes: 24_320_000_000)) + LargeMetricTile(label: "DISK USED", value: "097%", level: 0.97, showsCapacity: true, + capacity: CapacityReading(totalBytes: 1_000_000_000_000, usedBytes: 970_000_000_000)) + }.frame(height: 116) + HStack(alignment: .top, spacing: 14) { + VStack(spacing: 14) { + MiniTrace(label: "CPU", values: cpu, value: "40%") + MiniTrace(label: "MEMORY", values: cpu, value: "76%") + }.frame(width: 200, height: 170) + VStack(spacing: 12) { + NetworkTrafficPanel(transmit: 683_000, receiveHistory: rx, transmitHistory: tx) + .frame(height: 240) + LargeStatusReadout(label: "NETWORK RX", value: "19.7 MB/S").frame(height: 95) + }.frame(width: 300) + LargeDataGraph(label: "CPU // 96 SEC", value: "040%", values: cpu) + .frame(height: 240) + } + Spacer(minLength: 0) + } + .padding(16).frame(width: 960, height: 540) + .foregroundStyle(phosphor).background(Color.black) + .defaultAppStorage(defaults) + .environment(\.consoleTypography, ConsoleTypography(primary: scale, secondary: scale, other: scale)) + let renderer = ImageRenderer(content: root) + renderer.scale = 1 + let cgImage = try XCTUnwrap(renderer.cgImage) + XCTAssertEqual(cgImage.width, 960) + XCTAssertEqual(cgImage.height, 540) + if let output = ProcessInfo.processInfo.environment["RETROLEMETRY_QA_OUTPUT"] { + let bitmap = NSBitmapImageRep(cgImage: cgImage) + let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + try png.write(to: URL(fileURLWithPath: output).appendingPathComponent("panels-\(style.rawValue)-\(Int(scale * 100)).png")) + } + } + } + } +} diff --git a/Tests/RetrolemetryTests/UpdaterTests.swift b/Tests/RetrolemetryTests/UpdaterTests.swift new file mode 100644 index 0000000..ce4c43e --- /dev/null +++ b/Tests/RetrolemetryTests/UpdaterTests.swift @@ -0,0 +1,36 @@ +import XCTest +@testable import Retrolemetry + +final class UpdaterTests: XCTestCase { + private var info: [String: Any] { + ["SUFeedURL": UpdateConfiguration.feedURL, + "SUPublicEDKey": "rPCCnQ2uJbuBh7gnxN4ObX9SJGh+JLGDhiy8Qr9BeF8=", + "SURequireSignedFeed": true, "SUVerifyUpdateBeforeExtraction": true, + "SUSignedFeedFailureExpirationInterval": 0] + } + + func testDedicatedHTTPSConfiguration() { + XCTAssertTrue(UpdateConfiguration.isValid(info)) + XCTAssertEqual(UpdateConfiguration.bundleIdentifier, "io.github.SamSpring.Retrolemetry") + XCTAssertEqual(UpdateConfiguration.feedURL, "https://samspring.github.io/Retrolemetry/appcast.xml") + } + + func testMissingKeyOrWeakValidationCannotStart() { + for field in ["SUPublicEDKey", "SUVerifyUpdateBeforeExtraction", "SURequireSignedFeed", "SUSignedFeedFailureExpirationInterval"] { + var invalid = info + invalid.removeValue(forKey: field) + XCTAssertFalse(UpdateConfiguration.isValid(invalid)) + } + var invalid = info + invalid["SUPublicEDKey"] = "invalid" + XCTAssertFalse(UpdateConfiguration.isValid(invalid)) + } + + func testUnrelatedOrInsecureFeedsCannotStart() { + for feed in ["http://samspring.github.io/Retrolemetry/appcast.xml", "https://samspring.github.io/SpaceBar/appcast.xml"] { + var invalid = info + invalid["SUFeedURL"] = feed + XCTAssertFalse(UpdateConfiguration.isValid(invalid)) + } + } +} diff --git a/Tests/RetrolemetryTests/WeatherFeedTests.swift b/Tests/RetrolemetryTests/WeatherFeedTests.swift new file mode 100644 index 0000000..e4a46f4 --- /dev/null +++ b/Tests/RetrolemetryTests/WeatherFeedTests.swift @@ -0,0 +1,106 @@ +import XCTest +@testable import Retrolemetry + +final class WeatherFeedTests: XCTestCase { + private let fixture = Data(""" + {"current":{"temperature_2m":24.1,"apparent_temperature":25.0,"relative_humidity_2m":58,"precipitation":0,"weather_code":2,"wind_speed_10m":12}, + "hourly":{"time":[1792231200,1792234800],"temperature_2m":[24.1,23.8],"precipitation_probability":[5,10],"weather_code":[2,2]}, + "daily":{"time":[1792184400],"weather_code":[2],"temperature_2m_max":[25.0],"temperature_2m_min":[19.1],"precipitation_probability_max":[10]}} + """.utf8) + + private func session(statuses: [Int], data: Data) -> URLSession { + WeatherFeedStub.reset(statuses, data: data) + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [WeatherFeedStub.self] + config.urlCache = nil + return URLSession(configuration: config) + } + + func testTransientProviderFailureRecoversAndDecodesForecast() async throws { + let session = session(statuses: [503, 200], data: fixture) + defer { session.invalidateAndCancel() } + let payload = try await LocalWeatherFeed.fetch(latitude: 0, longitude: 0, session: session, retryDelays: [0, 0]) + XCTAssertEqual(WeatherFeedStub.calls, 2) + XCTAssertEqual(payload.current.temperature2m, 24.1) + XCTAssertEqual(payload.hourly.temperature2m, [24.1, 23.8]) + XCTAssertEqual(payload.daily.temperature2mMin, [19.1]) + } + + func testPersistentFailureIsBoundedToThreeAttempts() async { + let session = session(statuses: [503, 503, 503, 200], data: fixture) + defer { session.invalidateAndCancel() } + do { + _ = try await LocalWeatherFeed.fetch(latitude: 0, longitude: 0, session: session, retryDelays: [0, 0, 0, 0]) + XCTFail("Persistent server failure must not be accepted") + } catch { + XCTAssertEqual(WeatherFeedFailure.status(for: error), "WEATHER PROVIDER // HTTP 503") + } + XCTAssertEqual(WeatherFeedStub.calls, 3) + } + + func testInvalidPayloadDoesNotLoopOrInventReadings() async { + let session = session(statuses: [200, 200], data: Data("{}".utf8)) + defer { session.invalidateAndCancel() } + do { + _ = try await LocalWeatherFeed.fetch(latitude: 0, longitude: 0, session: session, retryDelays: [0, 0]) + XCTFail("Missing weather readings must not become zeros") + } catch { + XCTAssertEqual(WeatherFeedFailure.status(for: error), "WEATHER DATA INCOMPLETE") + } + XCTAssertEqual(WeatherFeedStub.calls, 1) + } + + func testCancellationStopsBackoffAndFurtherRequests() async throws { + let session = session(statuses: [503, 200], data: fixture) + defer { session.invalidateAndCancel() } + let task = Task { try await LocalWeatherFeed.fetch(latitude: 0, longitude: 0, session: session, retryDelays: [30, 30]) } + for _ in 0..<50 where WeatherFeedStub.calls == 0 { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertEqual(WeatherFeedStub.calls, 1) + task.cancel() + do { _ = try await task.value; XCTFail("Cancelled request must stop") } + catch { XCTAssertTrue(error is CancellationError) } + XCTAssertEqual(WeatherFeedStub.calls, 1) + } + + func testRequestAndPrivacySafeErrorContract() throws { + let url = try LocalWeatherFeed.url(latitude: 0, longitude: 0) + XCTAssertEqual(url.scheme, "https") + XCTAssertEqual(url.host, "api.open-meteo.com") + let query = URLComponents(url: url, resolvingAgainstBaseURL: false)!.queryItems! + XCTAssertEqual(query.first { $0.name == "forecast_days" }?.value, "7") + XCTAssertFalse(query.contains { $0.name == "token" || $0.name == "apikey" }) + XCTAssertThrowsError(try LocalWeatherFeed.url(latitude: .nan, longitude: 0)) + XCTAssertThrowsError(try LocalWeatherFeed.url(latitude: 91, longitude: 0)) + XCTAssertFalse(WeatherFeedFailure.canRetry(WeatherFeedFailure.http(429))) + XCTAssertFalse(WeatherFeedFailure.canRetry(WeatherFeedFailure.http(403))) + XCTAssertFalse(WeatherFeedFailure.canRetry(URLError(.cancelled))) + XCTAssertEqual(WeatherFeedFailure.status(for: URLError(.timedOut)), "WEATHER CONNECTION // -1001") + } +} + +private final class WeatherFeedStub: URLProtocol, @unchecked Sendable { + private static let lock = NSLock() + nonisolated(unsafe) private static var statuses: [Int] = [] + nonisolated(unsafe) private static var data = Data() + nonisolated(unsafe) private static var count = 0 + static var calls: Int { lock.lock(); defer { lock.unlock() }; return count } + + static func reset(_ statuses: [Int], data: Data) { + lock.lock(); defer { lock.unlock() } + self.statuses = statuses; self.data = data; count = 0 + } + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + Self.lock.lock() + let code = Self.statuses.isEmpty ? 503 : Self.statuses.removeFirst() + let data = Self.data + Self.count += 1 + Self.lock.unlock() + let response = HTTPURLResponse(url: request.url!, statusCode: code, httpVersion: "HTTP/1.1", headerFields: [:])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} diff --git a/assets/screenshots/README.md b/assets/screenshots/README.md new file mode 100644 index 0000000..fce4af5 --- /dev/null +++ b/assets/screenshots/README.md @@ -0,0 +1,11 @@ +# Screenshot assets + +Add release screenshots here with descriptive lowercase filenames, for example: + +- `retrolemetry-system-telemetry.png` +- `retrolemetry-sector-scan.png` +- `retrolemetry-settings.png` + +The first release includes isolated 960×540 captures of Signal Analysis, Local Weather Radar, and Live System Metrics. They contain no desktop, menu-bar, account, API-key, or precise-location information. + +Capture future console images at native resolution and review every image before publishing. Avoid personal location details, menu-bar account information, and unrelated desktop content. diff --git a/assets/screenshots/retrolemetry-live-system-metrics.png b/assets/screenshots/retrolemetry-live-system-metrics.png new file mode 100644 index 0000000..dbb6e02 Binary files /dev/null and b/assets/screenshots/retrolemetry-live-system-metrics.png differ diff --git a/assets/screenshots/retrolemetry-local-weather-radar.png b/assets/screenshots/retrolemetry-local-weather-radar.png new file mode 100644 index 0000000..d3f0051 Binary files /dev/null and b/assets/screenshots/retrolemetry-local-weather-radar.png differ diff --git a/assets/screenshots/retrolemetry-signal-analysis.png b/assets/screenshots/retrolemetry-signal-analysis.png new file mode 100644 index 0000000..024685a Binary files /dev/null and b/assets/screenshots/retrolemetry-signal-analysis.png differ diff --git a/design-qa.md b/design-qa.md new file mode 100644 index 0000000..c70f43c --- /dev/null +++ b/design-qa.md @@ -0,0 +1,48 @@ +# Design QA — graph headers and daily forecast temperatures + +- Source visual truth: `codex-clipboard-58505b4f-3011-4e9b-afee-f84332200aa3.png` and `codex-clipboard-aea7a765-285d-4ded-a17b-ed91b49ba80d.png` (user-provided session attachments) +- Implementation screenshots: `Retrolemetry Screenshot 2026-08-17 at 16.46.07.jpeg` and `Retrolemetry Screenshot 2026-08-17 at 16.46.24.jpeg` (local QA captures) +- Comparison boards: `/tmp/retrolemetry-metrics-qa.png` and `/tmp/retrolemetry-weather-qa.png` +- Viewport: 960 × 540 points at native app capture density +- Source pixels: 1350 × 504 and 280 × 296 +- Implementation pixels: 960 × 540 for both scenes +- Normalization: each source image was proportionally fitted or padded to a 960 × 540 comparison panel and placed beside the corresponding 960 × 540 implementation capture +- State: installed app, saved synthwave palette and saved typography/layout preferences, live System Metrics and settled Weather scenes + +## Full-view comparison evidence + +- System Metrics: each graph trace is confined to a canvas below a dedicated header band; no trace crosses the title or current-value text. +- Weather: all five daily low/high pairs render as full degree values rather than ellipses, with stronger size and weight than supporting forecast copy. + +The supplied sources are focused failure captures, so the side-by-side boards use those focused regions beside the full 960 × 540 scene. Separate focused implementation crops were not needed because both corrected regions are clearly readable in the native captures. + +## Required fidelity surfaces + +- Fonts and typography: existing monospaced family, weights, and runtime scaling are preserved. Daily temperatures now use the primary type scale and remain untruncated. +- Spacing and layout rhythm: graph headers have a reserved vertical band and separator. Daily LOW, HIGH, and RAIN columns have explicit aligned widths. +- Colors and visual tokens: existing cyan/magenta synthwave tokens and contrast are unchanged. +- Image quality and asset fidelity: no raster assets are involved; the procedural vectors remain sharp at native resolution. +- Copy and content: labels, live readings, forecast conditions, and units are unchanged. + +## Comparison history + +1. Earlier P1: graph traces crossed the large graph title/value text. Fix: moved graph titles into a separate, intrinsic-height header above the clipped graph canvas. Post-fix evidence: `/tmp/retrolemetry-metrics-qa.png`. +2. Earlier P1: daily low/high temperatures collapsed to ellipses and were visually too small. Fix: gave LOW and HIGH dedicated 52-point columns and primary-scale 13-point bold type. Post-fix evidence: `/tmp/retrolemetry-weather-qa.png`. + +## Findings + +No actionable P0, P1, or P2 issues remain in the requested regions. + +## Implementation checklist + +- [x] Keep every full-metrics trace below its label/value header. +- [x] Preserve behavior under saved typography scaling. +- [x] Enlarge and align daily low/high temperatures. +- [x] Prevent daily temperatures from truncating. +- [x] Verify both settled live scenes in the installed app. + +## Follow-up polish + +No P3 follow-up is required for this change. + +final result: passed diff --git a/scripts/embed_sparkle.sh b/scripts/embed_sparkle.sh new file mode 100644 index 0000000..380038c --- /dev/null +++ b/scripts/embed_sparkle.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Copy intact framework symlinks, then sign nested code from the inside out. +set -eu +[ "$#" = 2 ] || { echo 'Usage: embed_sparkle.sh APP FRAMEWORK' >&2; exit 2; } +APP="$1" +SOURCE="$2" +FRAMEWORK="$APP/Contents/Frameworks/Sparkle.framework" +[ -d "$SOURCE" ] || { echo 'Sparkle framework is missing. Run swift package resolve.' >&2; exit 1; } +[ ! -e "$FRAMEWORK" ] || { echo 'Refusing to replace an existing framework.' >&2; exit 1; } +mkdir -p "$APP/Contents/Frameworks" +ditto --noextattr --norsrc "$SOURCE" "$FRAMEWORK" +for relative in Versions/B/XPCServices/Downloader.xpc Versions/B/XPCServices/Installer.xpc \ + Versions/B/Autoupdate Versions/B/Updater.app .; do + target="$FRAMEWORK/$relative" + [ -e "$target" ] || { echo "Unexpected Sparkle structure: $relative" >&2; exit 1; } + if [ -n "${CODESIGN_IDENTITY:-}" ]; then + codesign --force --sign "$CODESIGN_IDENTITY" --options runtime --timestamp --preserve-metadata=entitlements "$target" + else + # CI/local builds have no hardened-runtime library-validation requirement. + codesign --force --sign - --timestamp=none --preserve-metadata=entitlements "$target" + fi +done +codesign --verify --deep --strict "$FRAMEWORK" diff --git a/scripts/notarize_app.sh b/scripts/notarize_app.sh new file mode 100755 index 0000000..3e99b3c --- /dev/null +++ b/scripts/notarize_app.sh @@ -0,0 +1,38 @@ +#!/bin/sh +set -eu + +APP_BUNDLE="${1:-build/Retrolemetry.app}" +NOTARY_PROFILE="${NOTARY_PROFILE:-}" +DIST_DIR="${DIST_DIR:-dist}" +VERSION="${VERSION:-1.0.0}" + +if [ -z "$NOTARY_PROFILE" ]; then + echo "Set NOTARY_PROFILE to a notarytool keychain profile." >&2 + exit 1 +fi + +if [ ! -d "$APP_BUNDLE" ]; then + echo "App bundle not found: $APP_BUNDLE" >&2 + exit 1 +fi + +mkdir -p "$DIST_DIR" +case "$DIST_DIR" in + /*) DIST_PATH="$DIST_DIR" ;; + *) DIST_PATH="$PWD/$DIST_DIR" ;; +esac +SUBMISSION="$DIST_PATH/Retrolemetry-$VERSION-notarization.zip" +FINAL_ARCHIVE="$DIST_PATH/Retrolemetry-$VERSION.zip" +APP_PARENT=$(cd "$(dirname "$APP_BUNDLE")" && pwd) +APP_BASENAME=$(basename "$APP_BUNDLE") + +codesign --verify --deep --strict --verbose=2 "$APP_BUNDLE" +rm -f "$SUBMISSION" +(cd "$APP_PARENT" && COPYFILE_DISABLE=1 /usr/bin/zip -qry "$SUBMISSION" "$APP_BASENAME") +xcrun notarytool submit "$SUBMISSION" --keychain-profile "$NOTARY_PROFILE" --wait +xcrun stapler staple "$APP_BUNDLE" +xcrun stapler validate "$APP_BUNDLE" +rm -f "$FINAL_ARCHIVE" +(cd "$APP_PARENT" && COPYFILE_DISABLE=1 /usr/bin/zip -qry "$FINAL_ARCHIVE" "$APP_BASENAME") + +echo "Created notarized archive $FINAL_ARCHIVE" diff --git a/scripts/package_app.sh b/scripts/package_app.sh new file mode 100755 index 0000000..8ad2b46 --- /dev/null +++ b/scripts/package_app.sh @@ -0,0 +1,87 @@ +#!/bin/sh +set -eu + +APP_NAME="Retrolemetry" +VERSION="${VERSION:-1.0.0}" +BUILD_NUMBER="${BUILD_NUMBER:-$(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' Resources/Info.plist)}" +CONFIGURATION="${CONFIGURATION:-release}" +OUTPUT_DIR="${OUTPUT_DIR:-build}" +DIST_DIR="${DIST_DIR:-dist}" +INFO_PLIST="Resources/Info.plist" +SWIFT_SCRATCH_PATH="${SWIFT_SCRATCH_PATH:-.build}" + +OUTPUT_APP="$OUTPUT_DIR/$APP_NAME.app" +STAGING_DIR=$(mktemp -d "${TMPDIR:-/tmp}/retrolemetry-package.XXXXXX") +trap 'rm -rf "$STAGING_DIR"' EXIT HUP INT TERM +APP_BUNDLE="$STAGING_DIR/$APP_NAME.app" +CONTENTS="$APP_BUNDLE/Contents" + +if [ -n "${PREBUILT_BINARY:-}" ]; then + BINARY="$PREBUILT_BINARY" +elif [ "${UNIVERSAL:-0}" = "1" ]; then + swift build --scratch-path "$SWIFT_SCRATCH_PATH" -c "$CONFIGURATION" --arch arm64 --arch x86_64 + BIN_DIR=$(swift build --scratch-path "$SWIFT_SCRATCH_PATH" -c "$CONFIGURATION" --arch arm64 --arch x86_64 --show-bin-path) + BINARY="$BIN_DIR/$APP_NAME" +else + swift build --scratch-path "$SWIFT_SCRATCH_PATH" -c "$CONFIGURATION" + BIN_DIR=$(swift build --scratch-path "$SWIFT_SCRATCH_PATH" -c "$CONFIGURATION" --show-bin-path) + BINARY="$BIN_DIR/$APP_NAME" +fi + +mkdir -p "$CONTENTS/MacOS" "$CONTENTS/Resources" "$OUTPUT_DIR" "$DIST_DIR" +cp "$BINARY" "$CONTENTS/MacOS/$APP_NAME" +cp "$INFO_PLIST" "$CONTENTS/Info.plist" +cp LICENSE "$CONTENTS/Resources/Retrolemetry-LICENSE.txt" +cp NOTICE.txt "$CONTENTS/Resources/Retrolemetry-NOTICE.txt" + +# SwiftPM links Sparkle but does not assemble the .app. Keep helpers, symlinks +# and signatures intact, and re-sign nested code before signing the outer app. +SPARKLE_FRAMEWORK="${SPARKLE_FRAMEWORK:-$SWIFT_SCRATCH_PATH/artifacts/sparkle/Sparkle/Sparkle.xcframework/macos-arm64_x86_64/Sparkle.framework}" +sh scripts/embed_sparkle.sh "$APP_BUNDLE" "$SPARKLE_FRAMEWORK" +cp "${SPARKLE_LICENSE:-$SWIFT_SCRATCH_PATH/artifacts/sparkle/Sparkle/LICENSE}" "$CONTENTS/Resources/Sparkle-LICENSE.txt" + +# Generate all standard/Retina sizes from the approved transparent icon master. +swift scripts/render_app_icon.swift Resources/AppIcon.png "$STAGING_DIR/AppIcon.iconset" +iconutil --convert icns --output "$CONTENTS/Resources/AppIcon.icns" "$STAGING_DIR/AppIcon.iconset" + +# Native SwiftUI CRT curvature uses a small Metal shader, compiled once at packaging. +if [ -n "${PREBUILT_METALLIB:-}" ]; then + cp "$PREBUILT_METALLIB" "$CONTENTS/Resources/default.metallib" +else +xcrun -sdk macosx metal -std=metal3.1 -mmacosx-version-min=14.0 -c Resources/CRT.metal -o "$STAGING_DIR/CRT.air" +xcrun -sdk macosx metallib "$STAGING_DIR/CRT.air" -o "$CONTENTS/Resources/default.metallib" +fi +# A source run from this build directory can use the same precompiled GPU library. +if [ -z "${PREBUILT_BINARY:-}" ]; then + cp "$CONTENTS/Resources/default.metallib" "$BIN_DIR/default.metallib" +fi + +/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" "$CONTENTS/Info.plist" +/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD_NUMBER" "$CONTENTS/Info.plist" +xattr -cr "$APP_BUNDLE" + +if [ -n "${CODESIGN_IDENTITY:-}" ]; then + codesign --force --options runtime --timestamp --entitlements Resources/Retrolemetry.entitlements --sign "$CODESIGN_IDENTITY" "$APP_BUNDLE" + echo "Signed with Developer ID identity: $CODESIGN_IDENTITY" +else + codesign --force --entitlements Resources/Retrolemetry.entitlements --sign - "$APP_BUNDLE" + echo "Applied an ad-hoc signature. This build is not notarized." +fi + +# Hardened apps need this declared resource capability before Core Location can +# display its normal user-consent prompt. It does not grant location permission. +codesign --display --entitlements - --xml "$APP_BUNDLE" > "$STAGING_DIR/signed-entitlements.plist" +test "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.personal-information.location' "$STAGING_DIR/signed-entitlements.plist")" = true + +case "$DIST_DIR" in + /*) ARCHIVE="$DIST_DIR/$APP_NAME-$VERSION.zip" ;; + *) ARCHIVE="$PWD/$DIST_DIR/$APP_NAME-$VERSION.zip" ;; +esac +rm -f "$ARCHIVE" +(cd "$STAGING_DIR" && COPYFILE_DISABLE=1 /usr/bin/zip -qry "$ARCHIVE" "$APP_NAME.app") +rm -rf "$OUTPUT_APP" +ditto --norsrc "$APP_BUNDLE" "$OUTPUT_APP" +xattr -cr "$OUTPUT_APP" + +echo "Created $OUTPUT_APP" +echo "Created $ARCHIVE" diff --git a/scripts/prepare_appcast.py b/scripts/prepare_appcast.py new file mode 100755 index 0000000..13a22cd --- /dev/null +++ b/scripts/prepare_appcast.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Prepare and verify a signed appcast privately; never publishes anything. + +Accept only a final, notarized/stapled Retrolemetry ZIP. The private key is +accessed through Retrolemetry's dedicated Keychain account, not an environment +variable or repository file. Stage outside the source checkout. +""" +import argparse +import base64 +import hashlib +import json +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import tempfile +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parent.parent +ACCOUNT = "io.github.SamSpring.Retrolemetry.sparkle" +FEED = "https://samspring.github.io/Retrolemetry/appcast.xml" +REPO = "https://github.com/SamSpring/Retrolemetry" +NS = "{http://www.andymatuschak.org/xml-namespaces/sparkle}" +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("archive", type=Path) +parser.add_argument("output", type=Path) +parser.add_argument("--previous", type=Path, help="Reviewed previous private feed staging") +parser.add_argument("--sparkle-tools", type=Path, default=ROOT / ".build/artifacts/sparkle/Sparkle/bin") +args = parser.parse_args() +archive, output = args.archive.resolve(), args.output.resolve() +assert not output.is_relative_to(ROOT), "Stage artifacts outside the repository" +assert archive.is_file() and not output.exists(), "Require a final archive and a NEW staging folder" +tools = args.sparkle_tools.resolve() + + +def run(command): + return subprocess.check_output(list(map(str, command)), text=True).strip() + + +with tempfile.TemporaryDirectory(prefix="retrolemetry-feed-validation-", dir="/private/tmp") as private: + run(["ditto", "-x", "-k", archive, private]) + app = Path(private) / "Retrolemetry.app" + assert sorted(p.name for p in Path(private).iterdir()) == ["Retrolemetry.app"], "ZIP must contain only the app" + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + source = plistlib.loads((ROOT / "Resources/Info.plist").read_bytes()) + assert info["CFBundleIdentifier"] == "io.github.SamSpring.Retrolemetry" + assert info["SUFeedURL"] == FEED and info["SUPublicEDKey"] == source["SUPublicEDKey"] + assert info["SURequireSignedFeed"] is True and info["SUVerifyUpdateBeforeExtraction"] is True + assert run([tools / "generate_keys", "--account", ACCOUNT, "-p"]) == info["SUPublicEDKey"] + version, build = info["CFBundleShortVersionString"], info["CFBundleVersion"] + assert re.fullmatch(r"\d+\.\d+\.\d+", version) and re.fullmatch(r"[1-9]\d*", build) + assert archive.name == f"Retrolemetry-{version}.zip" + assert info["LSMinimumSystemVersion"] == "14.0" + assert set(run(["lipo", "-archs", app / "Contents/MacOS/Retrolemetry"]).split()) == {"arm64", "x86_64"} + run(["codesign", "--verify", "--deep", "--strict", app]) + signature = subprocess.run(["codesign", "-dvv", str(app)], capture_output=True, text=True, check=True).stderr + assert "Authority=Developer ID Application:" in signature and "runtime" in signature + run(["xcrun", "stapler", "validate", app]) + run(["spctl", "--assess", "--type", "execute", app]) + output.mkdir(parents=True) + if args.previous: + previous = args.previous.resolve() + old = previous / "appcast.xml" + assert old.is_file() + run([tools / "sign_update", "--account", ACCOUNT, "--verify", old]) + for item in ET.parse(old).findall("./channel/item"): + assert int(item.findtext(NS + "version")) < int(build), "Build numbers must increase" + shutil.copyfile(old, output / "appcast.xml") + for path in previous.iterdir(): + if re.fullmatch(r"Retrolemetry-\d+\.\d+\.\d+\.(zip|md)", path.name): + assert path.is_file() and not path.is_symlink() + shutil.copyfile(path, output / path.name) + staged = output / archive.name + assert not staged.exists(), "Never replace released archive names" + shutil.copyfile(archive, staged) + shutil.copyfile(ROOT / "RELEASE_NOTES.md", output / f"Retrolemetry-{version}.md") + run([tools / "generate_appcast", "--account", ACCOUNT, "--maximum-deltas", "0", + "--versions", build, "--download-url-prefix", f"{REPO}/releases/download/v{version}/", + "--embed-release-notes", output]) + feed = output / "appcast.xml" + run([tools / "sign_update", "--account", ACCOUNT, "--verify", feed]) + item = next(i for i in ET.parse(feed).findall("./channel/item") if i.findtext(NS + "version") == build) + enclosure = item.find("enclosure") + expected = f"{REPO}/releases/download/v{version}/{archive.name}" + assert enclosure.attrib["url"] == expected + assert int(enclosure.attrib["length"]) == archive.stat().st_size + ed_signature = enclosure.attrib[NS + "edSignature"] + assert len(base64.b64decode(ed_signature, validate=True)) == 64 + assert item.findtext(NS + "minimumSystemVersion") in ["14.0", "14.0.0"] + assert item.findtext(NS + "hardwareRequirements") in [None, "arm64,x86_64", "x86_64,arm64"] + assert item.find("description") is not None + run([tools / "sign_update", "--account", ACCOUNT, "--verify", staged, ed_signature]) + checksum = hashlib.sha256(staged.read_bytes()).hexdigest() + (output / "SHA256SUMS.txt").write_text(f"{checksum} {archive.name}\n") + (output / "validation.json").write_text(json.dumps({ + "version": version, "build": build, "sha256": checksum, + "feedUrl": FEED, "downloadUrl": expected, "signedFeedVerified": True, + "signedArchiveVerified": True, "notarized": True, "published": False + }, indent=2) + "\n") + print("Signed feed and exact notarized ZIP verified in private staging. Nothing published.") diff --git a/scripts/prepare_globe_data.mjs b/scripts/prepare_globe_data.mjs new file mode 100644 index 0000000..1ce0082 --- /dev/null +++ b/scripts/prepare_globe_data.mjs @@ -0,0 +1,33 @@ +// Convert Natural Earth's public-domain 110m land polygons into bounded coastlines. +// Input: ne_110m_land.geojson from nvkelso/natural-earth-vector. Output: Swift source. +import { readFileSync } from 'node:fs'; +const data = JSON.parse(readFileSync(process.argv[2], 'utf8')); +function simplify(points, tolerance = 0.75) { + if (points.length <= 2) return points; + const a = points[0], b = points.at(-1); + const dx = b[0]-a[0], dy = b[1]-a[1], d = dx*dx+dy*dy; + let farthest = 0, index = 0; + for (let i=1; ifarthest) { farthest=distance; index=i; } + } + return farthest > tolerance ? [...simplify(points.slice(0,index+1),tolerance).slice(0,-1),...simplify(points.slice(index),tolerance)] : [a,b]; +} +const edges=[]; +for(const feature of data.features) { + const polygons=feature.geometry.type==='MultiPolygon' ? feature.geometry.coordinates : [feature.geometry.coordinates]; + for(const polygon of polygons) { + const ring=polygon[0]; + const area=Math.abs(ring.slice(1).reduce((s,p,i)=>s+ring[i][0]*p[1]-p[0]*ring[i][1],0))/2; + if(area<6) continue; + // Split closed rings into two open arcs so RDP keeps each continent's extent. + const half=Math.floor(ring.length/2); + const points=[...simplify(ring.slice(0,half+1)).slice(0,-1),...simplify(ring.slice(half))]; + for(let i=1;i180) continue; + edges.push([...points[i-1],...points[i]].map(x=>Number(x.toFixed(3)))); + } + } +} +console.log('// Made with Natural Earth. Public-domain 110m land data, simplified to 0.75 degrees.\n// https://www.naturalearthdata.com/about/terms-of-use/\n// Regenerate using scripts/prepare_globe_data.mjs with ne_110m_land.geojson.\nenum GlobeCoastlines {\n static let degrees: [SIMD4] = [\n'+edges.map(e=>' SIMD4('+e.join(', ')+'),').join('\n')+'\n ]\n}'); diff --git a/scripts/prepare_regional_maps.mjs b/scripts/prepare_regional_maps.mjs new file mode 100644 index 0000000..b1ec975 --- /dev/null +++ b/scripts/prepare_regional_maps.mjs @@ -0,0 +1,43 @@ +// Generate bounded geographic artwork from Natural Earth's public-domain 50m countries. +// Usage: node scripts/prepare_regional_maps.mjs ne_50m_admin_0_countries.geojson +// Emits Swift data to stdout; no network or private inputs are used. +import {readFileSync} from 'node:fs'; +const data = JSON.parse(readFileSync(process.argv[2], 'utf8')); +function simplify(points, tolerance = 0.30) { + if (points.length <= 2) return points; + const a=points[0],b=points.at(-1),dx=b[0]-a[0],dy=b[1]-a[1],d=dx*dx+dy*dy; + let farthest=0,index=0; + for(let i=1;ifarthest) { farthest=distance;index=i; } + } + return farthest>tolerance ? [...simplify(points.slice(0,index+1),tolerance).slice(0,-1),...simplify(points.slice(index),tolerance)] : [a,b]; +} +function edges(region) { + const result=[]; + const inside=region==='northAmerica' ? p=>p[0]>=-170&&p[0]<=-49&&p[1]>=8&&p[1]<=85 : p=>p[0]>=-25&&p[0]<=45&&p[1]>=34&&p[1]<=72; + for(const f of data.features) { + if(region==='northAmerica' ? f.properties.CONTINENT!=='North America' : f.properties.CONTINENT!=='Europe' && !['Turkey','Cyprus'].includes(f.properties.ADMIN)) continue; + const polygons=f.geometry.type==='MultiPolygon'?f.geometry.coordinates:[f.geometry.coordinates]; + for(const polygon of polygons) { + const ring=polygon[0],half=Math.floor(ring.length/2); + const area=Math.abs(ring.slice(1).reduce((sum,p,i)=>sum+ring[i][0]*p[1]-p[0]*ring[i][1],0))/2; + if(area<0.25) continue; + const points=[...simplify(ring.slice(0,half+1)).slice(0,-1),...simplify(ring.slice(half))]; + for(let i=1;iNumber(x.toFixed(4)))); + } + } + } + return result; +} +if (process.argv[3]) { + const values=edges(process.argv[3]); + if(process.argv[4]==='count') { console.log(values.length); process.exit(0); } + const start=Number(process.argv[4]??0),end=start+Number(process.argv[5]??values.length); + console.log(values.slice(start,end).map(e=>' SIMD4('+e.join(', ')+'),').join('\n')); + process.exit(0); +} +console.log('// Public-domain Natural Earth 50m admin-0 country artwork, simplified to 0.30 degrees.\n// Default de facto boundaries; clipped regional coverage; not a navigation/boundary authority.\n// https://www.naturalearthdata.com/about/terms-of-use/\n// Regenerate with scripts/prepare_regional_maps.mjs and ne_50m_admin_0_countries.geojson.\nenum RegionalMapData {\n'+['northAmerica','europe'].map(region=>' static let '+region+': [SIMD4] = [\n'+edges(region).map(e=>' SIMD4('+e.join(', ')+'),').join('\n')+'\n ]').join('\n')+'\n}'); diff --git a/scripts/qa_key.swift b/scripts/qa_key.swift new file mode 100644 index 0000000..61fa8cb --- /dev/null +++ b/scripts/qa_key.swift @@ -0,0 +1,9 @@ +import Foundation +import CryptoKit + +// Isolated QA only: never imports/exports a production Keychain key. +let key = Curve25519.Signing.PrivateKey() +let path = URL(fileURLWithPath: CommandLine.arguments[1]) +FileManager.default.createFile(atPath: path.path, contents: nil, attributes: [.posixPermissions: 0o600]) +try Data(key.rawRepresentation.base64EncodedString().utf8).write(to: path) +print(key.publicKey.rawRepresentation.base64EncodedString()) diff --git a/scripts/qa_updater.swift b/scripts/qa_updater.swift new file mode 100644 index 0000000..59d45d5 --- /dev/null +++ b/scripts/qa_updater.swift @@ -0,0 +1,124 @@ +// Compile with AppUpdater.swift, never with the production entry point. This +// harness has its own bundle ID, synthetic defaults and no telemetry/Keychain/login access. +import AppKit +import Combine +import CryptoKit +import Sparkle + +@main +@MainActor +enum UpdaterQA { + static func main() { + let app = NSApplication.shared + let delegate = Harness() + app.delegate = delegate + app.setActivationPolicy(.regular) + app.run() + } +} + +@MainActor +private final class Harness: NSObject, NSApplicationDelegate { + private var updates: AppUpdater! + private var observation: AnyCancellable? + private var timer: Timer? + private var menu: NSMenu! + private var clicked = Set() + private let root = URL(fileURLWithPath: Bundle.main.object(forInfoDictionaryKey: "QARoot") as! String) + private var scenario: String { (try? String(contentsOf: root.appendingPathComponent("scenario"), encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "invalid" } + private var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String } + + private func record(_ event: String, extra: [String: Any] = [:]) { + var value = extra + value["event"] = event + value["build"] = build + value["scenario"] = scenario + value["pid"] = ProcessInfo.processInfo.processIdentifier + value["settingsPreserved"] = UserDefaults.standard.string(forKey: "DockTelemetry.QASentinel") == "synthetic-layout-sentinel" + if let layout = UserDefaults.standard.dictionary(forKey: "DockTelemetry.QALayout"), + let data = try? JSONSerialization.data(withJSONObject: layout, options: [.sortedKeys]) { + value["layoutDigest"] = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + let bytes = try! JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) + Data([10]) + let path = root.appendingPathComponent("events.jsonl") + if !FileManager.default.fileExists(atPath: path.path) { FileManager.default.createFile(atPath: path.path, contents: nil) } + let handle = try! FileHandle(forWritingTo: path) + try! handle.seekToEnd(); try! handle.write(contentsOf: bytes); try! handle.close() + } + + func applicationDidFinishLaunching(_ notification: Notification) { + guard let identity = Bundle.main.bundleIdentifier, identity.hasPrefix("io.github.SamSpring.Retrolemetry.UpdaterQA.") else { fatalError("Not an isolated QA bundle") } + let defaults = UserDefaults.standard + if defaults.string(forKey: "DockTelemetry.QASentinel") == nil { + defaults.set("synthetic-layout-sentinel", forKey: "DockTelemetry.QASentinel") + defaults.set(["module": ["x": 42, "y": 18, "width": 300]], forKey: "DockTelemetry.QALayout") + } + defaults.set(false, forKey: "SUEnableAutomaticChecks") + let base = Bundle.main.object(forInfoDictionaryKey: "QAFeedBase") as! String + defaults.set(base + "/" + scenario + ".xml", forKey: "SUFeedURL") + record("launched", extra: ["layoutPreserved": defaults.dictionary(forKey: "DockTelemetry.QALayout")? ["module"] != nil]) + if build == "2" && scenario == "valid" { + record("relaunched-new-build") + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { NSApp.terminate(nil) } + return + } + updates = AppUpdater(bundleIdentifier: identity) + updates.start() + menu = NSMenu(title: "Retrolemetry Updater QA") + menu.addItem(withTitle: "Check for Updates…", action: #selector(SPUStandardUpdaterController.checkForUpdates(_:)), keyEquivalent: "").target = updates.controller + observation = updates.$lastError.compactMap { $0 }.sink { [weak self] error in + self?.record("updater-result", extra: ["errorDomain": error.domain, "errorCode": error.code, "description": error.localizedDescription]) + } + DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in + record("manual-check") + menu.performActionForItem(at: 0) + } + timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.advanceNativeUI() } + } + RunLoop.main.add(timer!, forMode: .modalPanel) + RunLoop.main.add(timer!, forMode: .common) + DispatchQueue.main.asyncAfter(deadline: .now() + 55) { [self] in + record("timeout") + NSApp.terminate(nil) + } + } + + private func advanceNativeUI() { + if ["tampered", "wrong-key", "wrong-feed"].contains(scenario), let error = updates.lastError { + record("rejected", extra: ["errorCode": error.code, "errorDomain": error.domain]) + NSApp.terminate(nil) + return + } + func walk(_ view: NSView) -> [NSView] { [view] + view.subviews.flatMap(walk) } + for window in NSApp.windows where window.isVisible { + let views = window.contentView.map(walk) ?? [] + let labels = views.compactMap { ($0 as? NSTextField)?.stringValue }.joined(separator: " ") + let marker = "window:" + labels + if !clicked.contains(marker) { + clicked.insert(marker) + record("native-window", extra: ["text": labels, "buttons": views.compactMap { ($0 as? NSButton)?.title }]) + } + if scenario == "no-update" && labels.localizedCaseInsensitiveContains("up to date") { + record("no-update-visible") + NSApp.terminate(nil) + return + } + for button in views.compactMap({ $0 as? NSButton }) where button.isEnabled { + let title = button.title + if ["Install Update", "Install and Relaunch"].contains(title) && !clicked.contains(title) { + clicked.insert(title) + record("native-button", extra: ["title": title]) + button.performClick(nil) + return + } + } + if ["tampered", "wrong-key", "wrong-feed"].contains(scenario), labels.contains("Update Error!") { + if let dismiss = views.compactMap({ $0 as? NSButton }).first(where: { ["Cancel Update", "OK"].contains($0.title) }) { + dismiss.performClick(nil) + return + } + } + } + } +} diff --git a/scripts/render_app_icon.swift b/scripts/render_app_icon.swift new file mode 100644 index 0000000..7823100 --- /dev/null +++ b/scripts/render_app_icon.swift @@ -0,0 +1,58 @@ +import CoreGraphics +import Foundation +import ImageIO +import UniformTypeIdentifiers + +// Native format conversion only: preserve artwork, proportions, margins and alpha. +// No design redraw, cropping, masking, or new effects are applied here. +func fail(_ message: String) -> Never { + FileHandle.standardError.write(Data(("Icon packaging: " + message + "\n").utf8)) + exit(1) +} + +guard CommandLine.arguments.count == 3 else { fail("Expected a PNG master and an .iconset output folder.") } +let input = URL(fileURLWithPath: CommandLine.arguments[1]) +let output = URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true) +guard output.pathExtension == "iconset" else { fail("Output must be an .iconset folder.") } +guard let source = CGImageSourceCreateWithURL(input as CFURL, nil), + let master = CGImageSourceCreateImageAtIndex(source, 0, nil) else { fail("Cannot decode the icon master.") } +guard master.width == master.height, master.width >= 1024 else { fail("Master must be square and at least 1024 pixels.") } +guard [.first, .last, .premultipliedFirst, .premultipliedLast].contains(master.alphaInfo) else { + fail("Master must include transparent outer edges.") +} +let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)! +let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue +try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + +let sizes: [(String, Int)] = [ + ("icon_16x16.png", 16), ("icon_16x16@2x.png", 32), + ("icon_32x32.png", 32), ("icon_32x32@2x.png", 64), + ("icon_128x128.png", 128), ("icon_128x128@2x.png", 256), + ("icon_256x256.png", 256), ("icon_256x256@2x.png", 512), + ("icon_512x512.png", 512), ("icon_512x512@2x.png", 1024) +] +for (name, pixels) in sizes { + guard let context = CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, + bytesPerRow: pixels * 4, space: colorSpace, bitmapInfo: bitmapInfo) else { + fail("Cannot allocate the icon-size buffer.") + } + context.interpolationQuality = .high + context.draw(master, in: CGRect(x: 0, y: 0, width: pixels, height: pixels)) + guard let image = context.makeImage(), let data = context.data else { fail("Cannot render an icon size.") } + let bytes = data.assumingMemoryBound(to: UInt8.self) + for (x, y) in [(0, 0), (pixels - 1, 0), (0, pixels - 1), (pixels - 1, pixels - 1)] { + guard bytes[(y * pixels + x) * 4 + 3] == 0 else { fail("Outer corner is not transparent.") } + } + // High-quality downsampling may round alpha a few levels below 255. + guard bytes[((pixels / 2) * pixels + pixels / 2) * 4 + 3] >= 250 else { + fail("Icon interior is unexpectedly transparent at \(pixels) px.") + } + let url = output.appendingPathComponent(name) + guard let destination = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil) else { + fail("Cannot create a PNG icon size.") + } + // No source metadata, generation prompt or personal source path is exported. + CGImageDestinationAddImage(destination, image, nil) + guard CGImageDestinationFinalize(destination) else { fail("Cannot save an icon size.") } +} +print("Verified 10 standard/Retina icon sizes (16–1024 px), transparent corners and near-opaque interiors.") diff --git a/scripts/test_updater.py b/scripts/test_updater.py new file mode 100644 index 0000000..4940bea --- /dev/null +++ b/scripts/test_updater.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Exercise the real standard Sparkle UI in a separately identified test app. + +Uses temporary keys, synthetic defaults and a loopback-only allowlisted server. +Does not install Retrolemetry, read its Keychain, or register login items. +Not a substitute for final notarized-production-app acceptance in a clean VM. +""" +import argparse +import hashlib +import http.server +import json +import os +from pathlib import Path +import plistlib +import shutil +import subprocess +import tempfile +import threading +import time +import uuid +import xml.etree.ElementTree as ET + +ROOT = Path(__file__).resolve().parent.parent +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--output", required=True, type=Path) +parser.add_argument("--sparkle-tools", type=Path, default=ROOT / ".build/artifacts/sparkle/Sparkle/bin") +args = parser.parse_args() +out = args.output.resolve() +assert not out.is_relative_to(ROOT), "QA artifacts and keys must stay outside the repository" +out.mkdir(parents=True, exist_ok=False) +tools = args.sparkle_tools.resolve() +framework = tools.parent / "Sparkle.xcframework/macos-arm64_x86_64/Sparkle.framework" +identity = "io.github.SamSpring.Retrolemetry.UpdaterQA." + uuid.uuid4().hex +ns = "{http://www.andymatuschak.org/xml-namespaces/sparkle}" + + +def run(command, **kwargs): + result = subprocess.run(list(map(str, command)), capture_output=True, text=True, **kwargs) + if result.returncode: + raise RuntimeError(result.stderr[-5000:] or result.stdout[-5000:]) + return result.stdout.strip() + + +allowed = {} + + +class Server(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = self.path.split("?", 1)[0] + file = allowed.get(path) + if not file: + self.send_error(404) + return + payload = file.read_bytes() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def log_message(self, *_): + pass + + +server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Server) +base = "http://127.0.0.1:" + str(server.server_port) +threading.Thread(target=server.serve_forever, daemon=True).start() + +with tempfile.TemporaryDirectory(prefix="retrolemetry-updater-keys-", dir="/private/tmp") as private: + seed = Path(private) / "test-seed" + wrong = Path(private) / "wrong-seed" + public = run(["swift", ROOT / "scripts/qa_key.swift", seed]) + run(["swift", ROOT / "scripts/qa_key.swift", wrong]) + binary = out / "qa-binary" + run(["swiftc", "-parse-as-library", ROOT / "scripts/qa_updater.swift", + ROOT / "Sources/Retrolemetry/AppUpdater.swift", "-o", binary, + "-F", framework.parent, "-framework", "Sparkle", "-Xlinker", "-rpath", + "-Xlinker", "@executable_path/../Frameworks"]) + for build in ["1", "2"]: + app = out / ("build" + build) / "Retrolemetry Updater QA.app" + contents = app / "Contents" + (contents / "MacOS").mkdir(parents=True) + shutil.copyfile(binary, contents / "MacOS/Retrolemetry") + (contents / "MacOS/Retrolemetry").chmod(0o755) + info = plistlib.loads((ROOT / "Resources/Info.plist").read_bytes()) + info.update(CFBundleIdentifier=identity, CFBundleName="Retrolemetry Updater QA", + CFBundleDisplayName="Retrolemetry Updater QA", CFBundleVersion=build, + CFBundleShortVersionString="0.0." + build, LSUIElement=False, + SUPublicEDKey=public, QARoot=str(out), QAFeedBase=base, + SUEnableAutomaticChecks=False, + NSAppTransportSecurity={"NSAllowsLocalNetworking": True}) + info.pop("CFBundleIconFile", None) + (contents / "Info.plist").write_bytes(plistlib.dumps(info)) + env = dict(os.environ) + env.pop("CODESIGN_IDENTITY", None) + run(["sh", ROOT / "scripts/embed_sparkle.sh", app, framework], env=env) + run(["codesign", "--force", "--sign", "-", app]) + run(["codesign", "--verify", "--deep", "--strict", app]) + newer = out / "build2/Retrolemetry Updater QA.app" + archives = out / "archives" + archives.mkdir() + archive = archives / "Retrolemetry-QA.zip" + run(["ditto", "-c", "-k", "--keepParent", newer, archive]) + (archives / "Retrolemetry-QA.md").write_text("# Private updater test\n\nSynthetic data only. Never publish.\n") + run([tools / "generate_appcast", "--ed-key-file", seed, "--maximum-deltas", "0", + "--embed-release-notes", "--download-url-prefix", base + "/", archives]) + feed = archives / "appcast.xml" + enclosure = ET.parse(feed).find("./channel/item/enclosure") + signature = enclosure.attrib[ns + "edSignature"] + run([tools / "sign_update", "--ed-key-file", seed, "--verify", archive, signature]) + run([tools / "sign_update", "--ed-key-file", seed, "--verify", feed]) + allowed["/Retrolemetry-QA.zip"] = archive + allowed["/valid.xml"] = feed + for case in ["tampered", "wrong-key", "wrong-feed", "no-update"]: + target = out / (case + ".xml") + tree = ET.parse(feed) + enc = tree.find("./channel/item/enclosure") + if case == "tampered": + bad = out / "tampered.zip" + data = bytearray(archive.read_bytes()); data[len(data) // 2] ^= 1 + bad.write_bytes(data) + allowed["/tampered.zip"] = bad + enc.set("url", base + "/tampered.zip") + elif case == "wrong-key": + bad_signature = run([tools / "sign_update", "--ed-key-file", wrong, "-p", archive]) + enc.set(ns + "edSignature", bad_signature) + elif case == "no-update": + tree.find("./channel/item/" + ns + "version").text = "1" + tree.write(target, encoding="utf-8", xml_declaration=True) + run([tools / "sign_update", "--ed-key-file", wrong if case == "wrong-feed" else seed, target]) + allowed["/" + case + ".xml"] = target + + events_path = out / "events.jsonl" + results = {} + for case in ["no-update", "tampered", "wrong-key", "wrong-feed", "valid"]: + (out / "scenario").write_text(case) + app = out / ("installed-" + case) / "Retrolemetry Updater QA.app" + run(["ditto", "--noextattr", "--norsrc", out / "build1/Retrolemetry Updater QA.app", app]) + before = hashlib.sha256((app / "Contents/MacOS/Retrolemetry").read_bytes()).hexdigest() + run(["open", "-n", app]) + deadline = time.monotonic() + 65 + complete = [] + while time.monotonic() < deadline: + events = [json.loads(line) for line in events_path.read_text().splitlines()] if events_path.exists() else [] + complete = [e for e in events if e["scenario"] == case and e["event"] in + ["no-update-visible", "rejected", "relaunched-new-build", "timeout"]] + if complete: + break + time.sleep(0.2) + time.sleep(1.5) + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + results[case] = {"events": complete, "installedBuild": info["CFBundleVersion"], + "executableUnchanged": before == hashlib.sha256((app / "Contents/MacOS/Retrolemetry").read_bytes()).hexdigest()} + (out / "result.json").write_text(json.dumps(results, indent=2) + "\n") + if not complete or complete[-1]["event"] == "timeout": + raise RuntimeError("QA incomplete for " + case + "; retain output for diagnosis") + assert all(e["settingsPreserved"] for e in complete) + case_events = [e for e in events if e["scenario"] == case] + assert len({e["layoutDigest"] for e in case_events}) == 1, "Layout bytes changed" + if case in ["tampered", "wrong-key", "wrong-feed"]: + assert any("improperly signed" in e.get("text", "") for e in case_events), "Must observe a signature rejection, not a generic failure" + assert info["CFBundleVersion"] == ("2" if case == "valid" else "1") + run(["codesign", "--verify", "--deep", "--strict", app]) + if case != "valid": + assert results[case]["executableUnchanged"] + print(case + ": passed", flush=True) + run(["defaults", "delete", identity]) + server.shutdown() + print("All private native updater cases passed. Temporary keys deleted; production app untouched.") diff --git a/scripts/validate_site.py b/scripts/validate_site.py new file mode 100644 index 0000000..dbbbe56 --- /dev/null +++ b/scripts/validate_site.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Validate the static site and, with --release, its public download metadata.""" +import argparse +from html.parser import HTMLParser +import json +from pathlib import Path +import re +import xml.etree.ElementTree as ET +from urllib.parse import urlsplit + +root = Path(__file__).resolve().parent.parent +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--release", action="store_true") +args = parser.parse_args() + +config = json.loads((root / "site/release.json").read_text()) +assert config["supportUrl"] == "https://ko-fi.com/samspring" +assert config["architecture"] == "universal" +assert config["minimumMacOS"] == "14.0" +repo = config["repositoryUrl"] +assert re.fullmatch(r"https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo) +if args.release: + assert config["notarized"] is True + assert config["publicDownloadVerified"] is True + assert re.fullmatch(r"\d+\.\d+\.\d+", config["version"]) + assert re.fullmatch(r"[a-f0-9]{64}", config["sha256"]) + expected = f"{repo}/releases/download/v{config['version']}/Retrolemetry-{config['version']}.zip" + assert config["downloadUrl"] == expected + ns = "{http://www.andymatuschak.org/xml-namespaces/sparkle}" + matching = [i for i in ET.parse(root / "site/appcast.xml").findall("./channel/item") + if i.findtext(ns + "shortVersionString") == config["version"]] + assert len(matching) == 1, "Require the reviewed release entry before deploying" + enclosure = matching[0].find("enclosure") + assert enclosure is not None and enclosure.attrib["url"] == expected + assert enclosure.attrib.get(ns + "edSignature"), "Missing update archive signature" + assert matching[0].findtext(ns + "minimumSystemVersion") in ["14.0", "14.0.0"] + + +class LocalFiles(HTMLParser): + def handle_starttag(self, tag, attrs): + for key, value in attrs: + if key in ("href", "src") and value and not value.startswith("#"): + url = urlsplit(value) + if url.scheme: + assert url.scheme == "https" + elif value != "./": + assert (root / "site" / url.path).is_file(), f"Missing site asset: {value}" + + +LocalFiles().feed((root / "site/index.html").read_text()) +print("Site validation passed" + (" for release." if args.release else ".")) diff --git a/scripts/verify_appcast.swift b/scripts/verify_appcast.swift new file mode 100644 index 0000000..55c521d --- /dev/null +++ b/scripts/verify_appcast.swift @@ -0,0 +1,22 @@ +import Foundation +import CryptoKit + +// Match Sparkle 2.10's signed-feed framing, and use only the committed PUBLIC key. +// Signing and native acceptance are also checked with official Sparkle tools. +let info = try PropertyListSerialization.propertyList(from: Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1])), format: nil) as! [String: Any] +let data = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[2])) +let key = try Curve25519.Signing.PublicKey(rawRepresentation: Data(base64Encoded: info["SUPublicEDKey"] as! String)!) +let xml = String(decoding: data, as: UTF8.self) +let pattern = #"\s*$"# +let regex = try NSRegularExpression(pattern: pattern) +guard let match = regex.firstMatch(in: xml, range: NSRange(xml.startIndex..., in: xml)), + let signatureRange = Range(match.range(at: 1), in: xml), + let markerRange = Range(match.range, in: xml), + let signature = Data(base64Encoded: String(xml[signatureRange])) else { + fatalError("Missing signed-feed framing") +} +let unsigned = Data(xml[.. + + Retrolemetry Updates + https://samspring.github.io/Retrolemetry/ + Verified Retrolemetry updates. No public release is available yet. + en + + diff --git a/site/assets/app-icon.png b/site/assets/app-icon.png new file mode 100644 index 0000000..a4191e3 Binary files /dev/null and b/site/assets/app-icon.png differ diff --git a/site/assets/live-system-metrics.png b/site/assets/live-system-metrics.png new file mode 100644 index 0000000..dbb6e02 Binary files /dev/null and b/site/assets/live-system-metrics.png differ diff --git a/site/assets/signal-analysis.png b/site/assets/signal-analysis.png new file mode 100644 index 0000000..024685a Binary files /dev/null and b/site/assets/signal-analysis.png differ diff --git a/site/assets/weather-radar.png b/site/assets/weather-radar.png new file mode 100644 index 0000000..d3f0051 Binary files /dev/null and b/site/assets/weather-radar.png differ diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..3893d30 --- /dev/null +++ b/site/index.html @@ -0,0 +1,46 @@ + + + + + + + + + Retrolemetry — A retro console for your Mac + + + + + + +
+
+ Retrolemetry + +
+
+
+
+

Your tiny screen,
alive.

+

A native retro telemetry and vector console for a dedicated Mac display.

+ +

macOS 14+ · Apple silicon & Intel · Free & open source

+

The first public download is in preparation. Source builds are available on GitHub.

+
+
Retrolemetry showing CPU, memory, disk, uptime, load and network readings in cyan and magenta.
Live System Metrics
+
+ +
+

Real readings

CPU, memory, disk, network, GPU counters, uptime and optional battery flow—shown locally without analytics.

+

Built for a second screen

Retrolemetry remembers its display, returns after reconnection and stays hidden when that chosen screen is away.

+

Make it yours

Move and resize modules, tune typography and CRT effects, reorder scenes, or switch between phosphor and synthwave.

+
+

Weather uses Open-Meteo with approximate or fixed public coordinates. Optional market quotes use your own Finnhub key stored in macOS Keychain. No accounts, ads, analytics or bundled credentials.

+
+ +
+ + diff --git a/site/release.json b/site/release.json new file mode 100644 index 0000000..39e45e3 --- /dev/null +++ b/site/release.json @@ -0,0 +1,11 @@ +{ + "repositoryUrl": "https://github.com/SamSpring/Retrolemetry", + "downloadUrl": "https://github.com/SamSpring/Retrolemetry/releases/download/v1.0.0/Retrolemetry-1.0.0.zip", + "version": "1.0.0", + "architecture": "universal", + "minimumMacOS": "14.0", + "sha256": "", + "notarized": false, + "publicDownloadVerified": false, + "supportUrl": "https://ko-fi.com/samspring" +} diff --git a/site/site.js b/site/site.js new file mode 100644 index 0000000..a7e9e91 --- /dev/null +++ b/site/site.js @@ -0,0 +1,21 @@ +"use strict"; +const statusLine = document.querySelector("#release-status"); +const download = document.querySelector("#download"); +fetch("release.json").then(response => { + if (!response.ok) throw new Error("Release configuration unavailable"); + return response.json(); +}).then(release => { + const repoOK = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(release.repositoryUrl || ""); + const expected = `${release.repositoryUrl}/releases/download/v${release.version}/Retrolemetry-${release.version}.zip`; + if (repoOK && /^\d+\.\d+\.\d+$/.test(release.version || "") && release.downloadUrl === expected && release.notarized === true && release.publicDownloadVerified === true && release.architecture === "universal" && release.minimumMacOS === "14.0" && /^[a-f0-9]{64}$/.test(release.sha256 || "")) { + download.href = release.downloadUrl; + download.textContent = "Download for Mac"; + statusLine.textContent = `Retrolemetry ${release.version} · Developer ID signed and notarized. `; + const checksum = document.createElement("a"); + checksum.href = `${release.repositoryUrl}/releases/download/v${release.version}/SHA256SUMS.txt`; + checksum.textContent = "Verify download"; + statusLine.append(checksum); + } +}).catch(() => { + // Keep the source link and preparation notice if metadata cannot be verified. +}); diff --git a/site/styles.css b/site/styles.css new file mode 100644 index 0000000..4daba6f --- /dev/null +++ b/site/styles.css @@ -0,0 +1,8 @@ +:root{color-scheme:only dark;--ink:#eefdf2;--body:#c7ddd0;--muted:#91ad9a;--green:#67ff79;--cyan:#50eaff;--pink:#ff3ca8;--rule:#74ff8c29;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:var(--ink);background:#020707;font-synthesis:none} +*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:#020707;background-image:radial-gradient(circle at 12% 10%,#0b4b274f,transparent 31rem),radial-gradient(circle at 88% 12%,#54104d4d,transparent 34rem),linear-gradient(#020707,#03090b 65%,#020506)}a{color:inherit;text-decoration:none}a:hover{text-decoration:underline;text-underline-offset:5px}a:focus-visible{outline:3px solid var(--cyan);outline-offset:6px}.page{max-width:1440px;margin:auto;padding:0 42px}.skip-link{position:fixed;top:-100px;left:20px;z-index:5;padding:12px;background:#07150b}.skip-link:focus{top:12px} +header{display:flex;align-items:center;justify-content:space-between;gap:28px;padding:34px 6px 28px;border-bottom:1px solid var(--rule)}.brand{display:flex;align-items:center;gap:15px;font-size:30px;font-weight:720;letter-spacing:-1px}.brand img{width:50px;height:50px}.brand:hover{text-decoration:none}nav{font-size:18px;color:var(--body)} +.hero{display:grid;grid-template-columns:minmax(340px,.85fr) minmax(500px,1.25fr);align-items:center;gap:64px;padding:92px 6px 78px}.hero-copy{min-width:0}h1{font-size:clamp(58px,6.7vw,92px);line-height:1.02;letter-spacing:-4.6px;font-weight:760;margin:0;background:linear-gradient(105deg,var(--green),#e7fff0 45%,var(--cyan) 72%,var(--pink));-webkit-background-clip:text;background-clip:text;color:transparent}.intro{font-size:27px;line-height:1.4;color:var(--body);margin:30px 0 38px;letter-spacing:-.7px;max-width:610px}.button{display:inline-flex;align-items:center;justify-content:center;min-height:68px;padding:18px 34px;border-radius:10px;background:linear-gradient(110deg,#77ff83,#64f7d3);color:#031007;font-size:22px;font-weight:720;box-shadow:0 0 34px #4dff7d26}.button:hover{background:#9bffa4;text-decoration:none}.requirements,.release-status{color:var(--muted);font-size:16px;line-height:1.55}.requirements{margin:23px 0 18px}.release-status{margin:0;max-width:560px}.release-status a{text-decoration:underline;text-underline-offset:4px}.hero-screen{margin:0;min-width:0}.hero-screen img,.gallery img{display:block;width:100%;height:auto;border:1px solid #75ff8e3d;border-radius:12px;box-shadow:0 20px 70px #000b,0 0 45px #4dff7d18}.hero-screen figcaption,.gallery figcaption{color:var(--muted);font-size:14px;margin-top:14px;text-align:center} +.gallery{display:grid;grid-template-columns:1fr 1fr;gap:32px;padding:0 6px 80px}.gallery figure{margin:0}.features{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:54px;padding:68px 6px;border-top:1px solid var(--rule);border-bottom:1px solid var(--rule)}h2{font-size:28px;line-height:1.2;letter-spacing:-.8px;margin:0 0 18px}.features p{font-size:18px;line-height:1.62;color:var(--muted);margin:0}.privacy-note{text-align:center;color:var(--muted);font-size:16px;line-height:1.65;max-width:980px;margin:34px auto 54px}footer{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:0 6px 38px;font-size:16px;color:var(--muted)}footer a{color:var(--body)} +@media(max-width:1000px){.page{padding:0 28px}.hero{grid-template-columns:1fr;gap:52px;padding:72px 0}.hero-copy{text-align:center}.intro,.release-status{margin-left:auto;margin-right:auto}.gallery,.features{gap:26px;padding-left:0;padding-right:0}h1{font-size:clamp(56px,10vw,84px)}} +@media(max-width:650px){.page{padding:0 20px}header{padding:22px 0}.brand{font-size:22px;gap:9px}.brand img{width:40px;height:40px}nav{font-size:13px}.hero{padding:60px 0 48px;gap:40px}h1{font-size:clamp(43px,13vw,62px);letter-spacing:-2.6px}.intro{font-size:20px;margin:24px 0 28px}.button{width:100%;font-size:19px}.requirements,.release-status{font-size:14px}.gallery{grid-template-columns:1fr;padding-bottom:56px}.features{grid-template-columns:1fr;gap:34px;padding:48px 0}h2{font-size:25px;margin-bottom:10px}.features p{font-size:17px}.privacy-note{font-size:14px;margin:28px 0 38px}footer{align-items:flex-start;flex-direction:column;gap:16px;font-size:14px;padding:0 0 30px}} +@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}}