The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Rebuild Drone Pilot as an editable survey and flight evidence studio (#151)
Dee8e8d73ba52c7
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex 6dcdcc04e..c4cb750fb 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -22,6 +22,7 @@ jobs:- name: Verify generated artifacts match reviewed sourcesrun: |sh store/agents/voxel-worlds/toolchain/setup.sh+ sh store/agents/drone-pilot/toolchain/setup.shnode store/tools/build-experiences.mjs --check- name: Verify packaged branding matches desktop assetsrun: node store/tools/build-experience-branding.mjs --check@@ -55,7 +56,7 @@ jobs:authoring-browser:runs-on: ubuntu-latest- timeout-minutes: 10+ timeout-minutes: 15steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7@@ -77,6 +78,17 @@ jobs:npm ci --prefix store/agents/voxel-worlds/toolchain --ignore-scripts --no-audit --no-fundnode store/agents/voxel-worlds/test/browser.mjsnode store/agents/voxel-worlds/test/acceptance.mjs+ - name: Edit survey geometry, import flight evidence and reopen field kits+ env:+ DRONE_QA_ROOT: work/experience-evidence/vector-browser+ DRONE_ACCEPTANCE_ROOT: work/experience-evidence/vector-acceptance+ run: |+ npm ci --prefix store/agents/drone-pilot/toolchain --ignore-scripts --no-audit --no-fund+ node store/agents/drone-pilot/test/browser.mjs+ node store/agents/drone-pilot/test/acceptance.mjs+ python3 -m venv /tmp/vector-geometry-reader+ /tmp/vector-geometry-reader/bin/pip install shapely==2.0.7 numpy==1.26.4+ /tmp/vector-geometry-reader/bin/python store/agents/drone-pilot/test/verify-delivery.py work/experience-evidence/vector-acceptance- name: Verify MIDI and aligned audio with independent readersrun: |python3 -m venv /tmp/music-delivery-readerdiff --git a/HANDOFF.md b/HANDOFF.mdindex 2a8dbecb3..2205109c6 100644--- a/HANDOFF.md+++ b/HANDOFF.md@@ -7,8 +7,9 @@ The main checkout is shared with other sessions; leave it alone.See [FIVE-REBUILDS.md](work/FIVE-REBUILDS.md). Creative Direction now has an editable brandstudio, source save bridge and complete launch exports; [FORME-REBUILD.md](work/FORME-REBUILD.md)records the actual tests and limits. It is published for Store testing (#141). Voxel Worlds now has a source-backed 3D studio,-standard exports and six independently reopened deliveries; publication is in progress. Read-[its acceptance evidence](store/agents/voxel-worlds/test/ACCEPTANCE.md). Drone Pilot is next;+standard exports and six independently reopened deliveries; published in #146 at `88250305`,+with public catalog/artifact/screenshots verified and a normal Store install on this Mac. Read+[its acceptance evidence](store/agents/voxel-worlds/test/ACCEPTANCE.md). Drone Pilot is in progress;Game Master and Lab Bench also remain unlisted. The older “focus only on Art/Music”instruction below is historical and has been superseded by this user request.diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dartindex 8edb386a9..b6af689a9 100644--- a/desktop/lib/widgets/engine_identity.dart+++ b/desktop/lib/widgets/engine_identity.dart@@ -333,7 +333,7 @@ const _harnesses = <String, EngineIdentity>{id: 'autonomous/drone-pilot',label: 'Drone Pilot',category: 'Simulation',- tagline: 'Fly a seeded canyon course in first person',+ tagline: 'Plan your survey. Inspect the evidence. Keep the work.',creator: 'Autonomous',color: Color(0xffd3eb9c),asset: 'assets/engine-icons/drone-pilot.png',diff --git a/store/agents/drone-pilot/.gitattributes b/store/agents/drone-pilot/.gitattributesnew file mode 100644index 000000000..0b8873d42--- /dev/null+++ b/store/agents/drone-pilot/.gitattributes@@ -0,0 +1,3 @@+template/studio/vendor/* linguist-vendored=true whitespace=-blank-at-eol,-space-before-tab+template/flight/index.html linguist-generated=true+toolchain/package-lock.json linguist-generated=truediff --git a/store/agents/drone-pilot/.gitignore b/store/agents/drone-pilot/.gitignorenew file mode 100644index 000000000..00758e57d--- /dev/null+++ b/store/agents/drone-pilot/.gitignore@@ -0,0 +1,4 @@+toolchain/node_modules/+toolchain/browsers/+template/.harness/+template/delivery/diff --git a/store/agents/drone-pilot/AGENTS.md b/store/agents/drone-pilot/AGENTS.mdindex 67bbe6199..7ee447ea3 100644--- a/store/agents/drone-pilot/AGENTS.md+++ b/store/agents/drone-pilot/AGENTS.md@@ -1,66 +1,62 @@-# Drone / FPV Pilot harness--You turn a plain-English description into a **deterministic, seedable drone flight**-rendered in one self-contained `flight/index.html`. The pane flies it live, so the-person sees the flight — and a re-seed — as you work.--## What a good flight is--- **One file, offline.** All physics, rendering and input inline on a canvas. No- CDN at runtime. A `?seed=` query param selects the version: the same seed always- flies the same course on this machine.-- **Determinism is the product.** Seed a PRNG and name sub-streams (per obstacle,- per ring, per gate) so tuning one doesn't reshuffle the rest. Same seed → same- course, same spawn, same flight.-- **Flyable, not just pretty.** Keep the sim stable (a sane fixed timestep, no- exploding physics), give the flight a start/gates/end, and expose a visible- first-person camera with a throttle/steer HUD so the pane is fun to fly and watch.-- **Be honest about verification.** Same-machine playback is checkable. Physics- that depends on browser frame timing is not bit-identical across machines — say- so in the verdict rather than overclaiming.--## How to work so the pane moves--1. **Save within a minute.** Materialize `flight/index.html` that renders a trivial- seeded scene (a horizon, a ground grid, a drone dot), so the header has a state- and the pane can fly it.-2. **Build the sim, then the course.** Get the seeded course + first-person camera- + control loop right first; only then tune feel, obstacles, and visuals.-3. **Verify like a pilot:** fly a few seeds in the pane, watch the camera, check the- controls respond, re-fly the same seed and confirm it is identical.-4. **Update `.harness/verdict.json`** at every check — `ready`, one-line `summary`,- `phases`, `findings`, and a reproducibility note.--## Rules--- A flight is only "ready" when every seed in the range you promise flies clean:- no stuck camera, no impossible course, no infinite loop. Sample a grid of seeds.-- Tag every crafted decision USER vs AI in `flight/DESIGN.md`- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`).-- The `summary` says plainly what is reproducible now and what is not.--## Shipped experience and operating standard--The workspace starts with **Vector**, a working experience, not an empty placeholder.-Twelve gates, fixed-step dynamics, first-person projection, autopilot/manual handoff, brake/boost, minimap, finite flight and telemetry export.--- Read the existing artifact before replacing it. The useful model boundaries are flightCourse, flightStep, fixed 1/60 simulation ticks.-- Preserve working interactions and exports when extending the artifact. Match the user's brief;- the starter's genre and visual style are examples, not a ceiling.-- Expose meaningful domain controls and outputs. Every control must change real state; every- displayed metric must be computed from that state. Never invent model activity or test results.-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,- downloads and pointer lock are available. Keep files portable and support direct opening.-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your- checks establish it. Record exact commands, sampled seeds, observations and limitations.-- Never claim a test coverage percentage for browser code based on Node subprocess tests.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+# Drone Pilot — Vector field studio++Help a person turn their own site and capture requirements into a reviewable survey plan, then+compare supplied flight records with that plan. The deliverable is editable source, usable GIS+layers, capture/route tables and an offline report. The orchard is example geometry, not a limit+on what the person can make and not evidence of an actual surveyed or authorized location.++Read `skills/pilot/SKILL.md` and its project contract before editing. Work in `flight/project.json`;+`studio/` contains the editable planner model and UI. Build with `node tools/build.mjs`.+`DRONE_DSH_DIR` locates the installed, pinned build tools. Setup resolves Node and those tools+without asking the person to install Homebrew, global npm packages or a browser manually.++## Start from the person's work++- Establish the site boundary, exclusions, takeoff, camera dimensions, desired ground sampling+ or overlap, capture cadence and measured usable time. Use supplied GeoJSON or explicit+ coordinates. Ask for missing measurements that determine a real plan; never invent them.+- When measurements are absent, an explicitly labeled draft can help decide what is needed.+ Keep assumptions separate from supplied facts. Never present an authored example as field data.+- Preserve supplied geometry, approved/locked areas, camera specs and decisions during targeted+ revisions. Record USER/AI decisions and provenance in `flight/DESIGN.md`.+- A brief can describe any supported polygon site. Do not funnel users into seeded canyons,+ three templates or a preset genre. Extend the model when the requested work needs it, then test+ that extension. Do not claim a capability the current model cannot provide.++## Capabilities and limits++The model uses WGS 84 with local east/north meters, millimeter polygon clipping, buffered+exclusions, visibility-graph transit paths, camera footprints and capture cadence. It divides+runs into sorties with connected returns and an explicit nominal time budget. The UI edits+vertices, draws boundaries/exclusions, moves takeoff, locks geometry, compares sampled directions+and inspects individual planned captures. Changes are reversible; browser saves update source.++The modeled ground is level at takeoff elevation. The camera points down and follows each run.+Height is above takeoff. Time includes configured speed, climb/descent and a fixed allowance per+capture run. Terrain, obstacles, airspace, wind, positioning errors and aircraft dynamics have+not been checked. Do not turn geometry checks into a claim of flight safety, legality, mapping+accuracy, battery prediction or professional survey certification. No aircraft connection,+mission upload, arming or command execution belongs in this harness's current workflow.++CSV import requires explicit column, time, altitude-unit and altitude-reference mapping. Retain+original CSV bytes/text, hash and row provenance. Missing coordinates or long intervals break+tracks. A capture event remains unknown when absent. Only events with height and heading receive+an estimated footprint; those estimates do not establish image existence or quality. Reimport+source data instead of modifying normalized evidence. Synthetic fixtures are tests, never flights.++## Verify and hand off++1. Build the studio. A successful build stays `ready:false` and may show an infeasible draft.+2. Run `node tools/check.mjs`: geometry, connected paths, budgets and source-data consistency.+ It writes `.harness/survey-check.json`, not a ready verdict.+3. Open the actual viewer. Exercise the user's edited areas, relevant settings, capture inspector,+ data import and save. Preserve both drafts if an agent/browser revision conflict appears.+4. Run `node tools/export.mjs` and reopen the outputs independently. GeoJSON uses longitude,+ latitude; KML is explicitly clamped to ground. CSV height is above takeoff, with nominal time.+ These are planning/review files, not an executable aircraft mission. Test the offline planner.+5. State exactly what was checked and what remains missing. Set a ready verdict only for the+ verified software deliverable. Return the files and concrete next revision choices in the+ person's language. Never claim a real flight, customer trial or subjective “wow” from fixtures.++Keep the original canyon implementation in `store/tools/experiences/drone-pilot.*` for later work.+Existing legacy HTML workspaces remain their original experience; do not silently overwrite them.diff --git a/store/agents/drone-pilot/PROVENANCE.md b/store/agents/drone-pilot/PROVENANCE.mdnew file mode 100644index 000000000..5a43d1774--- /dev/null+++ b/store/agents/drone-pilot/PROVENANCE.md@@ -0,0 +1,25 @@+# Provenance++The planner, geometry adapter, editable UI, data importer, file exporters and synthetic site+fixtures are original OpenHarness contributor work under the package MIT license. The original+FPV canyon implementation remains in `store/tools/experiences/`. The existing Vector identity+is retained; no generated bitmap or downloaded map imagery is included.++- `clipper-lib` 6.4.2 / JS port 6.4.2.2, Boost Software License 1.0 with embedded Tom Wu JSBN terms.+ The vendor file is unmodified, SHA-256+ `a650c6946682edc1a64016f6553eeb5c32ce45eb7ca0ad5d8221961af011d97c`.+ https://github.com/junmer/clipper-lib and https://sourceforge.net/p/jsclipper/wiki/documentation/+ Full notices are in `template/studio/vendor/LICENSE-BOOST.txt` and `LICENSE-JSBN.txt`, the+ standalone HTML payload, and exported `LICENSES.txt`. JSBN license mirror:+ https://github.com/andyperlitch/jsbn/blob/master/LICENSE+- esbuild 0.27.2, MIT, build time. https://github.com/evanw/esbuild+- Playwright Core 1.63.0, Apache-2.0, browser verification. https://github.com/microsoft/playwright+- Shapely 2.0.7 / GEOS and NumPy 1.26.4 are independent test readers, not package runtime dependencies.+ https://shapely.readthedocs.io/en/2.0.7/manual.html+- WGS 84 parameters: https://earth-info.nga.mil/index.php?dir=wgs84&action=wgs84+- GeoJSON: https://datatracker.ietf.org/doc/html/rfc7946+- KML: https://www.ogc.org/standards/kml/++No satellite imagery, real flight records, personal telemetry, aircraft connection, native GIS+import, customer trial or installed-agent prompt completion is implied by authored fixtures.+QGroundControl formats were researched but executable mission export is not part of this release.diff --git a/store/agents/drone-pilot/README.md b/store/agents/drone-pilot/README.mdindex fa7d8fd73..f74ee39a8 100644--- a/store/agents/drone-pilot/README.md+++ b/store/agents/drone-pilot/README.md@@ -1,60 +1,56 @@-# Drone Pilot — Vector+# Drone Pilot · Vector-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our-> standard for an open-ended tool that completes real user work. Existing projects and-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).+Turn a site boundary and photography requirements into an editable field-survey plan. Bring+GeoJSON or draw your own polygons, keep exclusions, choose camera geometry and compare directions.+Inspect each planned capture, split the job into sorties with routed returns, then import recorded+flight CSV to compare the plan with supplied evidence.---Fly a seeded canyon course in first person. Switch between manual controls and a tracking autopilot, inspect gate results and the flight path, and export telemetry.--## Try it--> Design a slalom course over a canyon floor. Make the autopilot fly a clean lap, then give me manual controls and a trace to compare against it.--The starter already works before the first prompt. Change it with the agent, interact with the-result in the pane, and keep the output. Everything needed at runtime is in `flight/index.html`.-It works offline and can be opened outside Harness.+You keep the work: an offline planner, editable project, GIS layers, map overlay, route/photo CSVs,+SVG map and printable report. No account, map key or cloud service is required to use those files.+Existing logos and icons are included. The starter orchard is editable example geometry.## What you can do-Twelve gates, fixed-step dynamics, first-person projection, autopilot/manual handoff, brake/boost, minimap, finite flight and telemetry export.--## Build on the starter--The model functions `flightCourse` and `flightStep` are the starting points for substantive changes. Preserve seed-reproducibility and user controls while changing the domain behavior. A different brief can replace-this starter's entire visual language. Keep the artifact self-contained and test the actual result.--The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed-workspaces are editable HTML; no build tool, network dependency or paid service is required.+- Edit arbitrary named boundaries/exclusions, drag or enter precise vertices, move takeoff, lock+ approved geometry, undo revisions and save the actual project back to the workspace.+- Derive ground sampling and footprint coverage from your camera; enforce capture cadence and+ configured overlap. Compare sampled directions without changing your other requirements.+- Divide captures into nominal time budgets that include climb, descent, transits and a connected+ return. Infeasible settings produce a concrete issue; requirements are not silently relaxed.+- Import your flight CSV with explicit time, coordinate, altitude and event mapping. Inspect+ records, gaps, nearest-route distances and estimated event footprints. Keep original source.+- Export standard GeoJSON, ground-clamped KML, CSV, a printable HTML report and a complete ZIP.+ Reopen the planner offline and keep editing your own geometry and camera settings.-## Verification+## Model scope-Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.-Browser interactions, exports, same-origin APIs and manifest routing: see-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).+This is level-ground, nadir-camera planning within 5 km of the chosen WGS 84 origin, excluding sites that cross the 180° meridian. Camera+footprints and time are geometric/nominal estimates. Terrain, obstacles, airspace, wind, positioning+error and aircraft dynamics are not verified. Files support planning and review; there is no+vehicle connection or executable aircraft mission. Event footprints do not prove that photographs+exist or form a usable map. No photogrammetric reconstruction is included.-`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or-audio equality is promised. The research is inspiration; this is original code, not a wrapper of-any cited third-party engine.+## Build and verify-## Check your actual edited model+Setup resolves Node, installs pinned package-local tools, and reuses Chrome/Chromium or installs+its local browser. In a workspace, `DRONE_DSH_DIR` points to the installed package:-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+```sh+node tools/build.mjs+node tools/check.mjs+node tools/export.mjs+```-## Logo and icon+The browser's **Save to workspace** updates source and retains its previous version. An agent+revision arriving during a browser draft offers both versions. **Save file** keeps `.vector.json`;+**Export field kit** includes the current draft and all delivery files. See the+[project contract](skills/pilot/references/project.md) and [acceptance evidence](test/ACCEPTANCE.md).-The original identity ships in `brand/`: [vector icon](brand/icon.svg),-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.+The original FPV canyon code remains under `store/tools/experiences/drone-pilot.*` for future work.+Existing legacy workspaces are not automatically migrated or overwritten.## Credit and stewardshipOriginal implementation and visual identity by OpenHarness contributors, maintained by-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.+Autonomous under the [MIT license](LICENSE). Dependency notices and source references are in+[PROVENANCE.md](PROVENANCE.md). Report issues in the OpenHarness repository.diff --git a/store/agents/drone-pilot/harness.json b/store/agents/drone-pilot/harness.jsonindex c43607d33..c7ee1fe0b 100644--- a/store/agents/drone-pilot/harness.json+++ b/store/agents/drone-pilot/harness.json@@ -4,7 +4,7 @@"name": "Drone Pilot","category": "Simulation","author": "Autonomous",- "description": "Fly a seeded canyon course in first person. Switch between manual controls and a tracking autopilot, inspect gate results and the flight path, and export telemetry.",+ "description": "Plan a field survey from your own boundary and camera requirements. Edit routes and exclusions, compare capture directions, split time-bounded sorties, inspect recorded flight CSV and keep an editable GIS and report kit.","engine": "claude","workspace": {"template": "template",@@ -15,18 +15,21 @@"instructions": "AGENTS.md","skills": ["skills"- ]+ ],+ "env": {+ "DRONE_DSH_DIR": "${dsh}"+ }},"toolchain": {"setup": "toolchain/setup.sh","doctor": "toolchain/doctor.sh"},"viewer": {- "use": "autonomous/web-viewer",+ "command": "toolchain/viewer.sh","artifactExtensions": [".html"],- "url": "http://127.0.0.1:${port}/?file=${artifact}"+ "url": "http://127.0.0.1:${port}/"},"verdict": ".harness/verdict.json"}diff --git a/store/agents/drone-pilot/skills/pilot/SKILL.md b/store/agents/drone-pilot/skills/pilot/SKILL.mdindex 47fd2646d..022758521 100644--- a/store/agents/drone-pilot/skills/pilot/SKILL.md+++ b/store/agents/drone-pilot/skills/pilot/SKILL.md@@ -1,77 +1,71 @@---name: pilot-description: Build a deterministic, seedable first-person drone flight in one HTML file from a plain-English description. Use whenever the user asks for a drone flight, an FPV line, an obstacle course, a stunt run, or prompt-to-flight.+description: Create and revise field-survey plans from supplied GeoJSON boundaries, exclusions, camera geometry and capture requirements. Use Drone Pilot for editable routes and sorties, recorded-flight CSV analysis, and portable GIS, CSV and report delivery.----# pilot--Take the user's description and produce a **single self-contained `flight/index.html`**-that flies a **deterministic, seedable** first-person drone, loading the seed from a-`?seed=` query param so the web-viewer can preview the current seed and re-seed live.--## The floor (in order)--1. **Seeded PRNG.** A small seeded PRNG derived from the hash of the seed string.- Nothing may call a non-seeded random — the flight must be reproducible.-2. **Seeded course + physics.** A seeded course (gates, rings, obstacles, spawn)- driven by a small, stable fixed-timestep physics loop (position, velocity,- yaw/pitch, throttle).-3. **`?seed=` plumbing.** Reading the param, plus a tiny UI (input + "re-seed"- button, and throttle/steer controls) so the person can browse seeds in the pane.-4. **Named sub-streams.** One PRNG sub-stream per concern (course layout, obstacle- placement, decor) so tuning one doesn't reshuffle the other.--## The gold checklist--- **Trait tables that survive an edition**: seed → flight (course length, obstacle- count, difficulty), and a census that shows no impossible/duplicated course in- the range you claim.-- **Level discipline**: a stable step so nothing explodes at high throttle; a HUD- (throttle, speed, gate count) that reads clearly.-- **Style range**: a racing line, a slalom through gates, a canyon weave, an- obstacle run — matched to the brief, not all at once.-- **Export route**: expose a "watch" mode that flies the seeded course on its own- and a visible minimap or gate list.--## Verify like a pilot, not a compiler--Fly a grid of seeds — actually fly them — and watch.-Two hard checks before "ready":-- **Re-fly same-seed** — it must be identical on this machine.-- **Census the seed range you promise** (e.g. 0–99); reject any stuck camera,- impossible course, or infinite loop.--Be explicit in the verdict about the reproducibility guarantee: same-machine yes;-frame-timing physics you cannot prove bit-identical — say so.--## Verdict feed--Write `.harness/verdict.json` at every change:--```json-{ "spec": 1, "ready": false, "summary": "seeded slalom run · re-seed live · census 0–99 clean",- "findings": [{ "severity": "info", "kind": "reproducibility", "message": "same-machine verification pending; frame-timing physics not provable bit-identical" }],- "artifact": "flight/index.html",- "phases": [{ "id": "seed", "name": "Seeded core", "state": "done" },- { "id": "flight", "name": "The flight", "state": "active" },- { "id": "edition", "name": "Edition", "state": "pending" }],- "updatedAt": "2026-09-18T00:00:00Z" }-```--## Starting from Vector--The template is functional: Twelve gates, fixed-step dynamics, first-person projection, autopilot/manual handoff, brake/boost, minimap, finite flight and telemetry export.--Keep its useful controls and exports when making a user's creation. Test the behavioral core-(flightCourse, flightStep, fixed 1/60 simulation ticks) as well as the visible result. A self-contained HTML file can still have well-separated-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.--Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before-marking the result ready. Export and reopen the result as part of the handoff to the user.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+# From a site to a field kit++Read [the project contract](references/project.md). Start with what the person needs to document+and the measurements they can supply. Translate ground-sampling or overlap requirements into+camera geometry. Preserve their boundary and approved exclusions. Explain missing inputs in+plain language; do not fabricate a georeferenced site, aircraft specifications or flight records.++## Author and revise++1. Read `flight/project.json` and `flight/DESIGN.md`. Distinguish supplied measurements, user+ decisions and explicit draft assumptions. The agent can create original polygon geometry;+ the starter orchard is only an example. Importing a GeoJSON file can replace or extend a site.+2. Author named boundary/exclusion layers and takeoff in local east/north meters. Keep the WGS 84+ origin and locked geometry stable during targeted edits. Camera sensor width is across a run;+ sensor height is along it. Line angles are counterclockwise from east.+3. Run `node tools/build.mjs`. `DRONE_DSH_DIR` resolves tools for materialized workspaces. The HTML+ embeds its runtime; no CDN, map key or cloud service is needed to use or share the planner.+4. Resolve infeasibility explicitly: cadence, narrow geometry, disconnected paths or an inadequate+ return budget. Do not silently relax requested height, speed, overlap, margin or reserve.+5. Compare directions with the UI when useful. It samples 12 angles in 15-degree steps plus the+ current direction and reports time and coverage. This is not a global route optimization.+ Photo footprints and source paths are inspectable. Never imply that a straight geometric+ segment models the aircraft's turn radius, acceleration or navigation error.++The UI supports named area edits, direct vertex dragging, new polygons, precise coordinate edits,+geometry locks, moving takeoff, camera/cadence settings, undo/redo and a take-home project file.+Workspace saves keep prior source in `.harness/history/`. Source changes arriving while the user+has a draft offer both versions. Do not overwrite either without an explicit save/restore choice.+Offline HTML has the same model and browser file import/export; native path opening uses only the+local viewer's explicit home-folder project picker.++## Inspect recorded evidence++Import a CSV with explicit latitude/longitude and time columns. Select elapsed seconds,+milliseconds, or ISO 8601 timestamps with timezone. Altitude requires meters/feet and takeoff/AMSL+reference; AMSL requires supplied takeoff elevation. Heading is degrees clockwise from north.+Battery is a percentage. Events use 1/0, true/false or yes/no, with blank meaning unknown.++The retained original CSV and SHA-256 establish provenance. Row numbers and missing-coordinate+breaks remain in the normalized records. Time gaps above the selected continuity threshold are+not connected. Compare nearest-route distances with all planned routes or one sortie, inspect+individual records and report samples/segments outside the inset region.++Footprint estimates need an event flag, positive height and heading, plus the current camera and+level-ground/nadir assumptions. Do not infer events from ordinary telemetry, fill unknown fields,+call nominal footprints observed images or claim an orthomosaic/photogrammetric reconstruction.+The model does not process photographs. Reimport the original source to revise its mapping.++## Deliver and verify++Run `node tools/check.mjs` for source, geometry and budget checks, then `node tools/export.mjs`:++- `.vector.json`: editable boundaries, settings, camera and retained flight source, if supplied.+- `planner.html`: one offline file with editing and all required runtime/license text embedded.+- `survey.geojson`: source polygons, inset region, routes, planned captures, footprint estimates+ and gaps. Recorded paths/estimated event coverage are separate named features when present.+- `overlay.kml`: map overlay with ground-clamped site and routes; not an altitude or mission file.+- `planned-photos.csv` / `planned-route.csv`: explicit coordinates, height above takeoff and nominal+ times. CSV values are review data, not commands or tested autopilot configuration.+- `site-map.svg`, `report.html` and `report.json`: portable map and calculations; print HTML to PDF.+- Original and normalized recorded CSV when supplied, full dependency licenses, README and ZIP.++Browser exports use the current draft. Reopen GIS/CSV/HTML with an independent reader and review+scale, coordinate order, dates, gaps and source retention. Test the actual viewer edits and an+offline reopen. Record exact commands and outcomes. Unit/schema checks do not establish native+GIS or ground-station imports, a completed real flight, a customer's success or visual quality.diff --git a/store/agents/drone-pilot/skills/pilot/references/project.md b/store/agents/drone-pilot/skills/pilot/references/project.mdnew file mode 100644index 000000000..2cb0e7d60--- /dev/null+++ b/store/agents/drone-pilot/skills/pilot/references/project.md@@ -0,0 +1,49 @@+# Vector 2 project contract++`flight/project.json` is a JSON object with `schema:"vector/2"`, stable `id`, `title`, `brief`,+`origin:[longitude,latitude]`, `home:[east,north]`, `areas`, `camera` and `settings`.++Coordinates are WGS 84 projected through ECEF into the origin's east/north tangent plane.+Each local point stays within 5 km; latitudes are between 85° south/north. Precision is not a+survey-accuracy guarantee. Split sites crossing the 180° meridian before planning; this exporter+does not split polygons at the antimeridian. Polygon clipping rounds to integer millimeters.++Each area is `{id,name,kind,locked,ring}`. Kind is `boundary` or `exclusion`. Ring is an open array+of `[east,north]` vertices in meters; validation normalizes orientation and redundant closure.+Use 3–128 vertices, simple nonintersecting edges and at least 1 m². Up to 32 areas and 200 source+vertices are supported; routing rejects more than 350 offset corners. Names and IDs are stable.+Locks constrain browser edits and indicate geometry the agent should preserve.++Camera fields are `name`, `sensorWidth`, `sensorHeight`, `focalLength` (mm), `imageWidth`,+`imageHeight` (whole pixels), `minInterval` (seconds). Sensor width lies across the capture run.+Settings: `height` (meters above takeoff), `speed`, `climbSpeed`, `descentSpeed` (m/s), `angle`+(0–179.9°, counterclockwise from east), `frontOverlap`, `sideOverlap` (fractions 0–.95), `margin`+(meters), `usableMinutes`, `reservePercent`, `turnSeconds` (fixed allowance per capture run).++The model computes ideal width/height as distance × sensor dimension / focal length. Ground+sampling distance derives from the pixel dimensions. Parallel line and photo spacing honor+requested overlap along regular runs. Camera cadence may make a setting infeasible. Photographs+are centered within clipped runs, connected by visibility-graph transits, and partitioned across+sorties. Budget includes return, climb/descent and allowance. Up to 1,000 grid rows, 3,000 planned+photos and 80 sorties; split larger jobs. Coverage is the union of ideal footprints intersected+with boundary minus exclusions. Boundaries/exclusions can leave uncovered gaps.++Optional `log` is produced by `studio/log.mjs` `importFlight(raw,name,mapping,origin)`. Keep `raw`,+`sha256`, `mapping`, `sourceRows`, `missingCoordinates`, `startTime`, and `records` unchanged.+Records contain elapsed seconds, local point, altitude in meters above takeoff, heading clockwise+from north, battery percentage, capture true/false/null, original row and `breakBefore`.+`comparisonSortie` and `maxGap` are analysis settings. Source consistency is verified on build+and save; only sub-clipping numerical differences between JS runtimes are tolerated.++CSV files are at most 3 MB / 12,000 samples / 80 columns; a whole project is at most 8 MB.+Time must increase strictly. Missing coordinate rows remain counted and break the track. At most+3,000 recorded capture events. Do not edit normalized evidence to make it agree with the plan.++`node tools/build.mjs` validates source and creates standalone `flight/index.html`. It intentionally+allows a structurally valid but infeasible draft, which shows its issue in the UI. `check.mjs` and+`export.mjs` require a feasible plan. A build/check does not set the artifact ready.++Source bridge: GET/PUT `/api/project`, optimistic `If-Match` revision, prior source backups.+The viewer compiles the next preview before replacing source, so a broken studio build leaves+existing files intact. GET `/api/files` lists visible recent project files; POST `/api/open`+opens an explicitly selected `.vector.json` in a draft. No aircraft or external service endpoint.diff --git a/store/agents/drone-pilot/store.json b/store/agents/drone-pilot/store.jsonindex 25f37c3c5..802e2f916 100644--- a/store/agents/drone-pilot/store.json+++ b/store/agents/drone-pilot/store.json@@ -1,16 +1,28 @@{- "listed": false,+ "listed": true,"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/drone-pilot","license": "MIT",- "tagline": "Fly a seeded canyon course in first person",+ "tagline": "Turn your site into a survey plan you can inspect and keep","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/starter.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/works-yard.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/estuary-evidence.jpg"],"examples": [{- "prompt": "Design a slalom course over a canyon floor. Make the autopilot fly a clean lap, then give me manual controls and a trace to compare against it.",- "caption": "Vector · interactive offline starter",+ "prompt": "Use my orchard boundary GeoJSON and camera measurements to plan a photo survey. Keep the pond excluded, show the ground sampling and each camera footprint, and divide the work into sorties that include a return. Give me editable files and a field report.",+ "caption": "Alder Orchard \u00b7 editable capture plan; example geometry","image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/starter.jpg"+ },+ {+ "prompt": "This work site is L-shaped and has two equipment areas to avoid. Compare capture directions and revise the equipment exclusion without moving the approved storage compound. Export a GIS layer and capture table I can review.",+ "caption": "Works Yard \u00b7 original boundary and exclusion geometry",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/works-yard.jpg"+ },+ {+ "prompt": "Compare this recorded CSV with the revised survey plan. I will map the time, altitude units and camera-event columns. Show missing samples and estimated event footprints, and retain my original data with the report.",+ "caption": "Estuary Plots \u00b7 evidence workflow using a synthetic CSV fixture",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/drone-pilot/estuary-evidence.jpg"}]}diff --git a/store/agents/drone-pilot/template/flight/index.html b/store/agents/drone-pilot/template/flight/index.htmlindex 998656932..d62876386 100644--- a/store/agents/drone-pilot/template/flight/index.html+++ b/store/agents/drone-pilot/template/flight/index.html@@ -1,1159 +1,41 @@-<!doctype html>-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">-<meta name="color-scheme" content="dark light"><title>VECTOR — Drone Pilot</title>-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EDrone%20Pilot%20%E2%80%94%20vector%20through%20a%20gate%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%2318323b%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2017%2027%2015v32L48%2079%2021%2064V32Z%22%20fill%3D%22none%22%20stroke%3D%22%23739798%22%20stroke-width%3D%225%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m29%2060%2034-31-9%2040-8-15Z%22%20fill%3D%22%23d3eb9c%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m21%2075%209-9%22%20stroke%3D%22%23d3eb9c%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%2F%3E%0A%3C%2Fsvg%3E">-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->-<style>:root {- color-scheme: dark;- --bg: #111414;- --panel: #191e1c;- --line: #ffffff1c;- --ink: #f4f2e9;- --muted: #a1aaa4;- --accent: #d0f28a;- font:- 14px/1.5 -apple-system,- BlinkMacSystemFont,- "Segoe UI",- sans-serif;-}-* {- box-sizing: border-box;-}-body {- margin: 0;- background: var(--bg);- color: var(--ink);-}-button,-input,-select {- font: inherit;-}-button,-a,-input,-select {- -webkit-tap-highlight-color: transparent;-}-button,-a {- touch-action: manipulation;-}-button {- cursor: pointer;-}-button:disabled {- opacity: 0.45;- cursor: wait;-}-button:focus-visible,-input:focus-visible,-select:focus-visible,-a:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 4px;-}-button,-input,-select {- color: inherit;- background: transparent;- border: 1px solid var(--line);- border-radius: 5px;- padding: 9px 13px;-}-button:hover {- background: #ffffff0c;- border-color: var(--muted);-}-button.primary {- background: var(--accent);- color: #142015;- border-color: transparent;- font-weight: 650;-}-button[aria-pressed="true"] {- border-color: var(--accent);- color: var(--accent);-}-input[type="range"] {- accent-color: var(--accent);- padding: 0;- min-width: 0;-}-input[type="number"] {- width: 80px;-}-select {- background: var(--panel);-}-label {- cursor: pointer;-}-a {- color: inherit;-}-h1,-h2,-h3,-p {- margin: 0;-}-h1 {- font-size: clamp(32px, 5vw, 64px);- line-height: 1.02;- letter-spacing: -0.055em;- font-weight: 550;-}-h2 {- font-weight: 550;- letter-spacing: -0.03em;-}-h3 {- font-size: 14px;- font-weight: 550;-}-.mono,-.eyebrow {- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;-}-.eyebrow {- font-size: 10px;- letter-spacing: 0.16em;- text-transform: uppercase;- color: var(--muted);-}-.muted {- color: var(--muted);-}-.small {- font-size: 12px;-}-.masthead {- display: flex;- align-items: center;- justify-content: space-between;- gap: 20px;- padding: 19px 28px;- border-bottom: 1px solid var(--line);-}-.identity {- display: flex;- gap: 12px;- align-items: center;- white-space: nowrap;- font-size: 12px;- font-weight: 600;- letter-spacing: 0.04em;-}-.mark {- width: 28px;- height: 28px;- flex: 0 0 28px;- display: grid;- place-items: center;-}-.mark svg {- display: block;- width: 100%;- height: 100%;-}-.seed-form {- display: flex;- align-items: center;- gap: 6px;-}-.seed-form label {- font:- 10px ui-monospace,- monospace;- text-transform: uppercase;- letter-spacing: 0.12em;- color: var(--muted);- margin-right: 4px;-}-.seed-form input {- width: 74px;- padding: 6px 8px;- font:- 12px ui-monospace,- monospace;-}-.seed-form button {- padding: 6px 10px;- font-size: 12px;-}-.intro {- padding: 32px 28px;- display: flex;- align-items: flex-end;- justify-content: space-between;- gap: 20px;-}-.intro p {- max-width: 440px;- color: var(--muted);- margin-top: 14px;-}-.intro .eyebrow {- margin-bottom: 12px;-}-.actions {- display: flex;- align-items: center;- gap: 8px;- flex-wrap: wrap;-}-.workspace {- display: grid;- grid-template-columns: minmax(0, 1fr) 270px;- gap: 22px;- padding: 0 28px 28px;-}-.panel {- background: var(--panel);- border: 1px solid var(--line);- border-radius: 8px;- overflow: hidden;-}-.panel-head {- display: flex;- align-items: center;- justify-content: space-between;- padding: 16px 20px;- border-bottom: 1px solid var(--line);- gap: 10px;-}-.side {- display: flex;- flex-direction: column;- gap: 20px;-}-.section {- border-top: 1px solid var(--line);- padding-top: 18px;-}-.section h3 {- margin-bottom: 15px;-}-.field {- display: grid;- gap: 7px;- margin: 14px 0;-}-.field > span {- display: flex;- justify-content: space-between;- font-size: 12px;- color: var(--muted);-}-.metrics {- display: grid;- grid-template-columns: repeat(3, 1fr);- gap: 1px;- background: var(--line);- border: 1px solid var(--line);- border-radius: 6px;- overflow: hidden;-}-.metric {- background: var(--bg);- padding: 13px 15px;-}-.metric strong {- display: block;- font:- 24px ui-monospace,- monospace;- letter-spacing: -0.06em;-}-.metric span {- font-size: 10px;- color: var(--muted);- text-transform: uppercase;- letter-spacing: 0.09em;-}-canvas {- display: block;- max-width: 100%;-}-.status-line {- display: flex;- justify-content: space-between;- gap: 20px;- padding: 14px 28px;- border-top: 1px solid var(--line);- font:- 10px ui-monospace,- monospace;- color: var(--muted);-}-.dot {- width: 6px;- height: 6px;- display: inline-block;- background: var(--accent);- border-radius: 50%;- margin-right: 6px;-}-.toast {- position: fixed;- z-index: 99;- left: 50%;- bottom: 22px;- transform: translateX(-50%);- max-width: 90vw;- background: var(--ink);- color: var(--bg);- padding: 11px 18px;- border-radius: 6px;- box-shadow: 0 3px 30px #0004;- font-size: 12px;-}-.toast:empty {- display: none;-}-[hidden] {- display: none !important;-}-.sr-only {- position: absolute;- width: 1px;- height: 1px;- padding: 0;- margin: -1px;- overflow: hidden;- clip-path: inset(50%);- white-space: nowrap;- border: 0;-}-@media (max-width: 800px) {- .workspace {- grid-template-columns: 1fr;- }- .side {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- }- .intro {- align-items: flex-start;- flex-direction: column;- }- .intro h1 {- font-size: 44px;- }-}-@media (max-width: 480px) {- .masthead {- padding: 13px 16px;- gap: 8px;- flex-wrap: wrap;- }- .intro {- padding: 26px 16px;- }- .intro h1 {- font-size: 38px;- }- .workspace {- padding: 0 16px 20px;- gap: 18px;- }- .side {- grid-template-columns: 1fr;- }- .seed-form label {- display: none;- }- .status-line {- padding: 12px 16px;- }- .status-line span:last-child {- display: none;- }- .metrics .metric {- padding: 12px 10px;- }- .panel-head {- padding: 12px;- }- .actions {- gap: 6px;- }-}-@media (prefers-reduced-motion: reduce) {- *,- *::before,- *::after {- scroll-behavior: auto !important;- animation: none !important;- transition: none !important;- }-}--:root {- --bg: #152025;- --panel: #1e2d32;- --ink: #e3ece5;- --muted: #9ab0b5;- --line: #66838744;- --accent: #c7e39b;-}-.flight-layout {- display: grid;- grid-template-columns: minmax(0, 1fr) 240px;- gap: 24px;- padding: 0 28px 28px;-}-.cockpit {- position: relative;- min-height: 530px;- border: 1px solid var(--line);- border-radius: 8px;- overflow: hidden;- background: #293f45;-}-.cockpit > canvas {- width: 100%;- height: 100%;- position: absolute;- inset: 0;- outline-offset: -3px;-}-.hud-top {- position: absolute;- top: 20px;- left: 20px;- right: 20px;- display: flex;- justify-content: space-between;- font:- 10px ui-monospace,- monospace;- letter-spacing: 0.1em;- text-shadow: 0 1px 3px #000;-}-.hud-bottom {- position: absolute;- bottom: 20px;- left: 25px;- right: 25px;- display: flex;- justify-content: space-between;- pointer-events: none;-}-.hud-bottom > div {- display: grid;- text-shadow: 0 2px 5px #000;-}-.hud-bottom strong {- font:- 32px ui-monospace,- monospace;- letter-spacing: -0.06em;-}-.hud-bottom span {- font:- 9px ui-monospace,- monospace;- opacity: 0.8;-}-.reticle {- position: absolute;- left: 50%;- top: 50%;- transform: translate(-50%, -50%);- font-size: 27px;- color: #ffffff99;- pointer-events: none;-}-.gate-hint {- position: absolute;- top: 56px;- left: 20px;- font:- 10px ui-monospace,- monospace;- color: #d4e9d0;-}-.flight-aside {- display: flex;- flex-direction: column;- gap: 22px;-}-.flight-actions {- display: grid;- gap: 8px;-}-.flight-actions button {- width: 100%;-}-#minimap {- width: 100%;- height: 180px;- margin-top: 12px;-}-.flight-pad {- display: grid;- grid-template-columns: repeat(3, 38px);- gap: 5px;- margin-top: 15px;-}-.flight-pad button:first-child {- grid-column: 2;-}-.flight-pad button:nth-child(2) {- grid-column: 1;-}-.flight-pad button {- touch-action: none;-}-.flight-summary {- position: absolute;- inset: 32% 10% auto;- background: #142124eb;- border: 1px solid #b3cdaf55;- padding: 24px;- text-align: center;- backdrop-filter: blur(8px);- font-size: 24px;-}-.flight-summary span {- font-size: 12px;- display: block;- margin-top: 8px;- color: var(--muted);-}-@media (max-width: 800px) {- .flight-layout {- grid-template-columns: 1fr;- }- .cockpit {- min-height: 500px;- }- .flight-aside {- display: grid;- grid-template-columns: 1fr 1fr;- }- .flight-actions {- align-content: start;- }- .flight-aside .section {- margin: 0;- }-}-@media (max-width: 480px) {- .flight-layout {- padding: 0 16px 20px;- }- .cockpit {- min-height: 440px;- }- .hud-top {- left: 12px;- right: 12px;- font-size: 8px;- }- .hud-bottom {- left: 14px;- right: 14px;- }- .hud-bottom strong {- font-size: 25px;- }- .flight-aside {- gap: 15px;- }- .flight-pad {- grid-template-columns: repeat(3, 34px);- }-}+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vector — Field Studio</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EDrone%20Pilot%20%E2%80%94%20vector%20through%20a%20gate%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%2318323b%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2017%2027%2015v32L48%2079%2021%2064V32Z%22%20fill%3D%22none%22%20stroke%3D%22%23739798%22%20stroke-width%3D%225%22%20stroke-linejoin%3D%22round%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m29%2060%2034-31-9%2040-8-15Z%22%20fill%3D%22%23d3eb9c%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m21%2075%209-9%22%20stroke%3D%22%23d3eb9c%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%2F%3E%0A%3C%2Fsvg%3E%0A"><style>:root{color-scheme:light;--paper:#f9faf6;--ink:#273c31;--muted:#758074;--line:#dde2d7;--orange:#c65a32;--pale:#eef1e8;--teal:#267d81;font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink)}button,input,select,textarea{font:inherit}button{cursor:pointer;background:transparent;border:1px solid var(--line);border-radius:7px;padding:8px 12px;color:inherit;white-space:nowrap}button:hover{background:#edf0e7;border-color:#c4cdbd}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:2px}button:disabled{opacity:.42;cursor:default}.primary{background:var(--ink);border-color:var(--ink);color:white}.primary:hover{background:#395844;color:white}header{display:flex;align-items:center;gap:30px;min-height:83px;padding:17px 25px;border-bottom:1px solid var(--line)}.identity{display:flex;gap:10px;align-items:center;min-width:176px;font-size:14px;font-weight:750;letter-spacing:2px}.identity small{display:block;font-size:8px;letter-spacing:2.2px;color:var(--muted);font-weight:550}.mark svg{width:38px;height:38px}.project-heading{border:0;text-align:left;padding:0;white-space:normal}.project-heading strong{display:block;font-size:17px;font-weight:650}.project-heading span{font-size:11px;color:var(--muted)}header nav{margin-left:auto;display:flex;gap:8px}.metrics{display:flex;align-items:center;min-height:92px;border-bottom:1px solid var(--line);padding:16px 25px;gap:0}.metric{flex:1;border-right:1px solid var(--line);padding:0 25px}.metric:first-child{padding-left:0}.metric:last-child{border:0}.metric small{font-size:9px;letter-spacing:1.2px;text-transform:uppercase;color:var(--muted);display:block}.metric b{font-size:25px;letter-spacing:-.6px;font-weight:550}.metric em{font-style:normal;font-size:11px;font-weight:400;margin-left:5px;color:var(--muted)}main{display:grid;grid-template-columns:280px minmax(380px,1fr) 258px;min-height:650px;height:calc(100vh - 211px)}aside{overflow:auto;scrollbar-width:thin}.controls{border-right:1px solid var(--line);padding:20px}.details{border-left:1px solid var(--line);padding:20px 17px}.tabs{display:flex;gap:14px;border-bottom:1px solid var(--line);margin-bottom:21px}.tabs button{border:0;border-radius:0;padding:0 0 12px;font-weight:600;font-size:12px}.tabs .active{border-bottom:2px solid var(--orange);color:var(--orange)}.section-title,.eyebrow{font-size:9px;letter-spacing:1.3px;color:var(--muted);font-weight:650}.section-title{display:flex;align-items:center;justify-content:space-between;margin:0 0 13px}.section-title button{font-size:10px;padding:3px 6px}.section-title span{letter-spacing:0}.controls section+section,.details section+section{border-top:1px solid var(--line);margin-top:22px;padding-top:20px}label{display:block;font-size:11px;color:#5d6b5e;margin:11px 0}input:not([type=checkbox]),select,textarea{display:block;width:100%;border:1px solid var(--line);border-radius:5px;background:#fffefa;color:var(--ink);padding:8px;margin-top:5px;min-width:0}input[type=number]{font-variant-numeric:tabular-nums}textarea{resize:vertical}.two{display:grid;grid-template-columns:1fr 1fr;gap:0 12px}.two label{min-width:0}.controls p,.details p{font-size:11px;line-height:1.65;color:var(--muted)}details summary{cursor:pointer;font-size:11px;color:var(--muted);margin:15px 0}.hint{background:var(--pale);padding:12px;border-radius:6px;font-size:11px}.stage{min-width:0;display:flex;flex-direction:column;background:#f0f2e9}.map-toolbar{display:flex;align-items:center;justify-content:space-between;padding:12px 15px;gap:8px;background:var(--paper);border-bottom:1px solid var(--line)}.map-toolbar button{font-size:10px;padding:7px 9px}.segmented{display:flex;border:1px solid var(--line);border-radius:6px;padding:2px;gap:1px}.segmented button{border:0}.segmented .active{background:var(--pale);color:var(--ink)}.map-wrap{position:relative;flex:1;min-height:470px;overflow:hidden}#map{width:100%;height:100%;position:absolute;inset:0;touch-action:none}#map .area{cursor:pointer;vector-effect:non-scaling-stroke}#map .handle{cursor:move;vector-effect:non-scaling-stroke}#map [data-home]{cursor:move}.map-heading{position:absolute;top:23px;left:25px;pointer-events:none;max-width:70%}.map-heading h1{font-family:Georgia,"Times New Roman",serif;font-size:29px;font-weight:400;letter-spacing:-.8px;margin:5px 0 3px}.map-heading p{font-size:10px;color:var(--muted);margin:0}.north{position:absolute;right:22px;top:23px;display:flex;flex-direction:column;text-align:center;font-size:9px;color:#7c8879}.north span{font-size:31px;line-height:1}.map-legend{position:absolute;bottom:61px;left:20px;display:flex;gap:12px;flex-wrap:wrap;font-size:9px;color:var(--muted);pointer-events:none}.map-legend span{display:flex;align-items:center;gap:5px}.map-legend i{width:8px;height:8px;display:inline-block;border-radius:2px}.boundary-key{background:#86a77d}.route-key{background:var(--orange)}.exclude-key{background:#cc8b7c}.log-key{background:var(--teal)}.map-actions{position:absolute;bottom:20px;right:17px;display:flex;background:#fafbf5ee;border:1px solid var(--line);border-radius:6px}.map-actions button{border:0;font-size:11px;padding:7px 10px}.map-caption{position:absolute;bottom:23px;left:22px;font-size:9px;color:#7b8575;display:flex;gap:12px;flex-wrap:wrap;max-width:48%}.assumptions{display:flex;align-items:center;gap:12px;padding:9px 17px;background:var(--paper);border-top:1px solid var(--line);font-size:10px;color:var(--muted)}.assumptions span{font-size:8px;letter-spacing:1px;background:var(--pale);padding:3px 5px;border-radius:3px}.assumptions p{margin:0}.assumptions button{font-size:10px;border:0;padding:0;text-decoration:underline;color:#597256}.area-row{width:100%;display:flex;align-items:center;text-align:left;gap:8px;padding:10px 8px;border:1px solid transparent;font-size:11px;margin:4px 0;white-space:normal}.area-row.active{background:#edf1e7;border-color:#d7e0ce}.area-row i{width:8px;height:8px;border-radius:2px;flex-shrink:0}.area-row span{flex:1}.area-row small{font-size:10px;color:var(--muted)}#area-editor{padding:3px 8px}#area-editor textarea{font:10px/1.7 monospace}.row-actions{display:flex;gap:6px}.row-actions button{font-size:10px;padding:5px 8px}.sortie{display:block;width:100%;text-align:left;padding:12px 10px;margin-bottom:7px;border-radius:6px}.sortie .row{display:flex;justify-content:space-between;gap:8px;font-size:11px}.sortie .row b{font-weight:650}.sortie small{display:block;font-size:9px;color:var(--muted);margin-top:4px}.sortie .bar{height:3px;background:#e9ede2;margin-top:9px;border-radius:3px}.sortie .bar i{display:block;height:100%;background:#b3bf99;border-radius:3px}.sortie.active{background:#edf1e7;border-color:#b9cba5}.check{display:flex;gap:7px;align-items:center;font-size:11px}.check input{accent-color:var(--ink)}.evidence-metrics{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:17px 0}.evidence-metrics div{background:var(--pale);padding:10px;border-radius:5px;font-size:9px;color:var(--muted)}.evidence-metrics b{display:block;color:var(--ink);font-size:21px;font-weight:550}.notice,.plan-error{padding:12px 25px;background:#f7e8cf;color:#765222;display:flex;gap:12px;align-items:center}.notice span{flex:1}.plan-error{border-bottom:1px solid #e5c79f;font-size:12px}.notice button{font-size:11px;border-color:#d9bd8d}#draw-help{position:absolute;top:115px;left:20px;right:20px;background:#fffefa;padding:12px;border:1px solid #d7dfca;box-shadow:0 5px 20px #24302012;border-radius:7px;font-size:11px;display:flex;align-items:center;gap:7px}#draw-help span{flex:1}#draw-help button{font-size:10px;padding:6px}footer{height:36px;border-top:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;padding:0 22px;font-size:10px;color:var(--muted)}footer #status{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:80%}dialog{background:var(--paper);color:var(--ink);border:1px solid var(--line);border-radius:13px;padding:30px;max-width:min(94vw,590px);width:590px;max-height:88vh;box-shadow:0 24px 100px #19322033}dialog::backdrop{background:#15251aaa;backdrop-filter:blur(3px)}dialog h2{font:29px Georgia,serif;margin:0 0 15px;letter-spacing:-.5px}dialog p{font-size:12px;color:var(--muted)}dialog label{font-size:12px}dialog .dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:22px}.dialog-error{background:#f5e2d7;color:#92492e;padding:12px;border-radius:5px;white-space:normal}.export-options{display:grid;gap:10px;margin:22px 0}.export-options button{text-align:left;padding:15px;white-space:normal}.export-options strong{display:block;font-size:13px}.export-options span{display:block;font-size:11px;opacity:.7;margin-top:3px}.wide-dialog{width:670px;max-width:min(94vw,670px)}#native-open{margin-top:20px}#recent-projects button{display:block;width:100%;text-align:left;margin-top:7px;white-space:normal;font-size:11px}[hidden]{display:none!important}@media(min-width:1550px){main{grid-template-columns:306px minmax(380px,1fr) 280px}.controls,.details{padding:24px}.metric b{font-size:29px}}@media(max-width:1190px){main{grid-template-columns:258px minmax(380px,1fr)}.details{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;border-left:0;border-top:1px solid var(--line)}.details section+section{margin:0;padding:0 0 0 20px;border-top:0;border-left:1px solid var(--line)}main{height:auto}.stage{min-height:650px}.controls{max-height:780px}.metric{padding:0 14px}.metric b{font-size:22px}header{gap:20px}.identity{min-width:130px}header nav button{font-size:11px}}@media(max-width:740px){header{padding:12px 14px;gap:12px;flex-wrap:wrap}.identity{min-width:auto}.identity small{display:none}.mark svg{width:29px;height:29px}.project-heading{margin-left:auto}.project-heading strong{font-size:14px}header nav{width:100%;display:grid;grid-template-columns:1fr 1fr;gap:7px}header nav button{min-width:0}.metrics{flex-wrap:wrap;padding:10px 14px;gap:12px}.metric{flex:0 0 calc(33.33% - 12px);padding:0;border:0}.metric b{font-size:22px}.metric small{font-size:8px}.metric em{font-size:9px}main{display:flex;flex-direction:column}.stage{order:0;min-height:550px}.controls{order:1;border:0;border-top:1px solid var(--line);max-height:none;padding:20px}.details{order:2;display:block;padding:20px}.details section+section{border-left:0;border-top:1px solid var(--line);padding:20px 0 0;margin-top:20px}.map-toolbar{padding:9px 7px;gap:4px}.map-toolbar button{padding:6px;font-size:9px}.map-heading h1{font-size:25px}.map-heading{left:18px}.map-caption{font-size:8px;max-width:45%;gap:3px}.map-actions button{padding:7px}.map-legend{gap:8px;font-size:8px;left:14px}.assumptions{font-size:9px}.assumptions button{font-size:9px}footer{height:auto;min-height:36px;padding:8px 14px}footer>span:last-child{display:none}footer #status{max-width:100%}#draw-help{flex-wrap:wrap;top:102px}#draw-help span{flex-basis:100%}.notice{flex-wrap:wrap;padding:12px}.notice span{flex-basis:100%}}</style></head><body>-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+<header><div class="identity"><span class="mark"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96"><title>Drone Pilot — vector through a gate</title><rect x="4" y="4" width="88" height="88" rx="23" fill="#18323b"/><path d="m48 17 27 15v32L48 79 21 64V32Z" fill="none" stroke="#739798" stroke-width="5" stroke-linejoin="round"/><path d="m29 60 34-31-9 40-8-15Z" fill="#d3eb9c"/><path d="m21 75 9-9" stroke="#d3eb9c" stroke-width="5" stroke-linecap="round"/>-</svg></span>VECTOR / FLIGHT</div>-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>-<section class="intro">- <div>- <p class="eyebrow">Training ground / Canyon sector 07</p>- <h1>Find your line.</h1>- <p>- Fly it yourself. Study the autopilot. Every gate, correction and split is- yours to inspect.- </p>- </div>- <button id="export-flight">Export telemetry ↗</button>-</section>-<main class="flight-layout">- <section class="cockpit">- <canvas- id="flight"- tabindex="0"- aria-label="First person drone flight. Use W and S to climb and descend, A and D to steer, Space to brake."- ></canvas>- <div class="hud-top">- <span- ><i class="dot"></i- ><span id="flight-mode">READY / AUTOPILOT</span></span- ><span id="flight-clock">00:00.00</span>- </div>- <div class="reticle" aria-hidden="true">+</div>- <div class="gate-hint" id="gate-hint">12 gates. One clean line.</div>- <div class="hud-bottom">- <div><strong id="velocity">0</strong><span>m/s · airspeed</span></div>- <div><strong id="altitude">13.0</strong><span>m · altitude</span></div>- <div><strong id="gates">0 / 12</strong><span>gates cleared</span></div>- </div>- <div id="flight-summary" class="flight-summary" hidden role="status"></div>- </section>- <aside class="flight-aside">- <div class="flight-actions">- <button class="primary" id="start-flight">▶ Watch autopilot</button- ><button id="manual">Take control</button- ><button id="reset-flight">↻ Restart course</button>- </div>- <section class="section">- <p class="eyebrow">The racing line</p>- <canvas- id="minimap"- aria-label="Course overview and recorded flight path"- ></canvas>- </section>- <section class="section">- <h3>Flight controls</h3>- <p class="small muted">- W / S · climb / descend<br />A / D · steer left / right<br />Shift ·- boost Space · brake- </p>- <div class="flight-pad">- <button data-axis="y" data-value="1" aria-label="Climb">↑</button- ><button data-axis="x" data-value="-1" aria-label="Steer left">←</button- ><button data-axis="y" data-value="-1" aria-label="Descend">↓</button- ><button data-axis="x" data-value="1" aria-label="Steer right">- →- </button>- </div>- </section>- <section class="section small muted">- <p>- Fixed-step browser simulation. The autopilot is a local tracking- controller you can inspect and replace.- </p>- <p style="margin-top: 8px">- Flight dynamics are illustrative. This does not control a physical- drone.- </p>- </section>- </aside>-</main>-<footer class="status-line">- <span><i class="dot"></i>60 Hz SIMULATION / SEEDED COURSE</span- ><span>PRECISION IS A FEELING YOU CAN LEARN.</span>-</footer>-<div class="toast" id="toast" role="status"></div>-<script id="harness-model">-'use strict';-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.-function hash(value) {- let h = 2166136261;- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);- return h >>> 0;-}-function random(seed, stream = "main") {- let a = hash(`${seed}:${stream}`);- return () => {- a = (a + 0x6d2b79f5) | 0;- let t = Math.imul(a ^ (a >>> 15), 1 | a);- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };-}-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));-const lerp = (a, b, t) => a + (b - a) * t;-const pick = (items, rng) => items[Math.floor(rng() * items.length)];-function normal(rng) {- return (- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *- Math.cos(2 * Math.PI * rng())- );-}+</svg>+</span><div>VECTOR<small>FIELD STUDIO</small></div></div><button id="project-details" class="project-heading"><strong id="project-title"></strong><span id="save-state">Opening project</span></button><nav><button id="open-project">Open project</button><button id="save-project">Save file</button><button id="save-source" hidden>Save to workspace</button><button id="deliver" class="primary">Export field kit ↗</button></nav></header>+<div id="source-notice" class="notice" hidden><span></span><button id="draft-keep">Download my draft</button><button id="source-load">Use source version</button></div>+<section id="metrics" class="metrics"></section><div id="plan-error" class="plan-error" role="alert" hidden></div>+<main><aside class="controls"><div class="tabs"><button id="plan-tab" class="active">Survey plan</button><button id="evidence-tab">Flight evidence</button></div><div id="settings-panel"></div><div id="evidence-panel" hidden></div></aside>+<section class="stage"><div class="map-toolbar"><div class="segmented"><button data-tool="select" class="active">↖ Edit</button><button data-tool="boundary">+ Boundary</button><button data-tool="exclusion">⊘ Exclusion</button><button data-tool="home">⌖ Takeoff</button></div><button id="import-geo">Import GeoJSON</button></div><div class="map-wrap"><svg id="map" aria-label="Editable georeferenced site map" role="img" tabindex="0"></svg><div class="map-heading"><span class="eyebrow">SITE OVERVIEW</span><h1 id="map-title"></h1><p id="map-subtitle"></p></div><div class="north">N<span>↑</span></div><div class="map-legend"><span><i class="boundary-key"></i>Site</span><span><i class="route-key"></i>Planned route</span><span><i class="exclude-key"></i>Exclusion</span><span id="log-legend" hidden><i class="log-key"></i>Recorded track</span></div><div class="map-actions"><button id="undo" title="Undo">↶</button><button id="redo" title="Redo">↷</button><button id="zoom-in" title="Zoom in">+</button><button id="zoom-out" title="Zoom out">−</button><button id="frame-site">Fit site</button></div><div id="draw-help" hidden><span>Click to add corners. Double-click or press Enter to finish.</span><button id="finish-draw">Finish polygon</button><button id="cancel-draw">Cancel</button></div><div class="map-caption"><span id="map-origin"></span><span id="scale"></span></div></div><div class="assumptions"><span>MODEL</span><p>Level ground · nadir camera · nominal timing. <button id="model-details">View assumptions</button></p></div></section>+<aside class="details"><section><div class="section-title">SITE LAYERS <span id="area-count"></span></div><div id="area-list"></div><div id="area-editor"></div></section><section><div class="section-title">SORTIES <button id="show-all">Show all</button></div><div id="sortie-list"></div></section><section class="coverage"><div class="section-title">IMAGE FOOTPRINTS</div><label class="check"><input id="show-coverage" type="checkbox"> Show nominal coverage</label><label class="check"><input id="show-gaps" type="checkbox" checked> Show coverage gaps</label><p>Coverage is a geometric estimate. It does not establish image quality or mapping accuracy.</p></section></aside></main>+<footer><span id="status" role="status">Ready to plan your site</span><span>Local files · works offline</span></footer>+<dialog id="project-dialog"><h2>Project & map origin</h2><label>Project title<input id="title-input" maxlength="120"></label><label>Brief<textarea id="brief-input" rows="4" maxlength="4000"></textarea></label><div class="two"><label>Origin longitude<input id="origin-lon" type="number" step="any"></label><label>Origin latitude<input id="origin-lat" type="number" step="any"></label></div><p>Coordinates are WGS 84. Changing the origin relocates all local geometry; vertices remain in east/north meters. A recorded log must be removed before relocation.</p><div class="dialog-actions"><button data-close>Cancel</button><button id="apply-project" class="primary">Apply</button></div></dialog>+<dialog id="open-dialog"><h2>Open a project</h2><p>Open an editable .vector.json file. The existing source changes only when you save to the workspace.</p><button id="choose-project">Choose file…</button><section id="native-open"><label>Or paste a project path in your home folder<input id="project-path" placeholder="~/Downloads/my-site.vector.json"></label><button id="open-path">Open this project</button><div id="recent-projects"></div></section><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="geo-dialog"><h2>Bring your site</h2><p>Import WGS 84 polygon GeoJSON. Interior rings become exclusions; a boundary/exclusion kind property is retained. You can edit every vertex after import.</p><label>Import mode<select id="geo-mode"><option value="replace">Replace site and use file coordinates</option><option value="add">Add to this site at its current origin</option></select></label><label>Default polygon layer<select id="geo-kind"><option value="boundary">Site boundaries</option><option value="exclusion">Exclusions</option></select></label><p>Replace starts a new site draft and removes any recorded log. Undo restores the prior project.</p><button id="choose-geo" class="primary">Choose GeoJSON…</button><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="log-dialog" class="wide-dialog"><h2>Read a recorded flight</h2><p id="log-name"></p><div id="log-mapping" class="two"></div><p>Heading is degrees clockwise from north. Capture events must be 1/0, true/false or yes/no; blank means unknown. Battery is a percentage. No photograph is inferred from a track sample.</p><div class="dialog-actions"><button data-close>Cancel</button><button id="apply-log" class="primary">Import recorded flight</button></div></dialog>+<dialog id="export-dialog"><h2>Take the field kit with you</h2><p id="export-summary"></p><div class="export-options"><button id="export-geo"><strong>GIS layers · GeoJSON</strong><span>Site, exclusions, routes, captures and coverage</span></button><button id="export-kml"><strong>Map overlay · KML</strong><span>Ground-clamped route and site geometry</span></button><button id="export-report"><strong>Survey report · HTML / PDF</strong><span>Calculations, assumptions and recorded evidence</span></button><button id="export-kit" class="primary"><strong>Complete editable kit · ZIP</strong><span>Planner, project, GIS, CSV, report and original log</span></button></div><p>Files support planning, review and GIS workflows. They are not an aircraft mission. No vehicle connection or upload is included.</p><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="model-dialog"><h2>What the model measures</h2><p>Vector computes local geometry within 5 km of a WGS 84 origin. Boundary insets and exclusion buffers constrain connected horizontal routes. Camera geometry determines ideal footprints and regular-run overlap.</p><p>Height is above takeoff. The ground is assumed level with takeoff and the camera points straight down, aligned with each run. No terrain model, obstacle data, airspace check, wind, navigation error or aircraft dynamics are included.</p><p>Time includes distance at the configured speed, climb and descent rates, a fixed allowance per capture run and a connected return to takeoff. The usable duration and reserve are inputs, not a validated battery prediction.</p><p>Recorded evidence uses only supplied samples. Gaps remain gaps. Footprints require actual event flags, height and heading; they still do not prove that an image exists or is suitable for mapping.</p><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<input id="project-file" type="file" accept=".json,.vector.json" hidden><input id="geo-file" type="file" accept=".json,.geojson" hidden><input id="log-file" type="file" accept=".csv,text/csv" hidden>+<script id="vector-data" type="application/json">{"project":{"schema":"vector/2","id":"alder-orchard","title":"Alder Orchard","brief":"Example geometry, not a surveyed or authorized site. Document the orchard blocks, avoid the irrigation pond and keep a return allowance in each sortie. Replace the boundary and camera with measured values before doing your own planning.","origin":[-122.802,38.466],"home":[20,20],"areas":[{"id":"orchard","name":"Orchard blocks","kind":"boundary","locked":false,"ring":[[0,0],[420,0],[420,260],[280,300],[0,300]]},{"id":"pond","name":"Irrigation pond","kind":"exclusion","locked":true,"ring":[[200,100],[265,95],[285,150],[240,175],[200,150]]}],"camera":{"name":"Example camera — enter your measured specs","sensorWidth":13.2,"sensorHeight":8.8,"focalLength":8.8,"imageWidth":5472,"imageHeight":3648,"minInterval":1},"settings":{"height":55,"speed":6,"angle":0,"frontOverlap":0.75,"sideOverlap":0.7,"margin":6,"usableMinutes":14,"reservePercent":20,"climbSpeed":3,"descentSpeed":2,"turnSeconds":3},"revision":"33c3f2588bea8f2e04fffa3134b8238cae28510901555baa274496af60a3512c"},"licenses":"Clipper 6.4.2 / JavaScript port 6.4.2.2\nCopyright Angus Johnson 2010–2017; Timo Kähkönen 2012–2017.\nUnmodified clipper-lib 6.4.2 from https://github.com/junmer/clipper-lib\n\nBoost Software License - Version 1.0 - August 17th, 2003\n\nPermission is hereby granted, free of charge, to any person or organization\nobtaining a copy of the software and accompanying documentation covered by\nthis license (the \"Software\") to use, reproduce, display, distribute,\nexecute, and transmit the Software, and to prepare derivative works of the\nSoftware, and to permit third-parties to whom the Software is furnished to\ndo so, all subject to the following:\n\nThe copyright notices in the Software and this entire statement, including\nthe above license grant, this restriction and the following disclaimer,\nmust be included in all copies of the Software, in whole or in part, and\nall derivative works of the Software, unless such copies or derivative\nworks are solely in the form of machine-executable object code generated by\na source language processor.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\nSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\nFOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n\nJSBN subset within Clipper:\nLicensing\n---------\n\nThis software is covered under the following copyright:\n\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND, \n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY \n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. \n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n\nAddress all questions regarding this license to:\n\n Tom Wu\n [email protected]\n"}</script><script>(()=>{var zn=Object.create;var ri=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var Qn=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var ir=(i,l)=>()=>(l||i((l={exports:{}}).exports,l),l.exports);var nr=(i,l,a,h)=>{if(l&&typeof l=="object"||typeof l=="function")for(let f of Qn(l))!er.call(i,f)&&f!==a&&ri(i,f,{get:()=>l[f],enumerable:!(h=Kn(l,f))||h.enumerable});return i};var rr=(i,l,a)=>(a=i!=null?zn(tr(i)):{},nr(l||!i||!i.__esModule?ri(a,"default",{value:i,enumerable:!0}):a,i));var oi=ir((pr,ye)=>{(function(){"use strict";var i={};i.version="6.4.2.2",i.use_lines=!0,i.use_xyz=!1;var l=!1;typeof ye<"u"&&ye.exports?(ye.exports=i,l=!0):(typeof define=="function"&&define.amd&&define(i),typeof document<"u"?window.ClipperLib=i:self.ClipperLib=i);var a;if(l){var h="chrome";a="Netscape"}else{var h=navigator.userAgent.toString().toLowerCase();a=navigator.appName}var f={};h.indexOf("chrome")!=-1&&h.indexOf("chromium")==-1?f.chrome=1:f.chrome=0,h.indexOf("chromium")!=-1?f.chromium=1:f.chromium=0,h.indexOf("safari")!=-1&&h.indexOf("chrome")==-1&&h.indexOf("chromium")==-1?f.safari=1:f.safari=0,h.indexOf("firefox")!=-1?f.firefox=1:f.firefox=0,h.indexOf("firefox/17")!=-1?f.firefox17=1:f.firefox17=0,h.indexOf("firefox/15")!=-1?f.firefox15=1:f.firefox15=0,h.indexOf("firefox/3")!=-1?f.firefox3=1:f.firefox3=0,h.indexOf("opera")!=-1?f.opera=1:f.opera=0,h.indexOf("msie 10")!=-1?f.msie10=1:f.msie10=0,h.indexOf("msie 9")!=-1?f.msie9=1:f.msie9=0,h.indexOf("msie 8")!=-1?f.msie8=1:f.msie8=0,h.indexOf("msie 7")!=-1?f.msie7=1:f.msie7=0,h.indexOf("msie ")!=-1?f.msie=1:f.msie=0,i.biginteger_used=null;var m,v=0xdeadbeefcafe,y=(v&16777215)==15715070;function c(t,e,n){i.biginteger_used=1,t!=null&&(typeof t=="number"&&typeof e>"u"?this.fromInt(t):typeof t=="number"?this.fromNumber(t,e,n):e==null&&typeof t!="string"?this.fromString(t,256):this.fromString(t,e))}function x(){return new c(null,void 0,void 0)}function N(t,e,n,r,o,s){for(;--s>=0;){var u=e*this[t++]+n[r]+o;o=Math.floor(u/67108864),n[r++]=u&67108863}return o}function O(t,e,n,r,o,s){for(var u=e&32767,p=e>>15;--s>=0;){var d=this[t]&32767,P=this[t++]>>15,w=p*d+P*u;d=u*d+((w&32767)<<15)+n[r]+(o&1073741823),o=(d>>>30)+(w>>>15)+p*P+(o>>>30),n[r++]=d&1073741823}return o}function I(t,e,n,r,o,s){for(var u=e&16383,p=e>>14;--s>=0;){var d=this[t]&16383,P=this[t++]>>14,w=p*d+P*u;d=u*d+((w&16383)<<14)+n[r]+o,o=(d>>28)+(w>>14)+p*P,n[r++]=d&268435455}return o}y&&a=="Microsoft Internet Explorer"?(c.prototype.am=O,m=30):y&&a!="Netscape"?(c.prototype.am=N,m=26):(c.prototype.am=I,m=28),c.prototype.DB=m,c.prototype.DM=(1<<m)-1,c.prototype.DV=1<<m;var b=52;c.prototype.FV=Math.pow(2,b),c.prototype.F1=b-m,c.prototype.F2=2*m-b;var _="0123456789abcdefghijklmnopqrstuvwxyz",D=new Array,Y,L;for(Y=48,L=0;L<=9;++L)D[Y++]=L;for(Y=97,L=10;L<36;++L)D[Y++]=L;for(Y=65,L=10;L<36;++L)D[Y++]=L;function Z(t){return _.charAt(t)}function ot(t,e){var n=D[t.charCodeAt(e)];return n??-1}function H(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s}function F(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0}function X(t){var e=x();return e.fromInt(t),e}function G(t,e){var n;if(e==16)n=4;else if(e==8)n=3;else if(e==256)n=8;else if(e==2)n=1;else if(e==32)n=5;else if(e==4)n=2;else{this.fromRadix(t,e);return}this.t=0,this.s=0;for(var r=t.length,o=!1,s=0;--r>=0;){var u=n==8?t[r]&255:ot(t,r);if(u<0){t.charAt(r)=="-"&&(o=!0);continue}o=!1,s==0?this[this.t++]=u:s+n>this.DB?(this[this.t-1]|=(u&(1<<this.DB-s)-1)<<s,this[this.t++]=u>>this.DB-s):this[this.t-1]|=u<<s,s+=n,s>=this.DB&&(s-=this.DB)}n==8&&(t[0]&128)!=0&&(this.s=-1,s>0&&(this[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),o&&c.ZERO.subTo(this,this)}function et(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t}function ct(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(t==16)e=4;else if(t==8)e=3;else if(t==2)e=1;else if(t==32)e=5;else if(t==4)e=2;else return this.toRadix(t);var n=(1<<e)-1,r,o=!1,s="",u=this.t,p=this.DB-u*this.DB%e;if(u-- >0)for(p<this.DB&&(r=this[u]>>p)>0&&(o=!0,s=Z(r));u>=0;)p<e?(r=(this[u]&(1<<p)-1)<<e-p,r|=this[--u]>>(p+=this.DB-e)):(r=this[u]>>(p-=e)&n,p<=0&&(p+=this.DB,--u)),r>0&&(o=!0),o&&(s+=Z(r));return o?s:"0"}function E(){var t=x();return c.ZERO.subTo(this,t),t}function R(){return this.s<0?this.negate():this}function Q(t){var e=this.s-t.s;if(e!=0)return e;var n=this.t;if(e=n-t.t,e!=0)return this.s<0?-e:e;for(;--n>=0;)if((e=this[n]-t[n])!=0)return e;return 0}function st(t){var e=1,n;return(n=t>>>16)!=0&&(t=n,e+=16),(n=t>>8)!=0&&(t=n,e+=8),(n=t>>4)!=0&&(t=n,e+=4),(n=t>>2)!=0&&(t=n,e+=2),(n=t>>1)!=0&&(t=n,e+=1),e}function mt(){return this.t<=0?0:this.DB*(this.t-1)+st(this[this.t-1]^this.s&this.DM)}function kt(t,e){var n;for(n=this.t-1;n>=0;--n)e[n+t]=this[n];for(n=t-1;n>=0;--n)e[n]=0;e.t=this.t+t,e.s=this.s}function _t(t,e){for(var n=t;n<this.t;++n)e[n-t]=this[n];e.t=Math.max(this.t-t,0),e.s=this.s}function yt(t,e){var n=t%this.DB,r=this.DB-n,o=(1<<r)-1,s=Math.floor(t/this.DB),u=this.s<<n&this.DM,p;for(p=this.t-1;p>=0;--p)e[p+s+1]=this[p]>>r|u,u=(this[p]&o)<<n;for(p=s-1;p>=0;--p)e[p]=0;e[s]=u,e.t=this.t+s+1,e.s=this.s,e.clamp()}function Ot(t,e){e.s=this.s;var n=Math.floor(t/this.DB);if(n>=this.t){e.t=0;return}var r=t%this.DB,o=this.DB-r,s=(1<<r)-1;e[0]=this[n]>>r;for(var u=n+1;u<this.t;++u)e[u-n-1]|=(this[u]&s)<<o,e[u-n]=this[u]>>r;r>0&&(e[this.t-n-1]|=(this.s&s)<<o),e.t=this.t-n,e.clamp()}function ee(t,e){for(var n=0,r=0,o=Math.min(t.t,this.t);n<o;)r+=this[n]-t[n],e[n++]=r&this.DM,r>>=this.DB;if(t.t<this.t){for(r-=t.s;n<this.t;)r+=this[n],e[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<t.t;)r-=t[n],e[n++]=r&this.DM,r>>=this.DB;r-=t.s}e.s=r<0?-1:0,r<-1?e[n++]=this.DV+r:r>0&&(e[n++]=r),e.t=n,e.clamp()}function ft(t,e){var n=this.abs(),r=t.abs(),o=n.t;for(e.t=o+r.t;--o>=0;)e[o]=0;for(o=0;o<r.t;++o)e[o+n.t]=n.am(0,r[o],e,o,0,n.t);e.s=0,e.clamp(),this.s!=t.s&&c.ZERO.subTo(e,e)}function me(t){for(var e=this.abs(),n=t.t=2*e.t;--n>=0;)t[n]=0;for(n=0;n<e.t-1;++n){var r=e.am(n,e[n],t,2*n,0,1);(t[n+e.t]+=e.am(n+1,2*e[n],t,2*n+1,r,e.t-n-1))>=e.DV&&(t[n+e.t]-=e.DV,t[n+e.t+1]=1)}t.t>0&&(t[t.t-1]+=e.am(n,e[n],t,2*n,0,1)),t.s=0,t.clamp()}function Qe(t,e,n){var r=t.abs();if(!(r.t<=0)){var o=this.abs();if(o.t<r.t){e?.fromInt(0),n!=null&&this.copyTo(n);return}n==null&&(n=x());var s=x(),u=this.s,p=t.s,d=this.DB-st(r[r.t-1]);d>0?(r.lShiftTo(d,s),o.lShiftTo(d,n)):(r.copyTo(s),o.copyTo(n));var P=s.t,w=s[P-1];if(w!=0){var C=w*(1<<this.F1)+(P>1?s[P-2]>>this.F2:0),S=this.FV/C,A=(1<<this.F1)/C,B=1<<this.F2,k=n.t,U=k-P,ut=e??x();for(s.dlShiftTo(U,ut),n.compareTo(ut)>=0&&(n[n.t++]=1,n.subTo(ut,n)),c.ONE.dlShiftTo(P,ut),ut.subTo(s,s);s.t<P;)s[s.t++]=0;for(;--U>=0;){var Ct=n[--k]==w?this.DM:Math.floor(n[k]*S+(n[k-1]+B)*A);if((n[k]+=s.am(0,Ct,n,U,0,P))<Ct)for(s.dlShiftTo(U,ut),n.subTo(ut,n);n[k]<--Ct;)n.subTo(ut,n)}e!=null&&(n.drShiftTo(P,e),u!=p&&c.ZERO.subTo(e,e)),n.t=P,n.clamp(),d>0&&n.rShiftTo(d,n),u<0&&c.ZERO.subTo(n,n)}}}function Si(t){var e=x();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(c.ZERO)>0&&t.subTo(e,e),e}function Ft(t){this.m=t}function Ti(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function bi(t){return t}function Li(t){t.divRemTo(this.m,null,t)}function Ei(t,e,n){t.multiplyTo(e,n),this.reduce(n)}function Ni(t,e){t.squareTo(e),this.reduce(e)}Ft.prototype.convert=Ti,Ft.prototype.revert=bi,Ft.prototype.reduce=Li,Ft.prototype.mulTo=Ei,Ft.prototype.sqrTo=Ni;function Oi(){if(this.t<1)return 0;var t=this[0];if((t&1)==0)return 0;var e=t&3;return e=e*(2-(t&15)*e)&15,e=e*(2-(t&255)*e)&255,e=e*(2-((t&65535)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function $t(t){this.m=t,this.mp=t.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t}function Xi(t){var e=x();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(c.ZERO)>0&&this.m.subTo(e,e),e}function Ai(t){var e=x();return t.copyTo(e),this.reduce(e),e}function Yi(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e<this.m.t;++e){var n=t[e]&32767,r=n*this.mpl+((n*this.mph+(t[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(n=e+this.m.t,t[n]+=this.m.am(0,r,t,e,0,this.m.t);t[n]>=t.DV;)t[n]-=t.DV,t[++n]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function Mi(t,e){t.squareTo(e),this.reduce(e)}function Bi(t,e,n){t.multiplyTo(e,n),this.reduce(n)}$t.prototype.convert=Xi,$t.prototype.revert=Ai,$t.prototype.reduce=Yi,$t.prototype.mulTo=Bi,$t.prototype.sqrTo=Mi;function Di(){return(this.t>0?this[0]&1:this.s)==0}function ki(t,e){if(t>4294967295||t<1)return c.ONE;var n=x(),r=x(),o=e.convert(this),s=st(t)-1;for(o.copyTo(n);--s>=0;)if(e.sqrTo(n,r),(t&1<<s)>0)e.mulTo(r,o,n);else{var u=n;n=r,r=u}return e.revert(n)}function Fi(t,e){var n;return t<256||e.isEven()?n=new Ft(e):n=new $t(e),this.exp(t,n)}c.prototype.copyTo=H,c.prototype.fromInt=F,c.prototype.fromString=G,c.prototype.clamp=et,c.prototype.dlShiftTo=kt,c.prototype.drShiftTo=_t,c.prototype.lShiftTo=yt,c.prototype.rShiftTo=Ot,c.prototype.subTo=ee,c.prototype.multiplyTo=ft,c.prototype.squareTo=me,c.prototype.divRemTo=Qe,c.prototype.invDigit=Oi,c.prototype.isEven=Di,c.prototype.exp=ki,c.prototype.toString=ct,c.prototype.negate=E,c.prototype.abs=R,c.prototype.compareTo=Q,c.prototype.bitLength=mt,c.prototype.mod=Si,c.prototype.modPowInt=Fi,c.ZERO=X(0),c.ONE=X(1);function $i(){var t=x();return this.copyTo(t),t}function Ri(){if(this.s<0){if(this.t==1)return this[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this[0];if(this.t==0)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function Wi(){return this.t==0?this.s:this[0]<<24>>24}function Ui(){return this.t==0?this.s:this[0]<<16>>16}function qi(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function Zi(){return this.s<0?-1:this.t<=0||this.t==1&&this[0]<=0?0:1}function Hi(t){if(t==null&&(t=10),this.signum()==0||t<2||t>36)return"0";var e=this.chunkSize(t),n=Math.pow(t,e),r=X(n),o=x(),s=x(),u="";for(this.divRemTo(r,o,s);o.signum()>0;)u=(n+s.intValue()).toString(t).substr(1)+u,o.divRemTo(r,o,s);return s.intValue().toString(t)+u}function ji(t,e){this.fromInt(0),e==null&&(e=10);for(var n=this.chunkSize(e),r=Math.pow(e,n),o=!1,s=0,u=0,p=0;p<t.length;++p){var d=ot(t,p);if(d<0){t.charAt(p)=="-"&&this.signum()==0&&(o=!0);continue}u=e*u+d,++s>=n&&(this.dMultiply(r),this.dAddOffset(u,0),s=0,u=0)}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(u,0)),o&&c.ZERO.subTo(this,this)}function Ji(t,e,n){if(typeof e=="number")if(t<2)this.fromInt(1);else for(this.fromNumber(t,n),this.testBit(t-1)||this.bitwiseTo(c.ONE.shiftLeft(t-1),Se,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(c.ONE.shiftLeft(t-1),this);else{var r=new Array,o=t&7;r.length=(t>>3)+1,e.nextBytes(r),o>0?r[0]&=(1<<o)-1:r[0]=0,this.fromString(r,256)}}function Gi(){var t=this.t,e=new Array;e[0]=this.s;var n=this.DB-t*this.DB%8,r,o=0;if(t-- >0)for(n<this.DB&&(r=this[t]>>n)!=(this.s&this.DM)>>n&&(e[o++]=r|this.s<<this.DB-n);t>=0;)n<8?(r=(this[t]&(1<<n)-1)<<8-n,r|=this[--t]>>(n+=this.DB-8)):(r=this[t]>>(n-=8)&255,n<=0&&(n+=this.DB,--t)),(r&128)!=0&&(r|=-256),o==0&&(this.s&128)!=(r&128)&&++o,(o>0||r!=this.s)&&(e[o++]=r);return e}function Vi(t){return this.compareTo(t)==0}function zi(t){return this.compareTo(t)<0?this:t}function Ki(t){return this.compareTo(t)>0?this:t}function Qi(t,e,n){var r,o,s=Math.min(t.t,this.t);for(r=0;r<s;++r)n[r]=e(this[r],t[r]);if(t.t<this.t){for(o=t.s&this.DM,r=s;r<this.t;++r)n[r]=e(this[r],o);n.t=this.t}else{for(o=this.s&this.DM,r=s;r<t.t;++r)n[r]=e(o,t[r]);n.t=t.t}n.s=e(this.s,t.s),n.clamp()}function tn(t,e){return t&e}function en(t){var e=x();return this.bitwiseTo(t,tn,e),e}function Se(t,e){return t|e}function nn(t){var e=x();return this.bitwiseTo(t,Se,e),e}function ti(t,e){return t^e}function rn(t){var e=x();return this.bitwiseTo(t,ti,e),e}function ei(t,e){return t&~e}function on(t){var e=x();return this.bitwiseTo(t,ei,e),e}function sn(){for(var t=x(),e=0;e<this.t;++e)t[e]=this.DM&~this[e];return t.t=this.t,t.s=~this.s,t}function ln(t){var e=x();return t<0?this.rShiftTo(-t,e):this.lShiftTo(t,e),e}function an(t){var e=x();return t<0?this.lShiftTo(-t,e):this.rShiftTo(t,e),e}function un(t){if(t==0)return-1;var e=0;return(t&65535)==0&&(t>>=16,e+=16),(t&255)==0&&(t>>=8,e+=8),(t&15)==0&&(t>>=4,e+=4),(t&3)==0&&(t>>=2,e+=2),(t&1)==0&&++e,e}function hn(){for(var t=0;t<this.t;++t)if(this[t]!=0)return t*this.DB+un(this[t]);return this.s<0?this.t*this.DB:-1}function fn(t){for(var e=0;t!=0;)t&=t-1,++e;return e}function pn(){for(var t=0,e=this.s&this.DM,n=0;n<this.t;++n)t+=fn(this[n]^e);return t}function dn(t){var e=Math.floor(t/this.DB);return e>=this.t?this.s!=0:(this[e]&1<<t%this.DB)!=0}function cn(t,e){var n=c.ONE.shiftLeft(t);return this.bitwiseTo(n,e,n),n}function mn(t){return this.changeBit(t,Se)}function yn(t){return this.changeBit(t,ei)}function vn(t){return this.changeBit(t,ti)}function Pn(t,e){for(var n=0,r=0,o=Math.min(t.t,this.t);n<o;)r+=this[n]+t[n],e[n++]=r&this.DM,r>>=this.DB;if(t.t<this.t){for(r+=t.s;n<this.t;)r+=this[n],e[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<t.t;)r+=t[n],e[n++]=r&this.DM,r>>=this.DB;r+=t.s}e.s=r<0?-1:0,r>0?e[n++]=r:r<-1&&(e[n++]=this.DV+r),e.t=n,e.clamp()}function gn(t){var e=x();return this.addTo(t,e),e}function xn(t){var e=x();return this.subTo(t,e),e}function Cn(t){var e=x();return this.multiplyTo(t,e),e}function wn(){var t=x();return this.squareTo(t),t}function In(t){var e=x();return this.divRemTo(t,e,null),e}function _n(t){var e=x();return this.divRemTo(t,null,e),e}function Sn(t){var e=x(),n=x();return this.divRemTo(t,e,n),new Array(e,n)}function Tn(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function bn(t,e){if(t!=0){for(;this.t<=e;)this[this.t++]=0;for(this[e]+=t;this[e]>=this.DV;)this[e]-=this.DV,++e>=this.t&&(this[this.t++]=0),++this[e]}}function ie(){}function ii(t){return t}function Ln(t,e,n){t.multiplyTo(e,n)}function En(t,e){t.squareTo(e)}ie.prototype.convert=ii,ie.prototype.revert=ii,ie.prototype.mulTo=Ln,ie.prototype.sqrTo=En;function Nn(t){return this.exp(t,new ie)}function On(t,e,n){var r=Math.min(this.t+t.t,e);for(n.s=0,n.t=r;r>0;)n[--r]=0;var o;for(o=n.t-this.t;r<o;++r)n[r+this.t]=this.am(0,t[r],n,r,0,this.t);for(o=Math.min(t.t,e);r<o;++r)this.am(0,t[r],n,r,0,e-r);n.clamp()}function Xn(t,e,n){--e;var r=n.t=this.t+t.t-e;for(n.s=0;--r>=0;)n[r]=0;for(r=Math.max(e-this.t,0);r<t.t;++r)n[this.t+r-e]=this.am(e-r,t[r],n,0,0,this.t+r-e);n.clamp(),n.drShiftTo(1,n)}function Ht(t){this.r2=x(),this.q3=x(),c.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}function An(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=x();return t.copyTo(e),this.reduce(e),e}function Yn(t){return t}function Mn(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function Bn(t,e){t.squareTo(e),this.reduce(e)}function Dn(t,e,n){t.multiplyTo(e,n),this.reduce(n)}Ht.prototype.convert=An,Ht.prototype.revert=Yn,Ht.prototype.reduce=Mn,Ht.prototype.mulTo=Dn,Ht.prototype.sqrTo=Bn;function kn(t,e){var n=t.bitLength(),r,o=X(1),s;if(n<=0)return o;n<18?r=1:n<48?r=3:n<144?r=4:n<768?r=5:r=6,n<8?s=new Ft(e):e.isEven()?s=new Ht(e):s=new $t(e);var u=new Array,p=3,d=r-1,P=(1<<r)-1;if(u[1]=s.convert(this),r>1){var w=x();for(s.sqrTo(u[1],w);p<=P;)u[p]=x(),s.mulTo(w,u[p-2],u[p]),p+=2}var C=t.t-1,S,A=!0,B=x(),k;for(n=st(t[C])-1;C>=0;){for(n>=d?S=t[C]>>n-d&P:(S=(t[C]&(1<<n+1)-1)<<d-n,C>0&&(S|=t[C-1]>>this.DB+n-d)),p=r;(S&1)==0;)S>>=1,--p;if((n-=p)<0&&(n+=this.DB,--C),A)u[S].copyTo(o),A=!1;else{for(;p>1;)s.sqrTo(o,B),s.sqrTo(B,o),p-=2;p>0?s.sqrTo(o,B):(k=o,o=B,B=k),s.mulTo(B,u[S],o)}for(;C>=0&&(t[C]&1<<n)==0;)s.sqrTo(o,B),k=o,o=B,B=k,--n<0&&(n=this.DB-1,--C)}return s.revert(o)}function Fn(t){var e=this.s<0?this.negate():this.clone(),n=t.s<0?t.negate():t.clone();if(e.compareTo(n)<0){var r=e;e=n,n=r}var o=e.getLowestSetBit(),s=n.getLowestSetBit();if(s<0)return e;for(o<s&&(s=o),s>0&&(e.rShiftTo(s,e),n.rShiftTo(s,n));e.signum()>0;)(o=e.getLowestSetBit())>0&&e.rShiftTo(o,e),(o=n.getLowestSetBit())>0&&n.rShiftTo(o,n),e.compareTo(n)>=0?(e.subTo(n,e),e.rShiftTo(1,e)):(n.subTo(e,n),n.rShiftTo(1,n));return s>0&&n.lShiftTo(s,n),n}function $n(t){if(t<=0)return 0;var e=this.DV%t,n=this.s<0?t-1:0;if(this.t>0)if(e==0)n=this[0]%t;else for(var r=this.t-1;r>=0;--r)n=(e*n+this[r])%t;return n}function Rn(t){var e=t.isEven();if(this.isEven()&&e||t.signum()==0)return c.ZERO;for(var n=t.clone(),r=this.clone(),o=X(1),s=X(0),u=X(0),p=X(1);n.signum()!=0;){for(;n.isEven();)n.rShiftTo(1,n),e?((!o.isEven()||!s.isEven())&&(o.addTo(this,o),s.subTo(t,s)),o.rShiftTo(1,o)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;r.isEven();)r.rShiftTo(1,r),e?((!u.isEven()||!p.isEven())&&(u.addTo(this,u),p.subTo(t,p)),u.rShiftTo(1,u)):p.isEven()||p.subTo(t,p),p.rShiftTo(1,p);n.compareTo(r)>=0?(n.subTo(r,n),e&&o.subTo(u,o),s.subTo(p,s)):(r.subTo(n,r),e&&u.subTo(o,u),p.subTo(s,p))}if(r.compareTo(c.ONE)!=0)return c.ZERO;if(p.compareTo(t)>=0)return p.subtract(t);if(p.signum()<0)p.addTo(t,p);else return p;return p.signum()<0?p.add(t):p}var lt=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],Wn=(1<<26)/lt[lt.length-1];function Un(t){var e,n=this.abs();if(n.t==1&&n[0]<=lt[lt.length-1]){for(e=0;e<lt.length;++e)if(n[0]==lt[e])return!0;return!1}if(n.isEven())return!1;for(e=1;e<lt.length;){for(var r=lt[e],o=e+1;o<lt.length&&r<Wn;)r*=lt[o++];for(r=n.modInt(r);e<o;)if(r%lt[e++]==0)return!1}return n.millerRabin(t)}function qn(t){var e=this.subtract(c.ONE),n=e.getLowestSetBit();if(n<=0)return!1;var r=e.shiftRight(n);t=t+1>>1,t>lt.length&&(t=lt.length);for(var o=x(),s=0;s<t;++s){o.fromInt(lt[Math.floor(Math.random()*lt.length)]);var u=o.modPow(r,this);if(u.compareTo(c.ONE)!=0&&u.compareTo(e)!=0){for(var p=1;p++<n&&u.compareTo(e)!=0;)if(u=u.modPowInt(2,this),u.compareTo(c.ONE)==0)return!1;if(u.compareTo(e)!=0)return!1}}return!0}c.prototype.chunkSize=qi,c.prototype.toRadix=Hi,c.prototype.fromRadix=ji,c.prototype.fromNumber=Ji,c.prototype.bitwiseTo=Qi,c.prototype.changeBit=cn,c.prototype.addTo=Pn,c.prototype.dMultiply=Tn,c.prototype.dAddOffset=bn,c.prototype.multiplyLowerTo=On,c.prototype.multiplyUpperTo=Xn,c.prototype.modInt=$n,c.prototype.millerRabin=qn,c.prototype.clone=$i,c.prototype.intValue=Ri,c.prototype.byteValue=Wi,c.prototype.shortValue=Ui,c.prototype.signum=Zi,c.prototype.toByteArray=Gi,c.prototype.equals=Vi,c.prototype.min=zi,c.prototype.max=Ki,c.prototype.and=en,c.prototype.or=nn,c.prototype.xor=rn,c.prototype.andNot=on,c.prototype.not=sn,c.prototype.shiftLeft=ln,c.prototype.shiftRight=an,c.prototype.getLowestSetBit=hn,c.prototype.bitCount=pn,c.prototype.testBit=dn,c.prototype.setBit=mn,c.prototype.clearBit=yn,c.prototype.flipBit=vn,c.prototype.add=gn,c.prototype.subtract=xn,c.prototype.multiply=Cn,c.prototype.divide=In,c.prototype.remainder=_n,c.prototype.divideAndRemainder=Sn,c.prototype.modPow=kn,c.prototype.modInverse=Rn,c.prototype.pow=Nn,c.prototype.gcd=Fn,c.prototype.isProbablePrime=Un,c.prototype.square=wn;var M=c;M.prototype.IsNegative=function(){return this.compareTo(M.ZERO)==-1},M.op_Equality=function(t,e){return t.compareTo(e)==0},M.op_Inequality=function(t,e){return t.compareTo(e)!=0},M.op_GreaterThan=function(t,e){return t.compareTo(e)>0},M.op_LessThan=function(t,e){return t.compareTo(e)<0},M.op_Addition=function(t,e){return new M(t,void 0,void 0).add(new M(e,void 0,void 0))},M.op_Subtraction=function(t,e){return new M(t,void 0,void 0).subtract(new M(e,void 0,void 0))},M.Int128Mul=function(t,e){return new M(t,void 0,void 0).multiply(new M(e,void 0,void 0))},M.op_Division=function(t,e){return t.divide(e)},M.prototype.ToDouble=function(){return parseFloat(this.toString())};var ni=function(t,e){var n;if(typeof Object.getOwnPropertyNames>"u"){for(n in e.prototype)(typeof t.prototype[n]>"u"||t.prototype[n]===Object.prototype[n])&&(t.prototype[n]=e.prototype[n]);for(n in e)typeof t[n]>"u"&&(t[n]=e[n]);t.$baseCtor=e}else{for(var r=Object.getOwnPropertyNames(e.prototype),o=0;o<r.length;o++)typeof Object.getOwnPropertyDescriptor(t.prototype,r[o])>"u"&&Object.defineProperty(t.prototype,r[o],Object.getOwnPropertyDescriptor(e.prototype,r[o]));for(n in e)typeof t[n]>"u"&&(t[n]=e[n]);t.$baseCtor=e}};i.Path=function(){return[]},i.Path.prototype.push=Array.prototype.push,i.Paths=function(){return[]},i.Paths.prototype.push=Array.prototype.push,i.DoublePoint=function(){var t=arguments;this.X=0,this.Y=0,t.length===1?(this.X=t[0].X,this.Y=t[0].Y):t.length===2&&(this.X=t[0],this.Y=t[1])},i.DoublePoint0=function(){this.X=0,this.Y=0},i.DoublePoint0.prototype=i.DoublePoint.prototype,i.DoublePoint1=function(t){this.X=t.X,this.Y=t.Y},i.DoublePoint1.prototype=i.DoublePoint.prototype,i.DoublePoint2=function(t,e){this.X=t,this.Y=e},i.DoublePoint2.prototype=i.DoublePoint.prototype,i.PolyNode=function(){this.m_Parent=null,this.m_polygon=new i.Path,this.m_Index=0,this.m_jointype=0,this.m_endtype=0,this.m_Childs=[],this.IsOpen=!1},i.PolyNode.prototype.IsHoleNode=function(){for(var t=!0,e=this.m_Parent;e!==null;)t=!t,e=e.m_Parent;return t},i.PolyNode.prototype.ChildCount=function(){return this.m_Childs.length},i.PolyNode.prototype.Contour=function(){return this.m_polygon},i.PolyNode.prototype.AddChild=function(t){var e=this.m_Childs.length;this.m_Childs.push(t),t.m_Parent=this,t.m_Index=e},i.PolyNode.prototype.GetNext=function(){return this.m_Childs.length>0?this.m_Childs[0]:this.GetNextSiblingUp()},i.PolyNode.prototype.GetNextSiblingUp=function(){return this.m_Parent===null?null:this.m_Index===this.m_Parent.m_Childs.length-1?this.m_Parent.GetNextSiblingUp():this.m_Parent.m_Childs[this.m_Index+1]},i.PolyNode.prototype.Childs=function(){return this.m_Childs},i.PolyNode.prototype.Parent=function(){return this.m_Parent},i.PolyNode.prototype.IsHole=function(){return this.IsHoleNode()},i.PolyTree=function(){this.m_AllPolys=[],i.PolyNode.call(this)},i.PolyTree.prototype.Clear=function(){for(var t=0,e=this.m_AllPolys.length;t<e;t++)this.m_AllPolys[t]=null;this.m_AllPolys.length=0,this.m_Childs.length=0},i.PolyTree.prototype.GetFirst=function(){return this.m_Childs.length>0?this.m_Childs[0]:null},i.PolyTree.prototype.Total=function(){var t=this.m_AllPolys.length;return t>0&&this.m_Childs[0]!==this.m_AllPolys[0]&&t--,t},ni(i.PolyTree,i.PolyNode),i.Math_Abs_Int64=i.Math_Abs_Int32=i.Math_Abs_Double=function(t){return Math.abs(t)},i.Math_Max_Int32_Int32=function(t,e){return Math.max(t,e)},f.msie||f.opera||f.safari?i.Cast_Int32=function(t){return t|0}:i.Cast_Int32=function(t){return~~t},typeof Number.toInteger>"u"&&(Number.toInteger=null),f.chrome?i.Cast_Int64=function(t){return t<-2147483648||t>2147483647?t<0?Math.ceil(t):Math.floor(t):~~t}:f.firefox&&typeof Number.toInteger=="function"?i.Cast_Int64=function(t){return Number.toInteger(t)}:f.msie7||f.msie8?i.Cast_Int64=function(t){return parseInt(t,10)}:f.msie?i.Cast_Int64=function(t){return t<-2147483648||t>2147483647?t<0?Math.ceil(t):Math.floor(t):t|0}:i.Cast_Int64=function(t){return t<0?Math.ceil(t):Math.floor(t)},i.Clear=function(t){t.length=0},i.PI=3.141592653589793,i.PI2=2*3.141592653589793,i.IntPoint=function(){var t=arguments,e=t.length;if(this.X=0,this.Y=0,i.use_xyz)if(this.Z=0,e===3)this.X=t[0],this.Y=t[1],this.Z=t[2];else if(e===2)this.X=t[0],this.Y=t[1],this.Z=0;else if(e===1)if(t[0]instanceof i.DoublePoint){var n=t[0];this.X=i.Clipper.Round(n.X),this.Y=i.Clipper.Round(n.Y),this.Z=0}else{var r=t[0];typeof r.Z>"u"&&(r.Z=0),this.X=r.X,this.Y=r.Y,this.Z=r.Z}else this.X=0,this.Y=0,this.Z=0;else if(e===2)this.X=t[0],this.Y=t[1];else if(e===1)if(t[0]instanceof i.DoublePoint){var n=t[0];this.X=i.Clipper.Round(n.X),this.Y=i.Clipper.Round(n.Y)}else{var r=t[0];this.X=r.X,this.Y=r.Y}else this.X=0,this.Y=0},i.IntPoint.op_Equality=function(t,e){return t.X===e.X&&t.Y===e.Y},i.IntPoint.op_Inequality=function(t,e){return t.X!==e.X||t.Y!==e.Y},i.IntPoint0=function(){this.X=0,this.Y=0,i.use_xyz&&(this.Z=0)},i.IntPoint0.prototype=i.IntPoint.prototype,i.IntPoint1=function(t){this.X=t.X,this.Y=t.Y,i.use_xyz&&(typeof t.Z>"u"?this.Z=0:this.Z=t.Z)},i.IntPoint1.prototype=i.IntPoint.prototype,i.IntPoint1dp=function(t){this.X=i.Clipper.Round(t.X),this.Y=i.Clipper.Round(t.Y),i.use_xyz&&(this.Z=0)},i.IntPoint1dp.prototype=i.IntPoint.prototype,i.IntPoint2=function(t,e,n){this.X=t,this.Y=e,i.use_xyz&&(typeof n>"u"?this.Z=0:this.Z=n)},i.IntPoint2.prototype=i.IntPoint.prototype,i.IntRect=function(){var t=arguments,e=t.length;if(e===4)this.left=t[0],this.top=t[1],this.right=t[2],this.bottom=t[3];else if(e===1){var n=t[0];this.left=n.left,this.top=n.top,this.right=n.right,this.bottom=n.bottom}else this.left=0,this.top=0,this.right=0,this.bottom=0},i.IntRect0=function(){this.left=0,this.top=0,this.right=0,this.bottom=0},i.IntRect0.prototype=i.IntRect.prototype,i.IntRect1=function(t){this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom},i.IntRect1.prototype=i.IntRect.prototype,i.IntRect4=function(t,e,n,r){this.left=t,this.top=e,this.right=n,this.bottom=r},i.IntRect4.prototype=i.IntRect.prototype,i.ClipType={ctIntersection:0,ctUnion:1,ctDifference:2,ctXor:3},i.PolyType={ptSubject:0,ptClip:1},i.PolyFillType={pftEvenOdd:0,pftNonZero:1,pftPositive:2,pftNegative:3},i.JoinType={jtSquare:0,jtRound:1,jtMiter:2},i.EndType={etOpenSquare:0,etOpenRound:1,etOpenButt:2,etClosedLine:3,etClosedPolygon:4},i.EdgeSide={esLeft:0,esRight:1},i.Direction={dRightToLeft:0,dLeftToRight:1},i.TEdge=function(){this.Bot=new i.IntPoint0,this.Curr=new i.IntPoint0,this.Top=new i.IntPoint0,this.Delta=new i.IntPoint0,this.Dx=0,this.PolyTyp=i.PolyType.ptSubject,this.Side=i.EdgeSide.esLeft,this.WindDelta=0,this.WindCnt=0,this.WindCnt2=0,this.OutIdx=0,this.Next=null,this.Prev=null,this.NextInLML=null,this.NextInAEL=null,this.PrevInAEL=null,this.NextInSEL=null,this.PrevInSEL=null},i.IntersectNode=function(){this.Edge1=null,this.Edge2=null,this.Pt=new i.IntPoint0},i.MyIntersectNodeSort=function(){},i.MyIntersectNodeSort.Compare=function(t,e){var n=e.Pt.Y-t.Pt.Y;return n>0?1:n<0?-1:0},i.LocalMinima=function(){this.Y=0,this.LeftBound=null,this.RightBound=null,this.Next=null},i.Scanbeam=function(){this.Y=0,this.Next=null},i.Maxima=function(){this.X=0,this.Next=null,this.Prev=null},i.OutRec=function(){this.Idx=0,this.IsHole=!1,this.IsOpen=!1,this.FirstLeft=null,this.Pts=null,this.BottomPt=null,this.PolyNode=null},i.OutPt=function(){this.Idx=0,this.Pt=new i.IntPoint0,this.Next=null,this.Prev=null},i.Join=function(){this.OutPt1=null,this.OutPt2=null,this.OffPt=new i.IntPoint0},i.ClipperBase=function(){this.m_MinimaList=null,this.m_CurrentLM=null,this.m_edges=new Array,this.m_UseFullRange=!1,this.m_HasOpenPaths=!1,this.PreserveCollinear=!1,this.m_Scanbeam=null,this.m_PolyOuts=null,this.m_ActiveEdges=null},i.ClipperBase.horizontal=-9007199254740992,i.ClipperBase.Skip=-2,i.ClipperBase.Unassigned=-1,i.ClipperBase.tolerance=1e-20,i.ClipperBase.loRange=47453132,i.ClipperBase.hiRange=0xfffffffffffff,i.ClipperBase.near_zero=function(t){return t>-i.ClipperBase.tolerance&&t<i.ClipperBase.tolerance},i.ClipperBase.IsHorizontal=function(t){return t.Delta.Y===0},i.ClipperBase.prototype.PointIsVertex=function(t,e){var n=e;do{if(i.IntPoint.op_Equality(n.Pt,t))return!0;n=n.Next}while(n!==e);return!1},i.ClipperBase.prototype.PointOnLineSegment=function(t,e,n,r){return r?t.X===e.X&&t.Y===e.Y||t.X===n.X&&t.Y===n.Y||t.X>e.X==t.X<n.X&&t.Y>e.Y==t.Y<n.Y&&M.op_Equality(M.Int128Mul(t.X-e.X,n.Y-e.Y),M.Int128Mul(n.X-e.X,t.Y-e.Y)):t.X===e.X&&t.Y===e.Y||t.X===n.X&&t.Y===n.Y||t.X>e.X==t.X<n.X&&t.Y>e.Y==t.Y<n.Y&&(t.X-e.X)*(n.Y-e.Y)===(n.X-e.X)*(t.Y-e.Y)},i.ClipperBase.prototype.PointOnPolygon=function(t,e,n){for(var r=e;;){if(this.PointOnLineSegment(t,r.Pt,r.Next.Pt,n))return!0;if(r=r.Next,r===e)break}return!1},i.ClipperBase.prototype.SlopesEqual=i.ClipperBase.SlopesEqual=function(){var t=arguments,e=t.length,n,r,o,s,u,p,d;return e===3?(n=t[0],r=t[1],d=t[2],d?M.op_Equality(M.Int128Mul(n.Delta.Y,r.Delta.X),M.Int128Mul(n.Delta.X,r.Delta.Y)):i.Cast_Int64(n.Delta.Y*r.Delta.X)===i.Cast_Int64(n.Delta.X*r.Delta.Y)):e===4?(o=t[0],s=t[1],u=t[2],d=t[3],d?M.op_Equality(M.Int128Mul(o.Y-s.Y,s.X-u.X),M.Int128Mul(o.X-s.X,s.Y-u.Y)):i.Cast_Int64((o.Y-s.Y)*(s.X-u.X))-i.Cast_Int64((o.X-s.X)*(s.Y-u.Y))===0):(o=t[0],s=t[1],u=t[2],p=t[3],d=t[4],d?M.op_Equality(M.Int128Mul(o.Y-s.Y,u.X-p.X),M.Int128Mul(o.X-s.X,u.Y-p.Y)):i.Cast_Int64((o.Y-s.Y)*(u.X-p.X))-i.Cast_Int64((o.X-s.X)*(u.Y-p.Y))===0)},i.ClipperBase.SlopesEqual3=function(t,e,n){return n?M.op_Equality(M.Int128Mul(t.Delta.Y,e.Delta.X),M.Int128Mul(t.Delta.X,e.Delta.Y)):i.Cast_Int64(t.Delta.Y*e.Delta.X)===i.Cast_Int64(t.Delta.X*e.Delta.Y)},i.ClipperBase.SlopesEqual4=function(t,e,n,r){return r?M.op_Equality(M.Int128Mul(t.Y-e.Y,e.X-n.X),M.Int128Mul(t.X-e.X,e.Y-n.Y)):i.Cast_Int64((t.Y-e.Y)*(e.X-n.X))-i.Cast_Int64((t.X-e.X)*(e.Y-n.Y))===0},i.ClipperBase.SlopesEqual5=function(t,e,n,r,o){return o?M.op_Equality(M.Int128Mul(t.Y-e.Y,n.X-r.X),M.Int128Mul(t.X-e.X,n.Y-r.Y)):i.Cast_Int64((t.Y-e.Y)*(n.X-r.X))-i.Cast_Int64((t.X-e.X)*(n.Y-r.Y))===0},i.ClipperBase.prototype.Clear=function(){this.DisposeLocalMinimaList();for(var t=0,e=this.m_edges.length;t<e;++t){for(var n=0,r=this.m_edges[t].length;n<r;++n)this.m_edges[t][n]=null;i.Clear(this.m_edges[t])}i.Clear(this.m_edges),this.m_UseFullRange=!1,this.m_HasOpenPaths=!1},i.ClipperBase.prototype.DisposeLocalMinimaList=function(){for(;this.m_MinimaList!==null;){var t=this.m_MinimaList.Next;this.m_MinimaList=null,this.m_MinimaList=t}this.m_CurrentLM=null},i.ClipperBase.prototype.RangeTest=function(t,e){e.Value?(t.X>i.ClipperBase.hiRange||t.Y>i.ClipperBase.hiRange||-t.X>i.ClipperBase.hiRange||-t.Y>i.ClipperBase.hiRange)&&i.Error("Coordinate outside allowed range in RangeTest()."):(t.X>i.ClipperBase.loRange||t.Y>i.ClipperBase.loRange||-t.X>i.ClipperBase.loRange||-t.Y>i.ClipperBase.loRange)&&(e.Value=!0,this.RangeTest(t,e))},i.ClipperBase.prototype.InitEdge=function(t,e,n,r){t.Next=e,t.Prev=n,t.Curr.X=r.X,t.Curr.Y=r.Y,i.use_xyz&&(t.Curr.Z=r.Z),t.OutIdx=-1},i.ClipperBase.prototype.InitEdge2=function(t,e){t.Curr.Y>=t.Next.Curr.Y?(t.Bot.X=t.Curr.X,t.Bot.Y=t.Curr.Y,i.use_xyz&&(t.Bot.Z=t.Curr.Z),t.Top.X=t.Next.Curr.X,t.Top.Y=t.Next.Curr.Y,i.use_xyz&&(t.Top.Z=t.Next.Curr.Z)):(t.Top.X=t.Curr.X,t.Top.Y=t.Curr.Y,i.use_xyz&&(t.Top.Z=t.Curr.Z),t.Bot.X=t.Next.Curr.X,t.Bot.Y=t.Next.Curr.Y,i.use_xyz&&(t.Bot.Z=t.Next.Curr.Z)),this.SetDx(t),t.PolyTyp=e},i.ClipperBase.prototype.FindNextLocMin=function(t){for(var e;;){for(;i.IntPoint.op_Inequality(t.Bot,t.Prev.Bot)||i.IntPoint.op_Equality(t.Curr,t.Top);)t=t.Next;if(t.Dx!==i.ClipperBase.horizontal&&t.Prev.Dx!==i.ClipperBase.horizontal)break;for(;t.Prev.Dx===i.ClipperBase.horizontal;)t=t.Prev;for(e=t;t.Dx===i.ClipperBase.horizontal;)t=t.Next;if(t.Top.Y!==t.Prev.Bot.Y){e.Prev.Bot.X<t.Bot.X&&(t=e);break}}return t},i.ClipperBase.prototype.ProcessBound=function(t,e){var n,r=t,o;if(r.OutIdx===i.ClipperBase.Skip){if(t=r,e){for(;t.Top.Y===t.Next.Bot.Y;)t=t.Next;for(;t!==r&&t.Dx===i.ClipperBase.horizontal;)t=t.Prev}else{for(;t.Top.Y===t.Prev.Bot.Y;)t=t.Prev;for(;t!==r&&t.Dx===i.ClipperBase.horizontal;)t=t.Next}if(t===r)e?r=t.Next:r=t.Prev;else{e?t=r.Next:t=r.Prev;var s=new i.LocalMinima;s.Next=null,s.Y=t.Bot.Y,s.LeftBound=null,s.RightBound=t,t.WindDelta=0,r=this.ProcessBound(t,e),this.InsertLocalMinima(s)}return r}if(t.Dx===i.ClipperBase.horizontal&&(e?n=t.Prev:n=t.Next,n.Dx===i.ClipperBase.horizontal?n.Bot.X!==t.Bot.X&&n.Top.X!==t.Bot.X&&this.ReverseHorizontal(t):n.Bot.X!==t.Bot.X&&this.ReverseHorizontal(t)),n=t,e){for(;r.Top.Y===r.Next.Bot.Y&&r.Next.OutIdx!==i.ClipperBase.Skip;)r=r.Next;if(r.Dx===i.ClipperBase.horizontal&&r.Next.OutIdx!==i.ClipperBase.Skip){for(o=r;o.Prev.Dx===i.ClipperBase.horizontal;)o=o.Prev;o.Prev.Top.X>r.Next.Top.X&&(r=o.Prev)}for(;t!==r;)t.NextInLML=t.Next,t.Dx===i.ClipperBase.horizontal&&t!==n&&t.Bot.X!==t.Prev.Top.X&&this.ReverseHorizontal(t),t=t.Next;t.Dx===i.ClipperBase.horizontal&&t!==n&&t.Bot.X!==t.Prev.Top.X&&this.ReverseHorizontal(t),r=r.Next}else{for(;r.Top.Y===r.Prev.Bot.Y&&r.Prev.OutIdx!==i.ClipperBase.Skip;)r=r.Prev;if(r.Dx===i.ClipperBase.horizontal&&r.Prev.OutIdx!==i.ClipperBase.Skip){for(o=r;o.Next.Dx===i.ClipperBase.horizontal;)o=o.Next;(o.Next.Top.X===r.Prev.Top.X||o.Next.Top.X>r.Prev.Top.X)&&(r=o.Next)}for(;t!==r;)t.NextInLML=t.Prev,t.Dx===i.ClipperBase.horizontal&&t!==n&&t.Bot.X!==t.Next.Top.X&&this.ReverseHorizontal(t),t=t.Prev;t.Dx===i.ClipperBase.horizontal&&t!==n&&t.Bot.X!==t.Next.Top.X&&this.ReverseHorizontal(t),r=r.Prev}return r},i.ClipperBase.prototype.AddPath=function(t,e,n){i.use_lines?!n&&e===i.PolyType.ptClip&&i.Error("AddPath: Open paths must be subject."):n||i.Error("AddPath: Open paths have been disabled.");var r=t.length-1;if(n)for(;r>0&&i.IntPoint.op_Equality(t[r],t[0]);)--r;for(;r>0&&i.IntPoint.op_Equality(t[r],t[r-1]);)--r;if(n&&r<2||!n&&r<1)return!1;for(var o=new Array,s=0;s<=r;s++)o.push(new i.TEdge);var u=!0;o[1].Curr.X=t[1].X,o[1].Curr.Y=t[1].Y,i.use_xyz&&(o[1].Curr.Z=t[1].Z);var p={Value:this.m_UseFullRange};this.RangeTest(t[0],p),this.m_UseFullRange=p.Value,p.Value=this.m_UseFullRange,this.RangeTest(t[r],p),this.m_UseFullRange=p.Value,this.InitEdge(o[0],o[1],o[r],t[0]),this.InitEdge(o[r],o[0],o[r-1],t[r]);for(var s=r-1;s>=1;--s)p.Value=this.m_UseFullRange,this.RangeTest(t[s],p),this.m_UseFullRange=p.Value,this.InitEdge(o[s],o[s+1],o[s-1],t[s]);for(var d=o[0],P=d,w=d;;){if(P.Curr===P.Next.Curr&&(n||P.Next!==d)){if(P===P.Next)break;P===d&&(d=P.Next),P=this.RemoveEdge(P),w=P;continue}if(P.Prev===P.Next)break;if(n&&i.ClipperBase.SlopesEqual4(P.Prev.Curr,P.Curr,P.Next.Curr,this.m_UseFullRange)&&(!this.PreserveCollinear||!this.Pt2IsBetweenPt1AndPt3(P.Prev.Curr,P.Curr,P.Next.Curr))){P===d&&(d=P.Next),P=this.RemoveEdge(P),P=P.Prev,w=P;continue}if(P=P.Next,P===w||!n&&P.Next===d)break}if(!n&&P===P.Next||n&&P.Prev===P.Next)return!1;n||(this.m_HasOpenPaths=!0,d.Prev.OutIdx=i.ClipperBase.Skip),P=d;do this.InitEdge2(P,e),P=P.Next,u&&P.Curr.Y!==d.Curr.Y&&(u=!1);while(P!==d);if(u){if(n)return!1;P.Prev.OutIdx=i.ClipperBase.Skip;var C=new i.LocalMinima;for(C.Next=null,C.Y=P.Bot.Y,C.LeftBound=null,C.RightBound=P,C.RightBound.Side=i.EdgeSide.esRight,C.RightBound.WindDelta=0;P.Bot.X!==P.Prev.Top.X&&this.ReverseHorizontal(P),P.Next.OutIdx!==i.ClipperBase.Skip;)P.NextInLML=P.Next,P=P.Next;return this.InsertLocalMinima(C),this.m_edges.push(o),!0}this.m_edges.push(o);var S,A=null;for(i.IntPoint.op_Equality(P.Prev.Bot,P.Prev.Top)&&(P=P.Next);P=this.FindNextLocMin(P),P!==A;){A===null&&(A=P);var C=new i.LocalMinima;C.Next=null,C.Y=P.Bot.Y,P.Dx<P.Prev.Dx?(C.LeftBound=P.Prev,C.RightBound=P,S=!1):(C.LeftBound=P,C.RightBound=P.Prev,S=!0),C.LeftBound.Side=i.EdgeSide.esLeft,C.RightBound.Side=i.EdgeSide.esRight,n?C.LeftBound.Next===C.RightBound?C.LeftBound.WindDelta=-1:C.LeftBound.WindDelta=1:C.LeftBound.WindDelta=0,C.RightBound.WindDelta=-C.LeftBound.WindDelta,P=this.ProcessBound(C.LeftBound,S),P.OutIdx===i.ClipperBase.Skip&&(P=this.ProcessBound(P,S));var B=this.ProcessBound(C.RightBound,!S);B.OutIdx===i.ClipperBase.Skip&&(B=this.ProcessBound(B,!S)),C.LeftBound.OutIdx===i.ClipperBase.Skip?C.LeftBound=null:C.RightBound.OutIdx===i.ClipperBase.Skip&&(C.RightBound=null),this.InsertLocalMinima(C),S||(P=B)}return!0},i.ClipperBase.prototype.AddPaths=function(t,e,n){for(var r=!1,o=0,s=t.length;o<s;++o)this.AddPath(t[o],e,n)&&(r=!0);return r},i.ClipperBase.prototype.Pt2IsBetweenPt1AndPt3=function(t,e,n){return i.IntPoint.op_Equality(t,n)||i.IntPoint.op_Equality(t,e)||i.IntPoint.op_Equality(n,e)?!1:t.X!==n.X?e.X>t.X==e.X<n.X:e.Y>t.Y==e.Y<n.Y},i.ClipperBase.prototype.RemoveEdge=function(t){t.Prev.Next=t.Next,t.Next.Prev=t.Prev;var e=t.Next;return t.Prev=null,e},i.ClipperBase.prototype.SetDx=function(t){t.Delta.X=t.Top.X-t.Bot.X,t.Delta.Y=t.Top.Y-t.Bot.Y,t.Delta.Y===0?t.Dx=i.ClipperBase.horizontal:t.Dx=t.Delta.X/t.Delta.Y},i.ClipperBase.prototype.InsertLocalMinima=function(t){if(this.m_MinimaList===null)this.m_MinimaList=t;else if(t.Y>=this.m_MinimaList.Y)t.Next=this.m_MinimaList,this.m_MinimaList=t;else{for(var e=this.m_MinimaList;e.Next!==null&&t.Y<e.Next.Y;)e=e.Next;t.Next=e.Next,e.Next=t}},i.ClipperBase.prototype.PopLocalMinima=function(t,e){return e.v=this.m_CurrentLM,this.m_CurrentLM!==null&&this.m_CurrentLM.Y===t?(this.m_CurrentLM=this.m_CurrentLM.Next,!0):!1},i.ClipperBase.prototype.ReverseHorizontal=function(t){var e=t.Top.X;t.Top.X=t.Bot.X,t.Bot.X=e,i.use_xyz&&(e=t.Top.Z,t.Top.Z=t.Bot.Z,t.Bot.Z=e)},i.ClipperBase.prototype.Reset=function(){if(this.m_CurrentLM=this.m_MinimaList,this.m_CurrentLM!==null){this.m_Scanbeam=null;for(var t=this.m_MinimaList;t!==null;){this.InsertScanbeam(t.Y);var e=t.LeftBound;e!==null&&(e.Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,i.use_xyz&&(e.Curr.Z=e.Bot.Z),e.OutIdx=i.ClipperBase.Unassigned),e=t.RightBound,e!==null&&(e.Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,i.use_xyz&&(e.Curr.Z=e.Bot.Z),e.OutIdx=i.ClipperBase.Unassigned),t=t.Next}this.m_ActiveEdges=null}},i.ClipperBase.prototype.InsertScanbeam=function(t){if(this.m_Scanbeam===null)this.m_Scanbeam=new i.Scanbeam,this.m_Scanbeam.Next=null,this.m_Scanbeam.Y=t;else if(t>this.m_Scanbeam.Y){var e=new i.Scanbeam;e.Y=t,e.Next=this.m_Scanbeam,this.m_Scanbeam=e}else{for(var n=this.m_Scanbeam;n.Next!==null&&t<=n.Next.Y;)n=n.Next;if(t===n.Y)return;var r=new i.Scanbeam;r.Y=t,r.Next=n.Next,n.Next=r}},i.ClipperBase.prototype.PopScanbeam=function(t){return this.m_Scanbeam===null?(t.v=0,!1):(t.v=this.m_Scanbeam.Y,this.m_Scanbeam=this.m_Scanbeam.Next,!0)},i.ClipperBase.prototype.LocalMinimaPending=function(){return this.m_CurrentLM!==null},i.ClipperBase.prototype.CreateOutRec=function(){var t=new i.OutRec;return t.Idx=i.ClipperBase.Unassigned,t.IsHole=!1,t.IsOpen=!1,t.FirstLeft=null,t.Pts=null,t.BottomPt=null,t.PolyNode=null,this.m_PolyOuts.push(t),t.Idx=this.m_PolyOuts.length-1,t},i.ClipperBase.prototype.DisposeOutRec=function(t){var e=this.m_PolyOuts[t];e.Pts=null,e=null,this.m_PolyOuts[t]=null},i.ClipperBase.prototype.UpdateEdgeIntoAEL=function(t){t.NextInLML===null&&i.Error("UpdateEdgeIntoAEL: invalid call");var e=t.PrevInAEL,n=t.NextInAEL;return t.NextInLML.OutIdx=t.OutIdx,e!==null?e.NextInAEL=t.NextInLML:this.m_ActiveEdges=t.NextInLML,n!==null&&(n.PrevInAEL=t.NextInLML),t.NextInLML.Side=t.Side,t.NextInLML.WindDelta=t.WindDelta,t.NextInLML.WindCnt=t.WindCnt,t.NextInLML.WindCnt2=t.WindCnt2,t=t.NextInLML,t.Curr.X=t.Bot.X,t.Curr.Y=t.Bot.Y,t.PrevInAEL=e,t.NextInAEL=n,i.ClipperBase.IsHorizontal(t)||this.InsertScanbeam(t.Top.Y),t},i.ClipperBase.prototype.SwapPositionsInAEL=function(t,e){if(!(t.NextInAEL===t.PrevInAEL||e.NextInAEL===e.PrevInAEL)){if(t.NextInAEL===e){var n=e.NextInAEL;n!==null&&(n.PrevInAEL=t);var r=t.PrevInAEL;r!==null&&(r.NextInAEL=e),e.PrevInAEL=r,e.NextInAEL=t,t.PrevInAEL=e,t.NextInAEL=n}else if(e.NextInAEL===t){var o=t.NextInAEL;o!==null&&(o.PrevInAEL=e);var s=e.PrevInAEL;s!==null&&(s.NextInAEL=t),t.PrevInAEL=s,t.NextInAEL=e,e.PrevInAEL=t,e.NextInAEL=o}else{var u=t.NextInAEL,p=t.PrevInAEL;t.NextInAEL=e.NextInAEL,t.NextInAEL!==null&&(t.NextInAEL.PrevInAEL=t),t.PrevInAEL=e.PrevInAEL,t.PrevInAEL!==null&&(t.PrevInAEL.NextInAEL=t),e.NextInAEL=u,e.NextInAEL!==null&&(e.NextInAEL.PrevInAEL=e),e.PrevInAEL=p,e.PrevInAEL!==null&&(e.PrevInAEL.NextInAEL=e)}t.PrevInAEL===null?this.m_ActiveEdges=t:e.PrevInAEL===null&&(this.m_ActiveEdges=e)}},i.ClipperBase.prototype.DeleteFromAEL=function(t){var e=t.PrevInAEL,n=t.NextInAEL;e===null&&n===null&&t!==this.m_ActiveEdges||(e!==null?e.NextInAEL=n:this.m_ActiveEdges=n,n!==null&&(n.PrevInAEL=e),t.NextInAEL=null,t.PrevInAEL=null)},i.Clipper=function(t){typeof t>"u"&&(t=0),this.m_PolyOuts=null,this.m_ClipType=i.ClipType.ctIntersection,this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=null,this.m_IntersectNodeComparer=null,this.m_ExecuteLocked=!1,this.m_ClipFillType=i.PolyFillType.pftEvenOdd,this.m_SubjFillType=i.PolyFillType.pftEvenOdd,this.m_Joins=null,this.m_GhostJoins=null,this.m_UsingPolyTree=!1,this.ReverseSolution=!1,this.StrictlySimple=!1,i.ClipperBase.call(this),this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=new Array,this.m_IntersectNodeComparer=i.MyIntersectNodeSort.Compare,this.m_ExecuteLocked=!1,this.m_UsingPolyTree=!1,this.m_PolyOuts=new Array,this.m_Joins=new Array,this.m_GhostJoins=new Array,this.ReverseSolution=(1&t)!==0,this.StrictlySimple=(2&t)!==0,this.PreserveCollinear=(4&t)!==0,i.use_xyz&&(this.ZFillFunction=null)},i.Clipper.ioReverseSolution=1,i.Clipper.ioStrictlySimple=2,i.Clipper.ioPreserveCollinear=4,i.Clipper.prototype.Clear=function(){this.m_edges.length!==0&&(this.DisposeAllPolyPts(),i.ClipperBase.prototype.Clear.call(this))},i.Clipper.prototype.InsertMaxima=function(t){var e=new i.Maxima;if(e.X=t,this.m_Maxima===null)this.m_Maxima=e,this.m_Maxima.Next=null,this.m_Maxima.Prev=null;else if(t<this.m_Maxima.X)e.Next=this.m_Maxima,e.Prev=null,this.m_Maxima=e;else{for(var n=this.m_Maxima;n.Next!==null&&t>=n.Next.X;)n=n.Next;if(t===n.X)return;e.Next=n.Next,e.Prev=n,n.Next!==null&&(n.Next.Prev=e),n.Next=e}},i.Clipper.prototype.Execute=function(){var t=arguments,e=t.length,n=t[1]instanceof i.PolyTree;if(e===4&&!n){var r=t[0],o=t[1],s=t[2],u=t[3];if(this.m_ExecuteLocked)return!1;this.m_HasOpenPaths&&i.Error("Error: PolyTree struct is needed for open path clipping."),this.m_ExecuteLocked=!0,i.Clear(o),this.m_SubjFillType=s,this.m_ClipFillType=u,this.m_ClipType=r,this.m_UsingPolyTree=!1;try{var p=this.ExecuteInternal();p&&this.BuildResult(o)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return p}else if(e===4&&n){var r=t[0],d=t[1],s=t[2],u=t[3];if(this.m_ExecuteLocked)return!1;this.m_ExecuteLocked=!0,this.m_SubjFillType=s,this.m_ClipFillType=u,this.m_ClipType=r,this.m_UsingPolyTree=!0;try{var p=this.ExecuteInternal();p&&this.BuildResult2(d)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return p}else if(e===2&&!n){var r=t[0],o=t[1];return this.Execute(r,o,i.PolyFillType.pftEvenOdd,i.PolyFillType.pftEvenOdd)}else if(e===2&&n){var r=t[0],d=t[1];return this.Execute(r,d,i.PolyFillType.pftEvenOdd,i.PolyFillType.pftEvenOdd)}},i.Clipper.prototype.FixHoleLinkage=function(t){if(!(t.FirstLeft===null||t.IsHole!==t.FirstLeft.IsHole&&t.FirstLeft.Pts!==null)){for(var e=t.FirstLeft;e!==null&&(e.IsHole===t.IsHole||e.Pts===null);)e=e.FirstLeft;t.FirstLeft=e}},i.Clipper.prototype.ExecuteInternal=function(){try{this.Reset(),this.m_SortedEdges=null,this.m_Maxima=null;var t={},e={};if(!this.PopScanbeam(t))return!1;for(this.InsertLocalMinimaIntoAEL(t.v);this.PopScanbeam(e)||this.LocalMinimaPending();){if(this.ProcessHorizontals(),this.m_GhostJoins.length=0,!this.ProcessIntersections(e.v))return!1;this.ProcessEdgesAtTopOfScanbeam(e.v),t.v=e.v,this.InsertLocalMinimaIntoAEL(t.v)}var n,r,o;for(r=0,o=this.m_PolyOuts.length;r<o;r++)n=this.m_PolyOuts[r],!(n.Pts===null||n.IsOpen)&&(n.IsHole^this.ReverseSolution)==this.Area$1(n)>0&&this.ReversePolyPtLinks(n.Pts);for(this.JoinCommonEdges(),r=0,o=this.m_PolyOuts.length;r<o;r++)n=this.m_PolyOuts[r],n.Pts!==null&&(n.IsOpen?this.FixupOutPolyline(n):this.FixupOutPolygon(n));return this.StrictlySimple&&this.DoSimplePolygons(),!0}finally{this.m_Joins.length=0,this.m_GhostJoins.length=0}},i.Clipper.prototype.DisposeAllPolyPts=function(){for(var t=0,e=this.m_PolyOuts.length;t<e;++t)this.DisposeOutRec(t);i.Clear(this.m_PolyOuts)},i.Clipper.prototype.AddJoin=function(t,e,n){var r=new i.Join;r.OutPt1=t,r.OutPt2=e,r.OffPt.X=n.X,r.OffPt.Y=n.Y,i.use_xyz&&(r.OffPt.Z=n.Z),this.m_Joins.push(r)},i.Clipper.prototype.AddGhostJoin=function(t,e){var n=new i.Join;n.OutPt1=t,n.OffPt.X=e.X,n.OffPt.Y=e.Y,i.use_xyz&&(n.OffPt.Z=e.Z),this.m_GhostJoins.push(n)},i.Clipper.prototype.SetZ=function(t,e,n){if(this.ZFillFunction!==null){if(t.Z!==0||this.ZFillFunction===null)return;i.IntPoint.op_Equality(t,e.Bot)?t.Z=e.Bot.Z:i.IntPoint.op_Equality(t,e.Top)?t.Z=e.Top.Z:i.IntPoint.op_Equality(t,n.Bot)?t.Z=n.Bot.Z:i.IntPoint.op_Equality(t,n.Top)?t.Z=n.Top.Z:this.ZFillFunction(e.Bot,e.Top,n.Bot,n.Top,t)}},i.Clipper.prototype.InsertLocalMinimaIntoAEL=function(t){for(var e={},n,r;this.PopLocalMinima(t,e);){n=e.v.LeftBound,r=e.v.RightBound;var o=null;if(n===null?(this.InsertEdgeIntoAEL(r,null),this.SetWindingCount(r),this.IsContributing(r)&&(o=this.AddOutPt(r,r.Bot))):r===null?(this.InsertEdgeIntoAEL(n,null),this.SetWindingCount(n),this.IsContributing(n)&&(o=this.AddOutPt(n,n.Bot)),this.InsertScanbeam(n.Top.Y)):(this.InsertEdgeIntoAEL(n,null),this.InsertEdgeIntoAEL(r,n),this.SetWindingCount(n),r.WindCnt=n.WindCnt,r.WindCnt2=n.WindCnt2,this.IsContributing(n)&&(o=this.AddLocalMinPoly(n,r,n.Bot)),this.InsertScanbeam(n.Top.Y)),r!==null&&(i.ClipperBase.IsHorizontal(r)?(r.NextInLML!==null&&this.InsertScanbeam(r.NextInLML.Top.Y),this.AddEdgeToSEL(r)):this.InsertScanbeam(r.Top.Y)),!(n===null||r===null)){if(o!==null&&i.ClipperBase.IsHorizontal(r)&&this.m_GhostJoins.length>0&&r.WindDelta!==0)for(var s=0,u=this.m_GhostJoins.length;s<u;s++){var p=this.m_GhostJoins[s];this.HorzSegmentsOverlap(p.OutPt1.Pt.X,p.OffPt.X,r.Bot.X,r.Top.X)&&this.AddJoin(p.OutPt1,o,p.OffPt)}if(n.OutIdx>=0&&n.PrevInAEL!==null&&n.PrevInAEL.Curr.X===n.Bot.X&&n.PrevInAEL.OutIdx>=0&&i.ClipperBase.SlopesEqual5(n.PrevInAEL.Curr,n.PrevInAEL.Top,n.Curr,n.Top,this.m_UseFullRange)&&n.WindDelta!==0&&n.PrevInAEL.WindDelta!==0){var d=this.AddOutPt(n.PrevInAEL,n.Bot);this.AddJoin(o,d,n.Top)}if(n.NextInAEL!==r){if(r.OutIdx>=0&&r.PrevInAEL.OutIdx>=0&&i.ClipperBase.SlopesEqual5(r.PrevInAEL.Curr,r.PrevInAEL.Top,r.Curr,r.Top,this.m_UseFullRange)&&r.WindDelta!==0&&r.PrevInAEL.WindDelta!==0){var d=this.AddOutPt(r.PrevInAEL,r.Bot);this.AddJoin(o,d,r.Top)}var P=n.NextInAEL;if(P!==null)for(;P!==r;)this.IntersectEdges(r,P,n.Curr),P=P.NextInAEL}}}},i.Clipper.prototype.InsertEdgeIntoAEL=function(t,e){if(this.m_ActiveEdges===null)t.PrevInAEL=null,t.NextInAEL=null,this.m_ActiveEdges=t;else if(e===null&&this.E2InsertsBeforeE1(this.m_ActiveEdges,t))t.PrevInAEL=null,t.NextInAEL=this.m_ActiveEdges,this.m_ActiveEdges.PrevInAEL=t,this.m_ActiveEdges=t;else{for(e===null&&(e=this.m_ActiveEdges);e.NextInAEL!==null&&!this.E2InsertsBeforeE1(e.NextInAEL,t);)e=e.NextInAEL;t.NextInAEL=e.NextInAEL,e.NextInAEL!==null&&(e.NextInAEL.PrevInAEL=t),t.PrevInAEL=e,e.NextInAEL=t}},i.Clipper.prototype.E2InsertsBeforeE1=function(t,e){return e.Curr.X===t.Curr.X?e.Top.Y>t.Top.Y?e.Top.X<i.Clipper.TopX(t,e.Top.Y):t.Top.X>i.Clipper.TopX(e,t.Top.Y):e.Curr.X<t.Curr.X},i.Clipper.prototype.IsEvenOddFillType=function(t){return t.PolyTyp===i.PolyType.ptSubject?this.m_SubjFillType===i.PolyFillType.pftEvenOdd:this.m_ClipFillType===i.PolyFillType.pftEvenOdd},i.Clipper.prototype.IsEvenOddAltFillType=function(t){return t.PolyTyp===i.PolyType.ptSubject?this.m_ClipFillType===i.PolyFillType.pftEvenOdd:this.m_SubjFillType===i.PolyFillType.pftEvenOdd},i.Clipper.prototype.IsContributing=function(t){var e,n;switch(t.PolyTyp===i.PolyType.ptSubject?(e=this.m_SubjFillType,n=this.m_ClipFillType):(e=this.m_ClipFillType,n=this.m_SubjFillType),e){case i.PolyFillType.pftEvenOdd:if(t.WindDelta===0&&t.WindCnt!==1)return!1;break;case i.PolyFillType.pftNonZero:if(Math.abs(t.WindCnt)!==1)return!1;break;case i.PolyFillType.pftPositive:if(t.WindCnt!==1)return!1;break;default:if(t.WindCnt!==-1)return!1;break}switch(this.m_ClipType){case i.ClipType.ctIntersection:switch(n){case i.PolyFillType.pftEvenOdd:case i.PolyFillType.pftNonZero:return t.WindCnt2!==0;case i.PolyFillType.pftPositive:return t.WindCnt2>0;default:return t.WindCnt2<0}case i.ClipType.ctUnion:switch(n){case i.PolyFillType.pftEvenOdd:case i.PolyFillType.pftNonZero:return t.WindCnt2===0;case i.PolyFillType.pftPositive:return t.WindCnt2<=0;default:return t.WindCnt2>=0}case i.ClipType.ctDifference:if(t.PolyTyp===i.PolyType.ptSubject)switch(n){case i.PolyFillType.pftEvenOdd:case i.PolyFillType.pftNonZero:return t.WindCnt2===0;case i.PolyFillType.pftPositive:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else switch(n){case i.PolyFillType.pftEvenOdd:case i.PolyFillType.pftNonZero:return t.WindCnt2!==0;case i.PolyFillType.pftPositive:return t.WindCnt2>0;default:return t.WindCnt2<0}case i.ClipType.ctXor:if(t.WindDelta===0)switch(n){case i.PolyFillType.pftEvenOdd:case i.PolyFillType.pftNonZero:return t.WindCnt2===0;case i.PolyFillType.pftPositive:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else return!0}return!0},i.Clipper.prototype.SetWindingCount=function(t){for(var e=t.PrevInAEL;e!==null&&(e.PolyTyp!==t.PolyTyp||e.WindDelta===0);)e=e.PrevInAEL;if(e===null){var n=t.PolyTyp===i.PolyType.ptSubject?this.m_SubjFillType:this.m_ClipFillType;t.WindDelta===0?t.WindCnt=n===i.PolyFillType.pftNegative?-1:1:t.WindCnt=t.WindDelta,t.WindCnt2=0,e=this.m_ActiveEdges}else if(t.WindDelta===0&&this.m_ClipType!==i.ClipType.ctUnion)t.WindCnt=1,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;else if(this.IsEvenOddFillType(t)){if(t.WindDelta===0){for(var r=!0,o=e.PrevInAEL;o!==null;)o.PolyTyp===e.PolyTyp&&o.WindDelta!==0&&(r=!r),o=o.PrevInAEL;t.WindCnt=r?0:1}else t.WindCnt=t.WindDelta;t.WindCnt2=e.WindCnt2,e=e.NextInAEL}else e.WindCnt*e.WindDelta<0?Math.abs(e.WindCnt)>1?e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta:t.WindCnt=t.WindDelta===0?1:t.WindDelta:t.WindDelta===0?t.WindCnt=e.WindCnt<0?e.WindCnt-1:e.WindCnt+1:e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;if(this.IsEvenOddAltFillType(t))for(;e!==t;)e.WindDelta!==0&&(t.WindCnt2=t.WindCnt2===0?1:0),e=e.NextInAEL;else for(;e!==t;)t.WindCnt2+=e.WindDelta,e=e.NextInAEL},i.Clipper.prototype.AddEdgeToSEL=function(t){this.m_SortedEdges===null?(this.m_SortedEdges=t,t.PrevInSEL=null,t.NextInSEL=null):(t.NextInSEL=this.m_SortedEdges,t.PrevInSEL=null,this.m_SortedEdges.PrevInSEL=t,this.m_SortedEdges=t)},i.Clipper.prototype.PopEdgeFromSEL=function(t){if(t.v=this.m_SortedEdges,t.v===null)return!1;var e=t.v;return this.m_SortedEdges=t.v.NextInSEL,this.m_SortedEdges!==null&&(this.m_SortedEdges.PrevInSEL=null),e.NextInSEL=null,e.PrevInSEL=null,!0},i.Clipper.prototype.CopyAELToSEL=function(){var t=this.m_ActiveEdges;for(this.m_SortedEdges=t;t!==null;)t.PrevInSEL=t.PrevInAEL,t.NextInSEL=t.NextInAEL,t=t.NextInAEL},i.Clipper.prototype.SwapPositionsInSEL=function(t,e){if(!(t.NextInSEL===null&&t.PrevInSEL===null)&&!(e.NextInSEL===null&&e.PrevInSEL===null)){if(t.NextInSEL===e){var n=e.NextInSEL;n!==null&&(n.PrevInSEL=t);var r=t.PrevInSEL;r!==null&&(r.NextInSEL=e),e.PrevInSEL=r,e.NextInSEL=t,t.PrevInSEL=e,t.NextInSEL=n}else if(e.NextInSEL===t){var n=t.NextInSEL;n!==null&&(n.PrevInSEL=e);var r=e.PrevInSEL;r!==null&&(r.NextInSEL=t),t.PrevInSEL=r,t.NextInSEL=e,e.PrevInSEL=t,e.NextInSEL=n}else{var n=t.NextInSEL,r=t.PrevInSEL;t.NextInSEL=e.NextInSEL,t.NextInSEL!==null&&(t.NextInSEL.PrevInSEL=t),t.PrevInSEL=e.PrevInSEL,t.PrevInSEL!==null&&(t.PrevInSEL.NextInSEL=t),e.NextInSEL=n,e.NextInSEL!==null&&(e.NextInSEL.PrevInSEL=e),e.PrevInSEL=r,e.PrevInSEL!==null&&(e.PrevInSEL.NextInSEL=e)}t.PrevInSEL===null?this.m_SortedEdges=t:e.PrevInSEL===null&&(this.m_SortedEdges=e)}},i.Clipper.prototype.AddLocalMaxPoly=function(t,e,n){this.AddOutPt(t,n),e.WindDelta===0&&this.AddOutPt(e,n),t.OutIdx===e.OutIdx?(t.OutIdx=-1,e.OutIdx=-1):t.OutIdx<e.OutIdx?this.AppendPolygon(t,e):this.AppendPolygon(e,t)},i.Clipper.prototype.AddLocalMinPoly=function(t,e,n){var r,o,s;if(i.ClipperBase.IsHorizontal(e)||t.Dx>e.Dx?(r=this.AddOutPt(t,n),e.OutIdx=t.OutIdx,t.Side=i.EdgeSide.esLeft,e.Side=i.EdgeSide.esRight,o=t,o.PrevInAEL===e?s=e.PrevInAEL:s=o.PrevInAEL):(r=this.AddOutPt(e,n),t.OutIdx=e.OutIdx,t.Side=i.EdgeSide.esRight,e.Side=i.EdgeSide.esLeft,o=e,o.PrevInAEL===t?s=t.PrevInAEL:s=o.PrevInAEL),s!==null&&s.OutIdx>=0&&s.Top.Y<n.Y&&o.Top.Y<n.Y){var u=i.Clipper.TopX(s,n.Y),p=i.Clipper.TopX(o,n.Y);if(u===p&&o.WindDelta!==0&&s.WindDelta!==0&&i.ClipperBase.SlopesEqual5(new i.IntPoint2(u,n.Y),s.Top,new i.IntPoint2(p,n.Y),o.Top,this.m_UseFullRange)){var d=this.AddOutPt(s,n);this.AddJoin(r,d,o.Top)}}return r},i.Clipper.prototype.AddOutPt=function(t,e){if(t.OutIdx<0){var n=this.CreateOutRec();n.IsOpen=t.WindDelta===0;var r=new i.OutPt;return n.Pts=r,r.Idx=n.Idx,r.Pt.X=e.X,r.Pt.Y=e.Y,i.use_xyz&&(r.Pt.Z=e.Z),r.Next=r,r.Prev=r,n.IsOpen||this.SetHoleState(t,n),t.OutIdx=n.Idx,r}else{var n=this.m_PolyOuts[t.OutIdx],o=n.Pts,s=t.Side===i.EdgeSide.esLeft;if(s&&i.IntPoint.op_Equality(e,o.Pt))return o;if(!s&&i.IntPoint.op_Equality(e,o.Prev.Pt))return o.Prev;var r=new i.OutPt;return r.Idx=n.Idx,r.Pt.X=e.X,r.Pt.Y=e.Y,i.use_xyz&&(r.Pt.Z=e.Z),r.Next=o,r.Prev=o.Prev,r.Prev.Next=r,o.Prev=r,s&&(n.Pts=r),r}},i.Clipper.prototype.GetLastOutPt=function(t){var e=this.m_PolyOuts[t.OutIdx];return t.Side===i.EdgeSide.esLeft?e.Pts:e.Pts.Prev},i.Clipper.prototype.SwapPoints=function(t,e){var n=new i.IntPoint1(t.Value);t.Value.X=e.Value.X,t.Value.Y=e.Value.Y,i.use_xyz&&(t.Value.Z=e.Value.Z),e.Value.X=n.X,e.Value.Y=n.Y,i.use_xyz&&(e.Value.Z=n.Z)},i.Clipper.prototype.HorzSegmentsOverlap=function(t,e,n,r){var o;return t>e&&(o=t,t=e,e=o),n>r&&(o=n,n=r,r=o),t<r&&n<e},i.Clipper.prototype.SetHoleState=function(t,e){for(var n=t.PrevInAEL,r=null;n!==null;)n.OutIdx>=0&&n.WindDelta!==0&&(r===null?r=n:r.OutIdx===n.OutIdx&&(r=null)),n=n.PrevInAEL;r===null?(e.FirstLeft=null,e.IsHole=!1):(e.FirstLeft=this.m_PolyOuts[r.OutIdx],e.IsHole=!e.FirstLeft.IsHole)},i.Clipper.prototype.GetDx=function(t,e){return t.Y===e.Y?i.ClipperBase.horizontal:(e.X-t.X)/(e.Y-t.Y)},i.Clipper.prototype.FirstIsBottomPt=function(t,e){for(var n=t.Prev;i.IntPoint.op_Equality(n.Pt,t.Pt)&&n!==t;)n=n.Prev;var r=Math.abs(this.GetDx(t.Pt,n.Pt));for(n=t.Next;i.IntPoint.op_Equality(n.Pt,t.Pt)&&n!==t;)n=n.Next;var o=Math.abs(this.GetDx(t.Pt,n.Pt));for(n=e.Prev;i.IntPoint.op_Equality(n.Pt,e.Pt)&&n!==e;)n=n.Prev;var s=Math.abs(this.GetDx(e.Pt,n.Pt));for(n=e.Next;i.IntPoint.op_Equality(n.Pt,e.Pt)&&n!==e;)n=n.Next;var u=Math.abs(this.GetDx(e.Pt,n.Pt));return Math.max(r,o)===Math.max(s,u)&&Math.min(r,o)===Math.min(s,u)?this.Area(t)>0:r>=s&&r>=u||o>=s&&o>=u},i.Clipper.prototype.GetBottomPt=function(t){for(var e=null,n=t.Next;n!==t;)n.Pt.Y>t.Pt.Y?(t=n,e=null):n.Pt.Y===t.Pt.Y&&n.Pt.X<=t.Pt.X&&(n.Pt.X<t.Pt.X?(e=null,t=n):n.Next!==t&&n.Prev!==t&&(e=n)),n=n.Next;if(e!==null)for(;e!==n;)for(this.FirstIsBottomPt(n,e)||(t=e),e=e.Next;i.IntPoint.op_Inequality(e.Pt,t.Pt);)e=e.Next;return t},i.Clipper.prototype.GetLowermostRec=function(t,e){t.BottomPt===null&&(t.BottomPt=this.GetBottomPt(t.Pts)),e.BottomPt===null&&(e.BottomPt=this.GetBottomPt(e.Pts));var n=t.BottomPt,r=e.BottomPt;return n.Pt.Y>r.Pt.Y?t:n.Pt.Y<r.Pt.Y?e:n.Pt.X<r.Pt.X?t:n.Pt.X>r.Pt.X||n.Next===n?e:r.Next===r||this.FirstIsBottomPt(n,r)?t:e},i.Clipper.prototype.OutRec1RightOfOutRec2=function(t,e){do if(t=t.FirstLeft,t===e)return!0;while(t!==null);return!1},i.Clipper.prototype.GetOutRec=function(t){for(var e=this.m_PolyOuts[t];e!==this.m_PolyOuts[e.Idx];)e=this.m_PolyOuts[e.Idx];return e},i.Clipper.prototype.AppendPolygon=function(t,e){var n=this.m_PolyOuts[t.OutIdx],r=this.m_PolyOuts[e.OutIdx],o;this.OutRec1RightOfOutRec2(n,r)?o=r:this.OutRec1RightOfOutRec2(r,n)?o=n:o=this.GetLowermostRec(n,r);var s=n.Pts,u=s.Prev,p=r.Pts,d=p.Prev;t.Side===i.EdgeSide.esLeft?e.Side===i.EdgeSide.esLeft?(this.ReversePolyPtLinks(p),p.Next=s,s.Prev=p,u.Next=d,d.Prev=u,n.Pts=d):(d.Next=s,s.Prev=d,p.Prev=u,u.Next=p,n.Pts=p):e.Side===i.EdgeSide.esRight?(this.ReversePolyPtLinks(p),u.Next=d,d.Prev=u,p.Next=s,s.Prev=p):(u.Next=p,p.Prev=u,s.Prev=d,d.Next=s),n.BottomPt=null,o===r&&(r.FirstLeft!==n&&(n.FirstLeft=r.FirstLeft),n.IsHole=r.IsHole),r.Pts=null,r.BottomPt=null,r.FirstLeft=n;var P=t.OutIdx,w=e.OutIdx;t.OutIdx=-1,e.OutIdx=-1;for(var C=this.m_ActiveEdges;C!==null;){if(C.OutIdx===w){C.OutIdx=P,C.Side=t.Side;break}C=C.NextInAEL}r.Idx=n.Idx},i.Clipper.prototype.ReversePolyPtLinks=function(t){if(t!==null){var e,n;e=t;do n=e.Next,e.Next=e.Prev,e.Prev=n,e=n;while(e!==t)}},i.Clipper.SwapSides=function(t,e){var n=t.Side;t.Side=e.Side,e.Side=n},i.Clipper.SwapPolyIndexes=function(t,e){var n=t.OutIdx;t.OutIdx=e.OutIdx,e.OutIdx=n},i.Clipper.prototype.IntersectEdges=function(t,e,n){var r=t.OutIdx>=0,o=e.OutIdx>=0;if(i.use_xyz&&this.SetZ(n,t,e),i.use_lines&&(t.WindDelta===0||e.WindDelta===0)){if(t.WindDelta===0&&e.WindDelta===0)return;t.PolyTyp===e.PolyTyp&&t.WindDelta!==e.WindDelta&&this.m_ClipType===i.ClipType.ctUnion?t.WindDelta===0?o&&(this.AddOutPt(t,n),r&&(t.OutIdx=-1)):r&&(this.AddOutPt(e,n),o&&(e.OutIdx=-1)):t.PolyTyp!==e.PolyTyp&&(t.WindDelta===0&&Math.abs(e.WindCnt)===1&&(this.m_ClipType!==i.ClipType.ctUnion||e.WindCnt2===0)?(this.AddOutPt(t,n),r&&(t.OutIdx=-1)):e.WindDelta===0&&Math.abs(t.WindCnt)===1&&(this.m_ClipType!==i.ClipType.ctUnion||t.WindCnt2===0)&&(this.AddOutPt(e,n),o&&(e.OutIdx=-1)));return}if(t.PolyTyp===e.PolyTyp)if(this.IsEvenOddFillType(t)){var s=t.WindCnt;t.WindCnt=e.WindCnt,e.WindCnt=s}else t.WindCnt+e.WindDelta===0?t.WindCnt=-t.WindCnt:t.WindCnt+=e.WindDelta,e.WindCnt-t.WindDelta===0?e.WindCnt=-e.WindCnt:e.WindCnt-=t.WindDelta;else this.IsEvenOddFillType(e)?t.WindCnt2=t.WindCnt2===0?1:0:t.WindCnt2+=e.WindDelta,this.IsEvenOddFillType(t)?e.WindCnt2=e.WindCnt2===0?1:0:e.WindCnt2-=t.WindDelta;var u,p,d,P;t.PolyTyp===i.PolyType.ptSubject?(u=this.m_SubjFillType,d=this.m_ClipFillType):(u=this.m_ClipFillType,d=this.m_SubjFillType),e.PolyTyp===i.PolyType.ptSubject?(p=this.m_SubjFillType,P=this.m_ClipFillType):(p=this.m_ClipFillType,P=this.m_SubjFillType);var w,C;switch(u){case i.PolyFillType.pftPositive:w=t.WindCnt;break;case i.PolyFillType.pftNegative:w=-t.WindCnt;break;default:w=Math.abs(t.WindCnt);break}switch(p){case i.PolyFillType.pftPositive:C=e.WindCnt;break;case i.PolyFillType.pftNegative:C=-e.WindCnt;break;default:C=Math.abs(e.WindCnt);break}if(r&&o)w!==0&&w!==1||C!==0&&C!==1||t.PolyTyp!==e.PolyTyp&&this.m_ClipType!==i.ClipType.ctXor?this.AddLocalMaxPoly(t,e,n):(this.AddOutPt(t,n),this.AddOutPt(e,n),i.Clipper.SwapSides(t,e),i.Clipper.SwapPolyIndexes(t,e));else if(r)(C===0||C===1)&&(this.AddOutPt(t,n),i.Clipper.SwapSides(t,e),i.Clipper.SwapPolyIndexes(t,e));else if(o)(w===0||w===1)&&(this.AddOutPt(e,n),i.Clipper.SwapSides(t,e),i.Clipper.SwapPolyIndexes(t,e));else if((w===0||w===1)&&(C===0||C===1)){var S,A;switch(d){case i.PolyFillType.pftPositive:S=t.WindCnt2;break;case i.PolyFillType.pftNegative:S=-t.WindCnt2;break;default:S=Math.abs(t.WindCnt2);break}switch(P){case i.PolyFillType.pftPositive:A=e.WindCnt2;break;case i.PolyFillType.pftNegative:A=-e.WindCnt2;break;default:A=Math.abs(e.WindCnt2);break}if(t.PolyTyp!==e.PolyTyp)this.AddLocalMinPoly(t,e,n);else if(w===1&&C===1)switch(this.m_ClipType){case i.ClipType.ctIntersection:S>0&&A>0&&this.AddLocalMinPoly(t,e,n);break;case i.ClipType.ctUnion:S<=0&&A<=0&&this.AddLocalMinPoly(t,e,n);break;case i.ClipType.ctDifference:(t.PolyTyp===i.PolyType.ptClip&&S>0&&A>0||t.PolyTyp===i.PolyType.ptSubject&&S<=0&&A<=0)&&this.AddLocalMinPoly(t,e,n);break;case i.ClipType.ctXor:this.AddLocalMinPoly(t,e,n);break}else i.Clipper.SwapSides(t,e)}},i.Clipper.prototype.DeleteFromSEL=function(t){var e=t.PrevInSEL,n=t.NextInSEL;e===null&&n===null&&t!==this.m_SortedEdges||(e!==null?e.NextInSEL=n:this.m_SortedEdges=n,n!==null&&(n.PrevInSEL=e),t.NextInSEL=null,t.PrevInSEL=null)},i.Clipper.prototype.ProcessHorizontals=function(){for(var t={};this.PopEdgeFromSEL(t);)this.ProcessHorizontal(t.v)},i.Clipper.prototype.GetHorzDirection=function(t,e){t.Bot.X<t.Top.X?(e.Left=t.Bot.X,e.Right=t.Top.X,e.Dir=i.Direction.dLeftToRight):(e.Left=t.Top.X,e.Right=t.Bot.X,e.Dir=i.Direction.dRightToLeft)},i.Clipper.prototype.ProcessHorizontal=function(t){var e={Dir:null,Left:null,Right:null};this.GetHorzDirection(t,e);for(var n=e.Dir,r=e.Left,o=e.Right,s=t.WindDelta===0,u=t,p=null;u.NextInLML!==null&&i.ClipperBase.IsHorizontal(u.NextInLML);)u=u.NextInLML;u.NextInLML===null&&(p=this.GetMaximaPair(u));var d=this.m_Maxima;if(d!==null)if(n===i.Direction.dLeftToRight){for(;d!==null&&d.X<=t.Bot.X;)d=d.Next;d!==null&&d.X>=u.Top.X&&(d=null)}else{for(;d.Next!==null&&d.Next.X<t.Bot.X;)d=d.Next;d.X<=u.Top.X&&(d=null)}for(var P=null;;){for(var w=t===u,C=this.GetNextInAEL(t,n);C!==null;){if(d!==null)if(n===i.Direction.dLeftToRight)for(;d!==null&&d.X<C.Curr.X;)t.OutIdx>=0&&!s&&this.AddOutPt(t,new i.IntPoint2(d.X,t.Bot.Y)),d=d.Next;else for(;d!==null&&d.X>C.Curr.X;)t.OutIdx>=0&&!s&&this.AddOutPt(t,new i.IntPoint2(d.X,t.Bot.Y)),d=d.Prev;if(n===i.Direction.dLeftToRight&&C.Curr.X>o||n===i.Direction.dRightToLeft&&C.Curr.X<r||C.Curr.X===t.Top.X&&t.NextInLML!==null&&C.Dx<t.NextInLML.Dx)break;if(t.OutIdx>=0&&!s){i.use_xyz&&(n===i.Direction.dLeftToRight?this.SetZ(C.Curr,t,C):this.SetZ(C.Curr,C,t)),P=this.AddOutPt(t,C.Curr);for(var S=this.m_SortedEdges;S!==null;){if(S.OutIdx>=0&&this.HorzSegmentsOverlap(t.Bot.X,t.Top.X,S.Bot.X,S.Top.X)){var A=this.GetLastOutPt(S);this.AddJoin(A,P,S.Top)}S=S.NextInSEL}this.AddGhostJoin(P,t.Bot)}if(C===p&&w){t.OutIdx>=0&&this.AddLocalMaxPoly(t,p,t.Top),this.DeleteFromAEL(t),this.DeleteFromAEL(p);return}if(n===i.Direction.dLeftToRight){var B=new i.IntPoint2(C.Curr.X,t.Curr.Y);this.IntersectEdges(t,C,B)}else{var B=new i.IntPoint2(C.Curr.X,t.Curr.Y);this.IntersectEdges(C,t,B)}var k=this.GetNextInAEL(C,n);this.SwapPositionsInAEL(t,C),C=k}if(t.NextInLML===null||!i.ClipperBase.IsHorizontal(t.NextInLML))break;t=this.UpdateEdgeIntoAEL(t),t.OutIdx>=0&&this.AddOutPt(t,t.Bot),e={Dir:n,Left:r,Right:o},this.GetHorzDirection(t,e),n=e.Dir,r=e.Left,o=e.Right}if(t.OutIdx>=0&&P===null){P=this.GetLastOutPt(t);for(var S=this.m_SortedEdges;S!==null;){if(S.OutIdx>=0&&this.HorzSegmentsOverlap(t.Bot.X,t.Top.X,S.Bot.X,S.Top.X)){var A=this.GetLastOutPt(S);this.AddJoin(A,P,S.Top)}S=S.NextInSEL}this.AddGhostJoin(P,t.Top)}if(t.NextInLML!==null)if(t.OutIdx>=0){if(P=this.AddOutPt(t,t.Top),t=this.UpdateEdgeIntoAEL(t),t.WindDelta===0)return;var U=t.PrevInAEL,k=t.NextInAEL;if(U!==null&&U.Curr.X===t.Bot.X&&U.Curr.Y===t.Bot.Y&&U.WindDelta===0&&U.OutIdx>=0&&U.Curr.Y>U.Top.Y&&i.ClipperBase.SlopesEqual3(t,U,this.m_UseFullRange)){var A=this.AddOutPt(U,t.Bot);this.AddJoin(P,A,t.Top)}else if(k!==null&&k.Curr.X===t.Bot.X&&k.Curr.Y===t.Bot.Y&&k.WindDelta!==0&&k.OutIdx>=0&&k.Curr.Y>k.Top.Y&&i.ClipperBase.SlopesEqual3(t,k,this.m_UseFullRange)){var A=this.AddOutPt(k,t.Bot);this.AddJoin(P,A,t.Top)}}else t=this.UpdateEdgeIntoAEL(t);else t.OutIdx>=0&&this.AddOutPt(t,t.Top),this.DeleteFromAEL(t)},i.Clipper.prototype.GetNextInAEL=function(t,e){return e===i.Direction.dLeftToRight?t.NextInAEL:t.PrevInAEL},i.Clipper.prototype.IsMinima=function(t){return t!==null&&t.Prev.NextInLML!==t&&t.Next.NextInLML!==t},i.Clipper.prototype.IsMaxima=function(t,e){return t!==null&&t.Top.Y===e&&t.NextInLML===null},i.Clipper.prototype.IsIntermediate=function(t,e){return t.Top.Y===e&&t.NextInLML!==null},i.Clipper.prototype.GetMaximaPair=function(t){return i.IntPoint.op_Equality(t.Next.Top,t.Top)&&t.Next.NextInLML===null?t.Next:i.IntPoint.op_Equality(t.Prev.Top,t.Top)&&t.Prev.NextInLML===null?t.Prev:null},i.Clipper.prototype.GetMaximaPairEx=function(t){var e=this.GetMaximaPair(t);return e===null||e.OutIdx===i.ClipperBase.Skip||e.NextInAEL===e.PrevInAEL&&!i.ClipperBase.IsHorizontal(e)?null:e},i.Clipper.prototype.ProcessIntersections=function(t){if(this.m_ActiveEdges===null)return!0;try{if(this.BuildIntersectList(t),this.m_IntersectList.length===0)return!0;if(this.m_IntersectList.length===1||this.FixupIntersectionOrder())this.ProcessIntersectList();else return!1}catch{this.m_SortedEdges=null,this.m_IntersectList.length=0,i.Error("ProcessIntersections error")}return this.m_SortedEdges=null,!0},i.Clipper.prototype.BuildIntersectList=function(t){if(this.m_ActiveEdges!==null){var e=this.m_ActiveEdges;for(this.m_SortedEdges=e;e!==null;)e.PrevInSEL=e.PrevInAEL,e.NextInSEL=e.NextInAEL,e.Curr.X=i.Clipper.TopX(e,t),e=e.NextInAEL;for(var n=!0;n&&this.m_SortedEdges!==null;){for(n=!1,e=this.m_SortedEdges;e.NextInSEL!==null;){var r=e.NextInSEL,o=new i.IntPoint0;if(e.Curr.X>r.Curr.X){this.IntersectPoint(e,r,o),o.Y<t&&(o=new i.IntPoint2(i.Clipper.TopX(e,t),t));var s=new i.IntersectNode;s.Edge1=e,s.Edge2=r,s.Pt.X=o.X,s.Pt.Y=o.Y,i.use_xyz&&(s.Pt.Z=o.Z),this.m_IntersectList.push(s),this.SwapPositionsInSEL(e,r),n=!0}else e=r}if(e.PrevInSEL!==null)e.PrevInSEL.NextInSEL=null;else break}this.m_SortedEdges=null}},i.Clipper.prototype.EdgesAdjacent=function(t){return t.Edge1.NextInSEL===t.Edge2||t.Edge1.PrevInSEL===t.Edge2},i.Clipper.IntersectNodeSort=function(t,e){return e.Pt.Y-t.Pt.Y},i.Clipper.prototype.FixupIntersectionOrder=function(){this.m_IntersectList.sort(this.m_IntersectNodeComparer),this.CopyAELToSEL();for(var t=this.m_IntersectList.length,e=0;e<t;e++){if(!this.EdgesAdjacent(this.m_IntersectList[e])){for(var n=e+1;n<t&&!this.EdgesAdjacent(this.m_IntersectList[n]);)n++;if(n===t)return!1;var r=this.m_IntersectList[e];this.m_IntersectList[e]=this.m_IntersectList[n],this.m_IntersectList[n]=r}this.SwapPositionsInSEL(this.m_IntersectList[e].Edge1,this.m_IntersectList[e].Edge2)}return!0},i.Clipper.prototype.ProcessIntersectList=function(){for(var t=0,e=this.m_IntersectList.length;t<e;t++){var n=this.m_IntersectList[t];this.IntersectEdges(n.Edge1,n.Edge2,n.Pt),this.SwapPositionsInAEL(n.Edge1,n.Edge2)}this.m_IntersectList.length=0};var Zn=function(t){return t<0?Math.ceil(t-.5):Math.round(t)},Hn=function(t){return t<0?Math.ceil(t-.5):Math.floor(t+.5)},jn=function(t){return t<0?-Math.round(Math.abs(t)):Math.round(t)},Jn=function(t){return t<0?(t-=.5,t<-2147483648?Math.ceil(t):t|0):(t+=.5,t>2147483647?Math.floor(t):t|0)};f.msie?i.Clipper.Round=Zn:f.chromium?i.Clipper.Round=jn:f.safari?i.Clipper.Round=Jn:i.Clipper.Round=Hn,i.Clipper.TopX=function(t,e){return e===t.Top.Y?t.Top.X:t.Bot.X+i.Clipper.Round(t.Dx*(e-t.Bot.Y))},i.Clipper.prototype.IntersectPoint=function(t,e,n){n.X=0,n.Y=0;var r,o;if(t.Dx===e.Dx){n.Y=t.Curr.Y,n.X=i.Clipper.TopX(t,n.Y);return}if(t.Delta.X===0)n.X=t.Bot.X,i.ClipperBase.IsHorizontal(e)?n.Y=e.Bot.Y:(o=e.Bot.Y-e.Bot.X/e.Dx,n.Y=i.Clipper.Round(n.X/e.Dx+o));else if(e.Delta.X===0)n.X=e.Bot.X,i.ClipperBase.IsHorizontal(t)?n.Y=t.Bot.Y:(r=t.Bot.Y-t.Bot.X/t.Dx,n.Y=i.Clipper.Round(n.X/t.Dx+r));else{r=t.Bot.X-t.Bot.Y*t.Dx,o=e.Bot.X-e.Bot.Y*e.Dx;var s=(o-r)/(t.Dx-e.Dx);n.Y=i.Clipper.Round(s),Math.abs(t.Dx)<Math.abs(e.Dx)?n.X=i.Clipper.Round(t.Dx*s+r):n.X=i.Clipper.Round(e.Dx*s+o)}if(n.Y<t.Top.Y||n.Y<e.Top.Y){if(t.Top.Y>e.Top.Y)return n.Y=t.Top.Y,n.X=i.Clipper.TopX(e,t.Top.Y),n.X<t.Top.X;n.Y=e.Top.Y,Math.abs(t.Dx)<Math.abs(e.Dx)?n.X=i.Clipper.TopX(t,n.Y):n.X=i.Clipper.TopX(e,n.Y)}n.Y>t.Curr.Y&&(n.Y=t.Curr.Y,Math.abs(t.Dx)>Math.abs(e.Dx)?n.X=i.Clipper.TopX(e,n.Y):n.X=i.Clipper.TopX(t,n.Y))},i.Clipper.prototype.ProcessEdgesAtTopOfScanbeam=function(t){for(var e=this.m_ActiveEdges;e!==null;){var n=this.IsMaxima(e,t);if(n){var r=this.GetMaximaPairEx(e);n=r===null||!i.ClipperBase.IsHorizontal(r)}if(n){this.StrictlySimple&&this.InsertMaxima(e.Top.X);var o=e.PrevInAEL;this.DoMaxima(e),o===null?e=this.m_ActiveEdges:e=o.NextInAEL}else{if(this.IsIntermediate(e,t)&&i.ClipperBase.IsHorizontal(e.NextInLML)?(e=this.UpdateEdgeIntoAEL(e),e.OutIdx>=0&&this.AddOutPt(e,e.Bot),this.AddEdgeToSEL(e)):(e.Curr.X=i.Clipper.TopX(e,t),e.Curr.Y=t),i.use_xyz&&(e.Top.Y===t?e.Curr.Z=e.Top.Z:e.Bot.Y===t?e.Curr.Z=e.Bot.Z:e.Curr.Z=0),this.StrictlySimple){var o=e.PrevInAEL;if(e.OutIdx>=0&&e.WindDelta!==0&&o!==null&&o.OutIdx>=0&&o.Curr.X===e.Curr.X&&o.WindDelta!==0){var s=new i.IntPoint1(e.Curr);i.use_xyz&&this.SetZ(s,o,e);var u=this.AddOutPt(o,s),p=this.AddOutPt(e,s);this.AddJoin(u,p,s)}}e=e.NextInAEL}}for(this.ProcessHorizontals(),this.m_Maxima=null,e=this.m_ActiveEdges;e!==null;){if(this.IsIntermediate(e,t)){var u=null;e.OutIdx>=0&&(u=this.AddOutPt(e,e.Top)),e=this.UpdateEdgeIntoAEL(e);var o=e.PrevInAEL,d=e.NextInAEL;if(o!==null&&o.Curr.X===e.Bot.X&&o.Curr.Y===e.Bot.Y&&u!==null&&o.OutIdx>=0&&o.Curr.Y===o.Top.Y&&i.ClipperBase.SlopesEqual5(e.Curr,e.Top,o.Curr,o.Top,this.m_UseFullRange)&&e.WindDelta!==0&&o.WindDelta!==0){var p=this.AddOutPt(ePrev2,e.Bot);this.AddJoin(u,p,e.Top)}else if(d!==null&&d.Curr.X===e.Bot.X&&d.Curr.Y===e.Bot.Y&&u!==null&&d.OutIdx>=0&&d.Curr.Y===d.Top.Y&&i.ClipperBase.SlopesEqual5(e.Curr,e.Top,d.Curr,d.Top,this.m_UseFullRange)&&e.WindDelta!==0&&d.WindDelta!==0){var p=this.AddOutPt(d,e.Bot);this.AddJoin(u,p,e.Top)}}e=e.NextInAEL}},i.Clipper.prototype.DoMaxima=function(t){var e=this.GetMaximaPairEx(t);if(e===null){t.OutIdx>=0&&this.AddOutPt(t,t.Top),this.DeleteFromAEL(t);return}for(var n=t.NextInAEL;n!==null&&n!==e;)this.IntersectEdges(t,n,t.Top),this.SwapPositionsInAEL(t,n),n=t.NextInAEL;t.OutIdx===-1&&e.OutIdx===-1?(this.DeleteFromAEL(t),this.DeleteFromAEL(e)):t.OutIdx>=0&&e.OutIdx>=0?(t.OutIdx>=0&&this.AddLocalMaxPoly(t,e,t.Top),this.DeleteFromAEL(t),this.DeleteFromAEL(e)):i.use_lines&&t.WindDelta===0?(t.OutIdx>=0&&(this.AddOutPt(t,t.Top),t.OutIdx=i.ClipperBase.Unassigned),this.DeleteFromAEL(t),e.OutIdx>=0&&(this.AddOutPt(e,t.Top),e.OutIdx=i.ClipperBase.Unassigned),this.DeleteFromAEL(e)):i.Error("DoMaxima error")},i.Clipper.ReversePaths=function(t){for(var e=0,n=t.length;e<n;e++)t[e].reverse()},i.Clipper.Orientation=function(t){return i.Clipper.Area(t)>=0},i.Clipper.prototype.PointCount=function(t){if(t===null)return 0;var e=0,n=t;do e++,n=n.Next;while(n!==t);return e},i.Clipper.prototype.BuildResult=function(t){i.Clear(t);for(var e=0,n=this.m_PolyOuts.length;e<n;e++){var r=this.m_PolyOuts[e];if(r.Pts!==null){var o=r.Pts.Prev,s=this.PointCount(o);if(!(s<2)){for(var u=new Array(s),p=0;p<s;p++)u[p]=o.Pt,o=o.Prev;t.push(u)}}}},i.Clipper.prototype.BuildResult2=function(t){t.Clear();for(var e=0,n=this.m_PolyOuts.length;e<n;e++){var r=this.m_PolyOuts[e],o=this.PointCount(r.Pts);if(!(r.IsOpen&&o<2||!r.IsOpen&&o<3)){this.FixHoleLinkage(r);var s=new i.PolyNode;t.m_AllPolys.push(s),r.PolyNode=s,s.m_polygon.length=o;for(var u=r.Pts.Prev,p=0;p<o;p++)s.m_polygon[p]=u.Pt,u=u.Prev}}for(var e=0,n=this.m_PolyOuts.length;e<n;e++){var r=this.m_PolyOuts[e];r.PolyNode!==null&&(r.IsOpen?(r.PolyNode.IsOpen=!0,t.AddChild(r.PolyNode)):r.FirstLeft!==null&&r.FirstLeft.PolyNode!==null?r.FirstLeft.PolyNode.AddChild(r.PolyNode):t.AddChild(r.PolyNode))}},i.Clipper.prototype.FixupOutPolyline=function(t){for(var e=t.Pts,n=e.Prev;e!==n;)if(e=e.Next,i.IntPoint.op_Equality(e.Pt,e.Prev.Pt)){e===n&&(n=e.Prev);var r=e.Prev;r.Next=e.Next,e.Next.Prev=r,e=r}e===e.Prev&&(t.Pts=null)},i.Clipper.prototype.FixupOutPolygon=function(t){var e=null;t.BottomPt=null;for(var n=t.Pts,r=this.PreserveCollinear||this.StrictlySimple;;){if(n.Prev===n||n.Prev===n.Next){t.Pts=null;return}if(i.IntPoint.op_Equality(n.Pt,n.Next.Pt)||i.IntPoint.op_Equality(n.Pt,n.Prev.Pt)||i.ClipperBase.SlopesEqual4(n.Prev.Pt,n.Pt,n.Next.Pt,this.m_UseFullRange)&&(!r||!this.Pt2IsBetweenPt1AndPt3(n.Prev.Pt,n.Pt,n.Next.Pt)))e=null,n.Prev.Next=n.Next,n.Next.Prev=n.Prev,n=n.Prev;else{if(n===e)break;e===null&&(e=n),n=n.Next}}t.Pts=n},i.Clipper.prototype.DupOutPt=function(t,e){var n=new i.OutPt;return n.Pt.X=t.Pt.X,n.Pt.Y=t.Pt.Y,i.use_xyz&&(n.Pt.Z=t.Pt.Z),n.Idx=t.Idx,e?(n.Next=t.Next,n.Prev=t,t.Next.Prev=n,t.Next=n):(n.Prev=t.Prev,n.Next=t,t.Prev.Next=n,t.Prev=n),n},i.Clipper.prototype.GetOverlap=function(t,e,n,r,o){return t<e?n<r?(o.Left=Math.max(t,n),o.Right=Math.min(e,r)):(o.Left=Math.max(t,r),o.Right=Math.min(e,n)):n<r?(o.Left=Math.max(e,n),o.Right=Math.min(t,r)):(o.Left=Math.max(e,r),o.Right=Math.min(t,n)),o.Left<o.Right},i.Clipper.prototype.JoinHorz=function(t,e,n,r,o,s){var u=t.Pt.X>e.Pt.X?i.Direction.dRightToLeft:i.Direction.dLeftToRight,p=n.Pt.X>r.Pt.X?i.Direction.dRightToLeft:i.Direction.dLeftToRight;if(u===p)return!1;if(u===i.Direction.dLeftToRight){for(;t.Next.Pt.X<=o.X&&t.Next.Pt.X>=t.Pt.X&&t.Next.Pt.Y===o.Y;)t=t.Next;s&&t.Pt.X!==o.X&&(t=t.Next),e=this.DupOutPt(t,!s),i.IntPoint.op_Inequality(e.Pt,o)&&(t=e,t.Pt.X=o.X,t.Pt.Y=o.Y,i.use_xyz&&(t.Pt.Z=o.Z),e=this.DupOutPt(t,!s))}else{for(;t.Next.Pt.X>=o.X&&t.Next.Pt.X<=t.Pt.X&&t.Next.Pt.Y===o.Y;)t=t.Next;!s&&t.Pt.X!==o.X&&(t=t.Next),e=this.DupOutPt(t,s),i.IntPoint.op_Inequality(e.Pt,o)&&(t=e,t.Pt.X=o.X,t.Pt.Y=o.Y,i.use_xyz&&(t.Pt.Z=o.Z),e=this.DupOutPt(t,s))}if(p===i.Direction.dLeftToRight){for(;n.Next.Pt.X<=o.X&&n.Next.Pt.X>=n.Pt.X&&n.Next.Pt.Y===o.Y;)n=n.Next;s&&n.Pt.X!==o.X&&(n=n.Next),r=this.DupOutPt(n,!s),i.IntPoint.op_Inequality(r.Pt,o)&&(n=r,n.Pt.X=o.X,n.Pt.Y=o.Y,i.use_xyz&&(n.Pt.Z=o.Z),r=this.DupOutPt(n,!s))}else{for(;n.Next.Pt.X>=o.X&&n.Next.Pt.X<=n.Pt.X&&n.Next.Pt.Y===o.Y;)n=n.Next;!s&&n.Pt.X!==o.X&&(n=n.Next),r=this.DupOutPt(n,s),i.IntPoint.op_Inequality(r.Pt,o)&&(n=r,n.Pt.X=o.X,n.Pt.Y=o.Y,i.use_xyz&&(n.Pt.Z=o.Z),r=this.DupOutPt(n,s))}return u===i.Direction.dLeftToRight===s?(t.Prev=n,n.Next=t,e.Next=r,r.Prev=e):(t.Next=n,n.Prev=t,e.Prev=r,r.Next=e),!0},i.Clipper.prototype.JoinPoints=function(t,e,n){var r=t.OutPt1,o=new i.OutPt,s=t.OutPt2,u=new i.OutPt,p=t.OutPt1.Pt.Y===t.OffPt.Y;if(p&&i.IntPoint.op_Equality(t.OffPt,t.OutPt1.Pt)&&i.IntPoint.op_Equality(t.OffPt,t.OutPt2.Pt)){if(e!==n)return!1;for(o=t.OutPt1.Next;o!==r&&i.IntPoint.op_Equality(o.Pt,t.OffPt);)o=o.Next;var d=o.Pt.Y>t.OffPt.Y;for(u=t.OutPt2.Next;u!==s&&i.IntPoint.op_Equality(u.Pt,t.OffPt);)u=u.Next;var P=u.Pt.Y>t.OffPt.Y;return d===P?!1:d?(o=this.DupOutPt(r,!1),u=this.DupOutPt(s,!0),r.Prev=s,s.Next=r,o.Next=u,u.Prev=o,t.OutPt1=r,t.OutPt2=o,!0):(o=this.DupOutPt(r,!0),u=this.DupOutPt(s,!1),r.Next=s,s.Prev=r,o.Prev=u,u.Next=o,t.OutPt1=r,t.OutPt2=o,!0)}else if(p){for(o=r;r.Prev.Pt.Y===r.Pt.Y&&r.Prev!==o&&r.Prev!==s;)r=r.Prev;for(;o.Next.Pt.Y===o.Pt.Y&&o.Next!==r&&o.Next!==s;)o=o.Next;if(o.Next===r||o.Next===s)return!1;for(u=s;s.Prev.Pt.Y===s.Pt.Y&&s.Prev!==u&&s.Prev!==o;)s=s.Prev;for(;u.Next.Pt.Y===u.Pt.Y&&u.Next!==s&&u.Next!==r;)u=u.Next;if(u.Next===s||u.Next===r)return!1;var w={Left:null,Right:null};if(!this.GetOverlap(r.Pt.X,o.Pt.X,s.Pt.X,u.Pt.X,w))return!1;var C=w.Left,S=w.Right,A=new i.IntPoint0,B;return r.Pt.X>=C&&r.Pt.X<=S?(A.X=r.Pt.X,A.Y=r.Pt.Y,i.use_xyz&&(A.Z=r.Pt.Z),B=r.Pt.X>o.Pt.X):s.Pt.X>=C&&s.Pt.X<=S?(A.X=s.Pt.X,A.Y=s.Pt.Y,i.use_xyz&&(A.Z=s.Pt.Z),B=s.Pt.X>u.Pt.X):o.Pt.X>=C&&o.Pt.X<=S?(A.X=o.Pt.X,A.Y=o.Pt.Y,i.use_xyz&&(A.Z=o.Pt.Z),B=o.Pt.X>r.Pt.X):(A.X=u.Pt.X,A.Y=u.Pt.Y,i.use_xyz&&(A.Z=u.Pt.Z),B=u.Pt.X>s.Pt.X),t.OutPt1=r,t.OutPt2=s,this.JoinHorz(r,o,s,u,A,B)}else{for(o=r.Next;i.IntPoint.op_Equality(o.Pt,r.Pt)&&o!==r;)o=o.Next;var k=o.Pt.Y>r.Pt.Y||!i.ClipperBase.SlopesEqual4(r.Pt,o.Pt,t.OffPt,this.m_UseFullRange);if(k){for(o=r.Prev;i.IntPoint.op_Equality(o.Pt,r.Pt)&&o!==r;)o=o.Prev;if(o.Pt.Y>r.Pt.Y||!i.ClipperBase.SlopesEqual4(r.Pt,o.Pt,t.OffPt,this.m_UseFullRange))return!1}for(u=s.Next;i.IntPoint.op_Equality(u.Pt,s.Pt)&&u!==s;)u=u.Next;var U=u.Pt.Y>s.Pt.Y||!i.ClipperBase.SlopesEqual4(s.Pt,u.Pt,t.OffPt,this.m_UseFullRange);if(U){for(u=s.Prev;i.IntPoint.op_Equality(u.Pt,s.Pt)&&u!==s;)u=u.Prev;if(u.Pt.Y>s.Pt.Y||!i.ClipperBase.SlopesEqual4(s.Pt,u.Pt,t.OffPt,this.m_UseFullRange))return!1}return o===r||u===s||o===u||e===n&&k===U?!1:k?(o=this.DupOutPt(r,!1),u=this.DupOutPt(s,!0),r.Prev=s,s.Next=r,o.Next=u,u.Prev=o,t.OutPt1=r,t.OutPt2=o,!0):(o=this.DupOutPt(r,!0),u=this.DupOutPt(s,!1),r.Next=s,s.Prev=r,o.Prev=u,u.Next=o,t.OutPt1=r,t.OutPt2=o,!0)}},i.Clipper.GetBounds=function(t){for(var e=0,n=t.length;e<n&&t[e].length===0;)e++;if(e===n)return new i.IntRect(0,0,0,0);var r=new i.IntRect;for(r.left=t[e][0].X,r.right=r.left,r.top=t[e][0].Y,r.bottom=r.top;e<n;e++)for(var o=0,s=t[e].length;o<s;o++)t[e][o].X<r.left?r.left=t[e][o].X:t[e][o].X>r.right&&(r.right=t[e][o].X),t[e][o].Y<r.top?r.top=t[e][o].Y:t[e][o].Y>r.bottom&&(r.bottom=t[e][o].Y);return r},i.Clipper.prototype.GetBounds2=function(t){var e=t,n=new i.IntRect;for(n.left=t.Pt.X,n.right=t.Pt.X,n.top=t.Pt.Y,n.bottom=t.Pt.Y,t=t.Next;t!==e;)t.Pt.X<n.left&&(n.left=t.Pt.X),t.Pt.X>n.right&&(n.right=t.Pt.X),t.Pt.Y<n.top&&(n.top=t.Pt.Y),t.Pt.Y>n.bottom&&(n.bottom=t.Pt.Y),t=t.Next;return n},i.Clipper.PointInPolygon=function(t,e){var n=0,r=e.length;if(r<3)return 0;for(var o=e[0],s=1;s<=r;++s){var u=s===r?e[0]:e[s];if(u.Y===t.Y&&(u.X===t.X||o.Y===t.Y&&u.X>t.X==o.X<t.X))return-1;if(o.Y<t.Y!=u.Y<t.Y){if(o.X>=t.X)if(u.X>t.X)n=1-n;else{var p=(o.X-t.X)*(u.Y-t.Y)-(u.X-t.X)*(o.Y-t.Y);if(p===0)return-1;p>0==u.Y>o.Y&&(n=1-n)}else if(u.X>t.X){var p=(o.X-t.X)*(u.Y-t.Y)-(u.X-t.X)*(o.Y-t.Y);if(p===0)return-1;p>0==u.Y>o.Y&&(n=1-n)}}o=u}return n},i.Clipper.prototype.PointInPolygon=function(t,e){var n=0,r=e,o=t.X,s=t.Y,u=e.Pt.X,p=e.Pt.Y;do{e=e.Next;var d=e.Pt.X,P=e.Pt.Y;if(P===s&&(d===o||p===s&&d>o==u<o))return-1;if(p<s!=P<s){if(u>=o)if(d>o)n=1-n;else{var w=(u-o)*(P-s)-(d-o)*(p-s);if(w===0)return-1;w>0==P>p&&(n=1-n)}else if(d>o){var w=(u-o)*(P-s)-(d-o)*(p-s);if(w===0)return-1;w>0==P>p&&(n=1-n)}}u=d,p=P}while(r!==e);return n},i.Clipper.prototype.Poly2ContainsPoly1=function(t,e){var n=t;do{var r=this.PointInPolygon(n.Pt,e);if(r>=0)return r>0;n=n.Next}while(n!==t);return!0},i.Clipper.prototype.FixupFirstLefts1=function(t,e){for(var n,r,o=0,s=this.m_PolyOuts.length;o<s;o++)n=this.m_PolyOuts[o],r=i.Clipper.ParseFirstLeft(n.FirstLeft),n.Pts!==null&&r===t&&this.Poly2ContainsPoly1(n.Pts,e.Pts)&&(n.FirstLeft=e)},i.Clipper.prototype.FixupFirstLefts2=function(t,e){for(var n=e.FirstLeft,r,o,s=0,u=this.m_PolyOuts.length;s<u;s++)r=this.m_PolyOuts[s],!(r.Pts===null||r===e||r===t)&&(o=i.Clipper.ParseFirstLeft(r.FirstLeft),!(o!==n&&o!==t&&o!==e)&&(this.Poly2ContainsPoly1(r.Pts,t.Pts)?r.FirstLeft=t:this.Poly2ContainsPoly1(r.Pts,e.Pts)?r.FirstLeft=e:(r.FirstLeft===t||r.FirstLeft===e)&&(r.FirstLeft=n)))},i.Clipper.prototype.FixupFirstLefts3=function(t,e){for(var n,r,o=0,s=this.m_PolyOuts.length;o<s;o++)n=this.m_PolyOuts[o],r=i.Clipper.ParseFirstLeft(n.FirstLeft),n.Pts!==null&&r===t&&(n.FirstLeft=e)},i.Clipper.ParseFirstLeft=function(t){for(;t!==null&&t.Pts===null;)t=t.FirstLeft;return t},i.Clipper.prototype.JoinCommonEdges=function(){for(var t=0,e=this.m_Joins.length;t<e;t++){var n=this.m_Joins[t],r=this.GetOutRec(n.OutPt1.Idx),o=this.GetOutRec(n.OutPt2.Idx);if(!(r.Pts===null||o.Pts===null)&&!(r.IsOpen||o.IsOpen)){var s;r===o?s=r:this.OutRec1RightOfOutRec2(r,o)?s=o:this.OutRec1RightOfOutRec2(o,r)?s=r:s=this.GetLowermostRec(r,o),this.JoinPoints(n,r,o)&&(r===o?(r.Pts=n.OutPt1,r.BottomPt=null,o=this.CreateOutRec(),o.Pts=n.OutPt2,this.UpdateOutPtIdxs(o),this.Poly2ContainsPoly1(o.Pts,r.Pts)?(o.IsHole=!r.IsHole,o.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts2(o,r),(o.IsHole^this.ReverseSolution)==this.Area$1(o)>0&&this.ReversePolyPtLinks(o.Pts)):this.Poly2ContainsPoly1(r.Pts,o.Pts)?(o.IsHole=r.IsHole,r.IsHole=!o.IsHole,o.FirstLeft=r.FirstLeft,r.FirstLeft=o,this.m_UsingPolyTree&&this.FixupFirstLefts2(r,o),(r.IsHole^this.ReverseSolution)==this.Area$1(r)>0&&this.ReversePolyPtLinks(r.Pts)):(o.IsHole=r.IsHole,o.FirstLeft=r.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(r,o))):(o.Pts=null,o.BottomPt=null,o.Idx=r.Idx,r.IsHole=s.IsHole,s===o&&(r.FirstLeft=o.FirstLeft),o.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts3(o,r)))}}},i.Clipper.prototype.UpdateOutPtIdxs=function(t){var e=t.Pts;do e.Idx=t.Idx,e=e.Prev;while(e!==t.Pts)},i.Clipper.prototype.DoSimplePolygons=function(){for(var t=0;t<this.m_PolyOuts.length;){var e=this.m_PolyOuts[t++],n=e.Pts;if(!(n===null||e.IsOpen))do{for(var r=n.Next;r!==e.Pts;){if(i.IntPoint.op_Equality(n.Pt,r.Pt)&&r.Next!==n&&r.Prev!==n){var o=n.Prev,s=r.Prev;n.Prev=s,s.Next=n,r.Prev=o,o.Next=r,e.Pts=n;var u=this.CreateOutRec();u.Pts=r,this.UpdateOutPtIdxs(u),this.Poly2ContainsPoly1(u.Pts,e.Pts)?(u.IsHole=!e.IsHole,u.FirstLeft=e,this.m_UsingPolyTree&&this.FixupFirstLefts2(u,e)):this.Poly2ContainsPoly1(e.Pts,u.Pts)?(u.IsHole=e.IsHole,e.IsHole=!u.IsHole,u.FirstLeft=e.FirstLeft,e.FirstLeft=u,this.m_UsingPolyTree&&this.FixupFirstLefts2(e,u)):(u.IsHole=e.IsHole,u.FirstLeft=e.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(e,u)),r=n}r=r.Next}n=n.Next}while(n!==e.Pts)}},i.Clipper.Area=function(t){if(!Array.isArray(t))return 0;var e=t.length;if(e<3)return 0;for(var n=0,r=0,o=e-1;r<e;++r)n+=(t[o].X+t[r].X)*(t[o].Y-t[r].Y),o=r;return-n*.5},i.Clipper.prototype.Area=function(t){var e=t;if(t===null)return 0;var n=0;do n=n+(t.Prev.Pt.X+t.Pt.X)*(t.Prev.Pt.Y-t.Pt.Y),t=t.Next;while(t!==e);return n*.5},i.Clipper.prototype.Area$1=function(t){return this.Area(t.Pts)},i.Clipper.SimplifyPolygon=function(t,e){var n=new Array,r=new i.Clipper(0);return r.StrictlySimple=!0,r.AddPath(t,i.PolyType.ptSubject,!0),r.Execute(i.ClipType.ctUnion,n,e,e),n},i.Clipper.SimplifyPolygons=function(t,e){typeof e>"u"&&(e=i.PolyFillType.pftEvenOdd);var n=new Array,r=new i.Clipper(0);return r.StrictlySimple=!0,r.AddPaths(t,i.PolyType.ptSubject,!0),r.Execute(i.ClipType.ctUnion,n,e,e),n},i.Clipper.DistanceSqrd=function(t,e){var n=t.X-e.X,r=t.Y-e.Y;return n*n+r*r},i.Clipper.DistanceFromLineSqrd=function(t,e,n){var r=e.Y-n.Y,o=n.X-e.X,s=r*e.X+o*e.Y;return s=r*t.X+o*t.Y-s,s*s/(r*r+o*o)},i.Clipper.SlopesNearCollinear=function(t,e,n,r){return Math.abs(t.X-e.X)>Math.abs(t.Y-e.Y)?t.X>e.X==t.X<n.X?i.Clipper.DistanceFromLineSqrd(t,e,n)<r:e.X>t.X==e.X<n.X?i.Clipper.DistanceFromLineSqrd(e,t,n)<r:i.Clipper.DistanceFromLineSqrd(n,t,e)<r:t.Y>e.Y==t.Y<n.Y?i.Clipper.DistanceFromLineSqrd(t,e,n)<r:e.Y>t.Y==e.Y<n.Y?i.Clipper.DistanceFromLineSqrd(e,t,n)<r:i.Clipper.DistanceFromLineSqrd(n,t,e)<r},i.Clipper.PointsAreClose=function(t,e,n){var r=t.X-e.X,o=t.Y-e.Y;return r*r+o*o<=n},i.Clipper.ExcludeOp=function(t){var e=t.Prev;return e.Next=t.Next,t.Next.Prev=e,e.Idx=0,e},i.Clipper.CleanPolygon=function(t,e){typeof e>"u"&&(e=1.415);var n=t.length;if(n===0)return new Array;for(var r=new Array(n),o=0;o<n;++o)r[o]=new i.OutPt;for(var o=0;o<n;++o)r[o].Pt=t[o],r[o].Next=r[(o+1)%n],r[o].Next.Prev=r[o],r[o].Idx=0;for(var s=e*e,u=r[0];u.Idx===0&&u.Next!==u.Prev;)i.Clipper.PointsAreClose(u.Pt,u.Prev.Pt,s)?(u=i.Clipper.ExcludeOp(u),n--):i.Clipper.PointsAreClose(u.Prev.Pt,u.Next.Pt,s)?(i.Clipper.ExcludeOp(u.Next),u=i.Clipper.ExcludeOp(u),n-=2):i.Clipper.SlopesNearCollinear(u.Prev.Pt,u.Pt,u.Next.Pt,s)?(u=i.Clipper.ExcludeOp(u),n--):(u.Idx=1,u=u.Next);n<3&&(n=0);for(var p=new Array(n),o=0;o<n;++o)p[o]=new i.IntPoint1(u.Pt),u=u.Next;return r=null,p},i.Clipper.CleanPolygons=function(t,e){for(var n=new Array(t.length),r=0,o=t.length;r<o;r++)n[r]=i.Clipper.CleanPolygon(t[r],e);return n},i.Clipper.Minkowski=function(t,e,n,r){var o=r?1:0,s=t.length,u=e.length,p=new Array;if(n)for(var d=0;d<u;d++){for(var P=new Array(s),w=0,C=t.length,S=t[w];w<C;w++,S=t[w])P[w]=new i.IntPoint2(e[d].X+S.X,e[d].Y+S.Y);p.push(P)}else for(var d=0;d<u;d++){for(var P=new Array(s),w=0,C=t.length,S=t[w];w<C;w++,S=t[w])P[w]=new i.IntPoint2(e[d].X-S.X,e[d].Y-S.Y);p.push(P)}for(var A=new Array,d=0;d<u-1+o;d++)for(var w=0;w<s;w++){var B=new Array;B.push(p[d%u][w%s]),B.push(p[(d+1)%u][w%s]),B.push(p[(d+1)%u][(w+1)%s]),B.push(p[d%u][(w+1)%s]),i.Clipper.Orientation(B)||B.reverse(),A.push(B)}return A},i.Clipper.MinkowskiSum=function(t,e,n){if(e[0]instanceof Array){for(var o=e,u=new i.Paths,s=new i.Clipper,p=0;p<o.length;++p){var d=i.Clipper.Minkowski(t,o[p],!0,n);if(s.AddPaths(d,i.PolyType.ptSubject,!0),n){var r=i.Clipper.TranslatePath(o[p],t[0]);s.AddPath(r,i.PolyType.ptClip,!0)}}return s.Execute(i.ClipType.ctUnion,u,i.PolyFillType.pftNonZero,i.PolyFillType.pftNonZero),u}else{var r=e,o=i.Clipper.Minkowski(t,r,!0,n),s=new i.Clipper;return s.AddPaths(o,i.PolyType.ptSubject,!0),s.Execute(i.ClipType.ctUnion,o,i.PolyFillType.pftNonZero,i.PolyFillType.pftNonZero),o}},i.Clipper.TranslatePath=function(t,e){for(var n=new i.Path,r=0;r<t.length;r++)n.push(new i.IntPoint2(t[r].X+e.X,t[r].Y+e.Y));return n},i.Clipper.MinkowskiDiff=function(t,e){var n=i.Clipper.Minkowski(t,e,!1,!0),r=new i.Clipper;return r.AddPaths(n,i.PolyType.ptSubject,!0),r.Execute(i.ClipType.ctUnion,n,i.PolyFillType.pftNonZero,i.PolyFillType.pftNonZero),n},i.Clipper.PolyTreeToPaths=function(t){var e=new Array;return i.Clipper.AddPolyNodeToPaths(t,i.Clipper.NodeType.ntAny,e),e},i.Clipper.AddPolyNodeToPaths=function(t,e,n){var r=!0;switch(e){case i.Clipper.NodeType.ntOpen:return;case i.Clipper.NodeType.ntClosed:r=!t.IsOpen;break;default:break}t.m_polygon.length>0&&r&&n.push(t.m_polygon);for(var o=0,s=t.Childs(),u=s.length,p=s[o];o<u;o++,p=s[o])i.Clipper.AddPolyNodeToPaths(p,e,n)},i.Clipper.OpenPathsFromPolyTree=function(t){for(var e=new i.Paths,n=0,r=t.ChildCount();n<r;n++)t.Childs()[n].IsOpen&&e.push(t.Childs()[n].m_polygon);return e},i.Clipper.ClosedPathsFromPolyTree=function(t){var e=new i.Paths;return i.Clipper.AddPolyNodeToPaths(t,i.Clipper.NodeType.ntClosed,e),e},ni(i.Clipper,i.ClipperBase),i.Clipper.NodeType={ntAny:0,ntOpen:1,ntClosed:2},i.ClipperOffset=function(t,e){typeof t>"u"&&(t=2),typeof e>"u"&&(e=i.ClipperOffset.def_arc_tolerance),this.m_destPolys=new i.Paths,this.m_srcPoly=new i.Path,this.m_destPoly=new i.Path,this.m_normals=new Array,this.m_delta=0,this.m_sinA=0,this.m_sin=0,this.m_cos=0,this.m_miterLim=0,this.m_StepsPerRad=0,this.m_lowest=new i.IntPoint0,this.m_polyNodes=new i.PolyNode,this.MiterLimit=t,this.ArcTolerance=e,this.m_lowest.X=-1},i.ClipperOffset.two_pi=6.28318530717959,i.ClipperOffset.def_arc_tolerance=.25,i.ClipperOffset.prototype.Clear=function(){i.Clear(this.m_polyNodes.Childs()),this.m_lowest.X=-1},i.ClipperOffset.Round=i.Clipper.Round,i.ClipperOffset.prototype.AddPath=function(t,e,n){var r=t.length-1;if(!(r<0)){var o=new i.PolyNode;if(o.m_jointype=e,o.m_endtype=n,n===i.EndType.etClosedLine||n===i.EndType.etClosedPolygon)for(;r>0&&i.IntPoint.op_Equality(t[0],t[r]);)r--;o.m_polygon.push(t[0]);for(var s=0,u=0,p=1;p<=r;p++)i.IntPoint.op_Inequality(o.m_polygon[s],t[p])&&(s++,o.m_polygon.push(t[p]),(t[p].Y>o.m_polygon[u].Y||t[p].Y===o.m_polygon[u].Y&&t[p].X<o.m_polygon[u].X)&&(u=s));if(!(n===i.EndType.etClosedPolygon&&s<2)&&(this.m_polyNodes.AddChild(o),n===i.EndType.etClosedPolygon))if(this.m_lowest.X<0)this.m_lowest=new i.IntPoint2(this.m_polyNodes.ChildCount()-1,u);else{var d=this.m_polyNodes.Childs()[this.m_lowest.X].m_polygon[this.m_lowest.Y];(o.m_polygon[u].Y>d.Y||o.m_polygon[u].Y===d.Y&&o.m_polygon[u].X<d.X)&&(this.m_lowest=new i.IntPoint2(this.m_polyNodes.ChildCount()-1,u))}}},i.ClipperOffset.prototype.AddPaths=function(t,e,n){for(var r=0,o=t.length;r<o;r++)this.AddPath(t[r],e,n)},i.ClipperOffset.prototype.FixOrientations=function(){if(this.m_lowest.X>=0&&!i.Clipper.Orientation(this.m_polyNodes.Childs()[this.m_lowest.X].m_polygon))for(var t=0;t<this.m_polyNodes.ChildCount();t++){var e=this.m_polyNodes.Childs()[t];(e.m_endtype===i.EndType.etClosedPolygon||e.m_endtype===i.EndType.etClosedLine&&i.Clipper.Orientation(e.m_polygon))&&e.m_polygon.reverse()}else for(var t=0;t<this.m_polyNodes.ChildCount();t++){var e=this.m_polyNodes.Childs()[t];e.m_endtype===i.EndType.etClosedLine&&!i.Clipper.Orientation(e.m_polygon)&&e.m_polygon.reverse()}},i.ClipperOffset.GetUnitNormal=function(t,e){var n=e.X-t.X,r=e.Y-t.Y;if(n===0&&r===0)return new i.DoublePoint2(0,0);var o=1/Math.sqrt(n*n+r*r);return n*=o,r*=o,new i.DoublePoint2(r,-n)},i.ClipperOffset.prototype.DoOffset=function(t){if(this.m_destPolys=new Array,this.m_delta=t,i.ClipperBase.near_zero(t)){for(var e=0;e<this.m_polyNodes.ChildCount();e++){var n=this.m_polyNodes.Childs()[e];n.m_endtype===i.EndType.etClosedPolygon&&this.m_destPolys.push(n.m_polygon)}return}this.MiterLimit>2?this.m_miterLim=2/(this.MiterLimit*this.MiterLimit):this.m_miterLim=.5;var r;this.ArcTolerance<=0?r=i.ClipperOffset.def_arc_tolerance:this.ArcTolerance>Math.abs(t)*i.ClipperOffset.def_arc_tolerance?r=Math.abs(t)*i.ClipperOffset.def_arc_tolerance:r=this.ArcTolerance;var o=3.14159265358979/Math.acos(1-r/Math.abs(t));this.m_sin=Math.sin(i.ClipperOffset.two_pi/o),this.m_cos=Math.cos(i.ClipperOffset.two_pi/o),this.m_StepsPerRad=o/i.ClipperOffset.two_pi,t<0&&(this.m_sin=-this.m_sin);for(var e=0;e<this.m_polyNodes.ChildCount();e++){var n=this.m_polyNodes.Childs()[e];this.m_srcPoly=n.m_polygon;var s=this.m_srcPoly.length;if(!(s===0||t<=0&&(s<3||n.m_endtype!==i.EndType.etClosedPolygon))){if(this.m_destPoly=new Array,s===1){if(n.m_jointype===i.JoinType.jtRound)for(var u=1,p=0,d=1;d<=o;d++){this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[0].X+u*t),i.ClipperOffset.Round(this.m_srcPoly[0].Y+p*t)));var P=u;u=u*this.m_cos-this.m_sin*p,p=P*this.m_sin+p*this.m_cos}else for(var u=-1,p=-1,d=0;d<4;++d)this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[0].X+u*t),i.ClipperOffset.Round(this.m_srcPoly[0].Y+p*t))),u<0?u=1:p<0?p=1:u=-1;this.m_destPolys.push(this.m_destPoly);continue}this.m_normals.length=0;for(var d=0;d<s-1;d++)this.m_normals.push(i.ClipperOffset.GetUnitNormal(this.m_srcPoly[d],this.m_srcPoly[d+1]));if(n.m_endtype===i.EndType.etClosedLine||n.m_endtype===i.EndType.etClosedPolygon?this.m_normals.push(i.ClipperOffset.GetUnitNormal(this.m_srcPoly[s-1],this.m_srcPoly[0])):this.m_normals.push(new i.DoublePoint1(this.m_normals[s-2])),n.m_endtype===i.EndType.etClosedPolygon){for(var w=s-1,d=0;d<s;d++)w=this.OffsetPoint(d,w,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else if(n.m_endtype===i.EndType.etClosedLine){for(var w=s-1,d=0;d<s;d++)w=this.OffsetPoint(d,w,n.m_jointype);this.m_destPolys.push(this.m_destPoly),this.m_destPoly=new Array;for(var C=this.m_normals[s-1],d=s-1;d>0;d--)this.m_normals[d]=new i.DoublePoint2(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new i.DoublePoint2(-C.X,-C.Y),w=0;for(var d=s-1;d>=0;d--)w=this.OffsetPoint(d,w,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else{for(var w=0,d=1;d<s-1;++d)w=this.OffsetPoint(d,w,n.m_jointype);var S;if(n.m_endtype===i.EndType.etOpenButt){var d=s-1;S=new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[d].X+this.m_normals[d].X*t),i.ClipperOffset.Round(this.m_srcPoly[d].Y+this.m_normals[d].Y*t)),this.m_destPoly.push(S),S=new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[d].X-this.m_normals[d].X*t),i.ClipperOffset.Round(this.m_srcPoly[d].Y-this.m_normals[d].Y*t)),this.m_destPoly.push(S)}else{var d=s-1;w=s-2,this.m_sinA=0,this.m_normals[d]=new i.DoublePoint2(-this.m_normals[d].X,-this.m_normals[d].Y),n.m_endtype===i.EndType.etOpenSquare?this.DoSquare(d,w):this.DoRound(d,w)}for(var d=s-1;d>0;d--)this.m_normals[d]=new i.DoublePoint2(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new i.DoublePoint2(-this.m_normals[1].X,-this.m_normals[1].Y),w=s-1;for(var d=w-1;d>0;--d)w=this.OffsetPoint(d,w,n.m_jointype);n.m_endtype===i.EndType.etOpenButt?(S=new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[0].X-this.m_normals[0].X*t),i.ClipperOffset.Round(this.m_srcPoly[0].Y-this.m_normals[0].Y*t)),this.m_destPoly.push(S),S=new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[0].X+this.m_normals[0].X*t),i.ClipperOffset.Round(this.m_srcPoly[0].Y+this.m_normals[0].Y*t)),this.m_destPoly.push(S)):(w=1,this.m_sinA=0,n.m_endtype===i.EndType.etOpenSquare?this.DoSquare(0,1):this.DoRound(0,1)),this.m_destPolys.push(this.m_destPoly)}}}},i.ClipperOffset.prototype.Execute=function(){var t=arguments,e=t[0]instanceof i.PolyTree;if(e){var n=t[0],r=t[1];n.Clear(),this.FixOrientations(),this.DoOffset(r);var o=new i.Clipper(0);if(o.AddPaths(this.m_destPolys,i.PolyType.ptSubject,!0),r>0)o.Execute(i.ClipType.ctUnion,n,i.PolyFillType.pftPositive,i.PolyFillType.pftPositive);else{var s=i.Clipper.GetBounds(this.m_destPolys),u=new i.Path;if(u.push(new i.IntPoint2(s.left-10,s.bottom+10)),u.push(new i.IntPoint2(s.right+10,s.bottom+10)),u.push(new i.IntPoint2(s.right+10,s.top-10)),u.push(new i.IntPoint2(s.left-10,s.top-10)),o.AddPath(u,i.PolyType.ptSubject,!0),o.ReverseSolution=!0,o.Execute(i.ClipType.ctUnion,n,i.PolyFillType.pftNegative,i.PolyFillType.pftNegative),n.ChildCount()===1&&n.Childs()[0].ChildCount()>0){var p=n.Childs()[0];n.Childs()[0]=p.Childs()[0],n.Childs()[0].m_Parent=n;for(var d=1;d<p.ChildCount();d++)n.AddChild(p.Childs()[d])}else n.Clear()}}else{var n=t[0],r=t[1];i.Clear(n),this.FixOrientations(),this.DoOffset(r);var o=new i.Clipper(0);if(o.AddPaths(this.m_destPolys,i.PolyType.ptSubject,!0),r>0)o.Execute(i.ClipType.ctUnion,n,i.PolyFillType.pftPositive,i.PolyFillType.pftPositive);else{var s=i.Clipper.GetBounds(this.m_destPolys),u=new i.Path;u.push(new i.IntPoint2(s.left-10,s.bottom+10)),u.push(new i.IntPoint2(s.right+10,s.bottom+10)),u.push(new i.IntPoint2(s.right+10,s.top-10)),u.push(new i.IntPoint2(s.left-10,s.top-10)),o.AddPath(u,i.PolyType.ptSubject,!0),o.ReverseSolution=!0,o.Execute(i.ClipType.ctUnion,n,i.PolyFillType.pftNegative,i.PolyFillType.pftNegative),n.length>0&&n.splice(0,1)}}},i.ClipperOffset.prototype.OffsetPoint=function(t,e,n){if(this.m_sinA=this.m_normals[e].X*this.m_normals[t].Y-this.m_normals[t].X*this.m_normals[e].Y,Math.abs(this.m_sinA*this.m_delta)<1){var r=this.m_normals[e].X*this.m_normals[t].X+this.m_normals[t].Y*this.m_normals[e].Y;if(r>0)return this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_normals[e].X*this.m_delta),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_normals[e].Y*this.m_delta))),e}else this.m_sinA>1?this.m_sinA=1:this.m_sinA<-1&&(this.m_sinA=-1);if(this.m_sinA*this.m_delta<0)this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_normals[e].X*this.m_delta),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_normals[e].Y*this.m_delta))),this.m_destPoly.push(new i.IntPoint1(this.m_srcPoly[t])),this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_normals[t].X*this.m_delta),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_normals[t].Y*this.m_delta)));else switch(n){case i.JoinType.jtMiter:{var o=1+(this.m_normals[t].X*this.m_normals[e].X+this.m_normals[t].Y*this.m_normals[e].Y);o>=this.m_miterLim?this.DoMiter(t,e,o):this.DoSquare(t,e);break}case i.JoinType.jtSquare:this.DoSquare(t,e);break;case i.JoinType.jtRound:this.DoRound(t,e);break}return e=t,e},i.ClipperOffset.prototype.DoSquare=function(t,e){var n=Math.tan(Math.atan2(this.m_sinA,this.m_normals[e].X*this.m_normals[t].X+this.m_normals[e].Y*this.m_normals[t].Y)/4);this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_delta*(this.m_normals[e].X-this.m_normals[e].Y*n)),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_delta*(this.m_normals[e].Y+this.m_normals[e].X*n)))),this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_delta*(this.m_normals[t].X+this.m_normals[t].Y*n)),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_delta*(this.m_normals[t].Y-this.m_normals[t].X*n))))},i.ClipperOffset.prototype.DoMiter=function(t,e,n){var r=this.m_delta/n;this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+(this.m_normals[e].X+this.m_normals[t].X)*r),i.ClipperOffset.Round(this.m_srcPoly[t].Y+(this.m_normals[e].Y+this.m_normals[t].Y)*r)))},i.ClipperOffset.prototype.DoRound=function(t,e){for(var n=Math.atan2(this.m_sinA,this.m_normals[e].X*this.m_normals[t].X+this.m_normals[e].Y*this.m_normals[t].Y),r=Math.max(i.Cast_Int32(i.ClipperOffset.Round(this.m_StepsPerRad*Math.abs(n))),1),o=this.m_normals[e].X,s=this.m_normals[e].Y,u,p=0;p<r;++p)this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+o*this.m_delta),i.ClipperOffset.Round(this.m_srcPoly[t].Y+s*this.m_delta))),u=o,o=o*this.m_cos-this.m_sin*s,s=u*this.m_sin+s*this.m_cos;this.m_destPoly.push(new i.IntPoint2(i.ClipperOffset.Round(this.m_srcPoly[t].X+this.m_normals[t].X*this.m_delta),i.ClipperOffset.Round(this.m_srcPoly[t].Y+this.m_normals[t].Y*this.m_delta)))},i.Error=function(t){try{throw new Error(t)}catch(e){alert(e.message)}},i.JS={},i.JS.AreaOfPolygon=function(t,e){return e||(e=1),i.Clipper.Area(t)/(e*e)},i.JS.AreaOfPolygons=function(t,e){e||(e=1);for(var n=0,r=0;r<t.length;r++)n+=i.Clipper.Area(t[r]);return n/(e*e)},i.JS.BoundsOfPath=function(t,e){return i.JS.BoundsOfPaths([t],e)},i.JS.BoundsOfPaths=function(t,e){e||(e=1);var n=i.Clipper.GetBounds(t);return n.left/=e,n.bottom/=e,n.right/=e,n.top/=e,n},i.JS.Clean=function(r,e){if(!(r instanceof Array))return[];var n=r[0]instanceof Array,r=i.JS.Clone(r);if(typeof e!="number"||e===null)return i.Error("Delta is not a number in Clean()."),r;if(r.length===0||r.length===1&&r[0].length===0||e<0)return r;n||(r=[r]);for(var o=r.length,s,u,p,d,P,w,C,S=[],A=0;A<o;A++)if(u=r[A],s=u.length,s!==0){if(s<3){p=u,S.push(p);continue}for(p=u,d=e*e,P=u[0],w=1,C=1;C<s;C++)(u[C].X-P.X)*(u[C].X-P.X)+(u[C].Y-P.Y)*(u[C].Y-P.Y)<=d||(p[w]=u[C],P=u[C],w++);P=u[w-1],(u[0].X-P.X)*(u[0].X-P.X)+(u[0].Y-P.Y)*(u[0].Y-P.Y)<=d&&w--,w<s&&p.splice(w,s-w),p.length&&S.push(p)}return!n&&S.length?S=S[0]:!n&&S.length===0?S=[]:n&&S.length===0&&(S=[[]]),S},i.JS.Clone=function(t){if(!(t instanceof Array))return[];if(t.length===0)return[];if(t.length===1&&t[0].length===0)return[[]];var e=t[0]instanceof Array;e||(t=[t]);var n=t.length,r,o,s,u,p=new Array(n);for(o=0;o<n;o++){for(r=t[o].length,u=new Array(r),s=0;s<r;s++)u[s]={X:t[o][s].X,Y:t[o][s].Y};p[o]=u}return e||(p=p[0]),p},i.JS.Lighten=function(t,e){if(!(t instanceof Array))return[];if(typeof e!="number"||e===null)return i.Error("Tolerance is not a number in Lighten()."),i.JS.Clone(t);if(t.length===0||t.length===1&&t[0].length===0||e<0)return i.JS.Clone(t);var n=t[0]instanceof Array;n||(t=[t]);var r,o,s,u,p,d,P,w,C,S,A,B,k,U,ut,Ct,jt,Gn=t.length,Vn=e*e,Jt=[];for(r=0;r<Gn;r++)if(s=t[r],d=s.length,d!==0){for(u=0;u<1e6;u++){for(p=[],d=s.length,s[d-1].X!==s[0].X||s[d-1].Y!==s[0].Y?(B=1,s.push({X:s[0].X,Y:s[0].Y}),d=s.length):B=0,A=[],o=0;o<d-2;o++)P=s[o],C=s[o+1],w=s[o+2],Ct=P.X,jt=P.Y,k=w.X-Ct,U=w.Y-jt,(k!==0||U!==0)&&(ut=((C.X-Ct)*k+(C.Y-jt)*U)/(k*k+U*U),ut>1?(Ct=w.X,jt=w.Y):ut>0&&(Ct+=k*ut,jt+=U*ut)),k=C.X-Ct,U=C.Y-jt,S=k*k+U*U,S<=Vn&&(A[o+1]=1,o++);for(p.push({X:s[0].X,Y:s[0].Y}),o=1;o<d-1;o++)A[o]||p.push({X:s[o].X,Y:s[o].Y});if(p.push({X:s[d-1].X,Y:s[d-1].Y}),B&&s.pop(),A.length)s=p;else break}d=p.length,p[d-1].X===p[0].X&&p[d-1].Y===p[0].Y&&p.pop(),p.length>2&&Jt.push(p)}return n||(Jt=Jt[0]),typeof Jt>"u"&&(Jt=[]),Jt},i.JS.PerimeterOfPath=function(t,e,n){if(typeof t>"u")return 0;var r=Math.sqrt,o=0,s,u,p=0,d=0,P=0,w=0,C=t.length;if(C<2)return 0;for(e&&(t[C]=t[0],C++);--C;)s=t[C],p=s.X,d=s.Y,u=t[C-1],P=u.X,w=u.Y,o+=r((p-P)*(p-P)+(d-w)*(d-w));return e&&t.pop(),o/n},i.JS.PerimeterOfPaths=function(t,e,n){n||(n=1);for(var r=0,o=0;o<t.length;o++)r+=i.JS.PerimeterOfPath(t[o],e,n);return r},i.JS.ScaleDownPath=function(t,e){var n,r;for(e||(e=1),n=t.length;n--;)r=t[n],r.X=r.X/e,r.Y=r.Y/e},i.JS.ScaleDownPaths=function(t,e){var n,r,o;for(e||(e=1),n=t.length;n--;)for(r=t[n].length;r--;)o=t[n][r],o.X=o.X/e,o.Y=o.Y/e},i.JS.ScaleUpPath=function(t,e){var n,r,o=Math.round;for(e||(e=1),n=t.length;n--;)r=t[n],r.X=o(r.X*e),r.Y=o(r.Y*e)},i.JS.ScaleUpPaths=function(t,e){var n,r,o,s=Math.round;for(e||(e=1),n=t.length;n--;)for(r=t[n].length;r--;)o=t[n][r],o.X=s(o.X*e),o.Y=s(o.Y*e)},i.ExPolygons=function(){return[]},i.ExPolygon=function(){this.outer=null,this.holes=null},i.JS.AddOuterPolyNodeToExPolygons=function(t,e){var n=new i.ExPolygon;n.outer=t.Contour();var r=t.Childs(),o=r.length;n.holes=new Array(o);var s,u,p,d,P,w;for(p=0;p<o;p++)for(s=r[p],n.holes[p]=s.Contour(),d=0,P=s.Childs(),w=P.length;d<w;d++)u=P[d],i.JS.AddOuterPolyNodeToExPolygons(u,e);e.push(n)},i.JS.ExPolygonsToPaths=function(t){var e,n,r,o,s=new i.Paths;for(e=0,r=t.length;e<r;e++)for(s.push(t[e].outer),n=0,o=t[e].holes.length;n<o;n++)s.push(t[e].holes[n]);return s},i.JS.PolyTreeToExPolygons=function(t){var e=new i.ExPolygons,n,r,o,s;for(r=0,o=t.Childs(),s=o.length;r<s;r++)n=o[r],i.JS.AddOuterPolyNodeToExPolygons(n,e);return e}})()});var j=rr(oi(),1),ve=6378137,Te=1/298.257223563,re=Te*(2-Te),si=ve*(1-Te),ge=i=>i*Math.PI/180,li=i=>i*180/Math.PI,Xt=1e3,wt=1e-8,it=(i,l)=>Math.hypot(i[0]-l[0],i[1]-l[1]),Vt=i=>i.slice(1).reduce((l,a,h)=>l+it(i[h],a),0),ne=(i,l)=>i[0]*l[1]-i[1]*l[0],Yt=i=>i.reduce((l,a,h)=>l+ne(a,i[(h+1)%i.length]),0)/2,Rt=i=>Math.abs(i.reduce((l,a)=>l+Yt(a),0)),Gt=i=>i.map(([l,a])=>({X:Math.round(l*Xt),Y:Math.round(a*Xt)})),Le=i=>i.map(l=>[l.X/Xt,l.Y/Xt]);function Ee(i,l=!0){let a=i.map(h=>[...h]);return Yt(a)>0!==l&&a.reverse(),a}function vt(i){if(!Array.isArray(i)||i.length<2||!Number.isFinite(i[0])||Math.abs(i[0])>180||!Number.isFinite(i[1])||Math.abs(i[1])>85)throw new Error("Use WGS 84 longitude, latitude coordinates between 85\xB0 south and north.");return i.slice(0,2)}function be(i){let[l,a]=vt(i).map(ge),h=ve/Math.sqrt(1-re*Math.sin(a)**2);return[h*Math.cos(a)*Math.cos(l),h*Math.cos(a)*Math.sin(l),h*(1-re)*Math.sin(a)]}function Pe(i,l){let[a,h]=vt(i).map(ge),f=be(i),m=be(l).map((v,y)=>v-f[y]);if(Math.hypot(...m)>5e3)throw new Error("Keep each site within 5 km of its map origin. Split a larger job into sites.");return[-Math.sin(a)*m[0]+Math.cos(a)*m[1],-Math.sin(h)*Math.cos(a)*m[0]-Math.sin(h)*Math.sin(a)*m[1]+Math.cos(h)*m[2]]}function St(i,l){let[a,h]=vt(i).map(ge),[f,m]=l,v=be(i);if(!l.every(Number.isFinite)||Math.hypot(f,m)>5e3)throw new Error("A site coordinate is outside the supported local map.");let y=v[0]-Math.sin(a)*f-Math.sin(h)*Math.cos(a)*m,c=v[1]+Math.cos(a)*f-Math.sin(h)*Math.sin(a)*m,x=v[2]+Math.cos(h)*m,N=Math.hypot(y,c),O=Math.atan2(x*ve,N*si),I=li(Math.atan2(c,y)),b=li(Math.atan2(x+re/(1-re)*si*Math.sin(O)**3,N-re*ve*Math.cos(O)**3));return vt([I===180?-180:I,b])}function zt(i){let l=i.flat();if(!l.length)return{min:[0,0],max:[1,1],size:[1,1]};let a=[0,1].map(f=>Math.min(...l.map(m=>m[f]))),h=[0,1].map(f=>Math.max(...l.map(m=>m[f])));return{min:a,max:h,size:h.map((f,m)=>f-a[m])}}function ui(i,l,a,h){let f=l.map((N,O)=>N-i[O]),m=h.map((N,O)=>N-a[O]),v=a.map((N,O)=>N-i[O]),y=ne(f,m);if(Math.abs(y)<wt){if(Math.abs(ne(v,f))>wt)return[];let N=Math.abs(f[0])>Math.abs(f[1])?0:1;return Math.abs(f[N])<wt?[]:[a,h].map(O=>(O[N]-i[N])/f[N]).filter(O=>O>=-wt&&O<=1+wt)}let c=ne(v,m)/y,x=ne(v,f)/y;return c>=-wt&&c<=1+wt&&x>=-wt&&x<=1+wt?[Math.max(0,Math.min(1,c))]:[]}function Ne(i,l="Boundary"){if(!Array.isArray(i))throw new Error(l+" needs polygon vertices.");let a=i.map(h=>{if(!Array.isArray(h)||h.length!==2||!h.every(Number.isFinite)||Math.hypot(...h)>5e3)throw new Error(l+" has an invalid local coordinate.");return[...h]});if(a.length>3&&it(a[0],a.at(-1))<.001&&a.pop(),a.length<3||a.length>128||Math.abs(Yt(a))<1)throw new Error(l+" needs 3\u2013128 vertices and at least one square meter.");for(let h=0;h<a.length;h++){if(it(a[h],a[(h+1)%a.length])<.01)throw new Error(l+" has duplicate or nearly identical vertices.");for(let f=h+1;f<a.length;f++)if(!(f===h+1||h===0&&f===a.length-1)&&ui(a[h],a[(h+1)%a.length],a[f],a[(f+1)%a.length]).length)throw new Error(l+" crosses itself. Move the crossing vertices.")}return Ee(a)}function Oe(i,l,a){if(!i.length)return[];let h=new j.default.Clipper;h.StrictlySimple=!0,h.AddPaths(i.map(Gt),j.default.PolyType.ptSubject,!0),l.length&&h.AddPaths(l.map(Gt),j.default.PolyType.ptClip,!0);let f=new j.default.Paths;return h.Execute(a,f,j.default.PolyFillType.pftNonZero,j.default.PolyFillType.pftNonZero),f.map(Le).filter(m=>m.length>=3&&Math.abs(Yt(m))>1e-6)}var At=i=>Oe(i,[],j.default.ClipType.ctUnion),se=(i,l)=>Oe(i,l,j.default.ClipType.ctDifference),le=(i,l)=>l.length?Oe(i,l,j.default.ClipType.ctIntersection):[];function ai(i,l){if(Math.abs(l)<1e-4)return i.map(f=>f.map(m=>[...m]));let a=new j.default.ClipperOffset(2,.02*Xt),h=new j.default.Paths;return a.AddPaths(i.map(Gt),j.default.JoinType.jtMiter,j.default.EndType.etClosedPolygon),a.Execute(h,l*Xt),h.map(Le)}function xe(i,l,a){return se(ai(At(i),-a),ai(At(l),a))}function at(i,l){let a={X:Math.round(l[0]*Xt),Y:Math.round(l[1]*Xt)},h=!1;for(let f of i){let m=j.default.Clipper.PointInPolygon(a,Gt(f));if(m===-1)return!0;m===1&&(h=!h)}return h}function oe(i,l,a){if(!at(i,l)||!at(i,a))return!1;let h=[0,1];for(let f of i)for(let m=0;m<f.length;m++)h.push(...ui(l,a,f[m],f[(m+1)%f.length]));h.sort((f,m)=>f-m);for(let f=1;f<h.length;f++){let m=(h[f-1]+h[f])/2;if(!at(i,l.map((v,y)=>v+(a[y]-v)*m)))return!1}return!0}function hi(i,l,a){if(!i.length)return[];if(!Number.isFinite(l)||l<.5)throw new Error("Flight lines must be at least 0.5 m apart.");let h=ge(a),f=[Math.cos(h),Math.sin(h)],m=[-f[1],f[0]],v=(_,D)=>_[0]*D[0]+_[1]*D[1],y=i.flat(),c=Math.min(...y.map(_=>v(_,m))),x=Math.max(...y.map(_=>v(_,m))),N=Math.min(...y.map(_=>v(_,f)))-1,O=Math.max(...y.map(_=>v(_,f)))+1,I=Math.max(1,Math.ceil((x-c)/l));if(I>1e3)throw new Error("This requires more than 1,000 flight lines. Split the site or revise capture requirements.");let b=[];for(let _=0;_<I;_++){let D=c+(_+.5)*(x-c)/I,Y=H=>f.map((F,X)=>F*H+m[X]*D),L=new j.default.Clipper,Z=new j.default.PolyTree;L.AddPath(Gt([Y(N),Y(O)]),j.default.PolyType.ptSubject,!1),L.AddPaths(i.map(Gt),j.default.PolyType.ptClip,!0),L.Execute(j.default.ClipType.ctIntersection,Z,j.default.PolyFillType.pftNonZero,j.default.PolyFillType.pftNonZero);let ot=j.default.Clipper.OpenPathsFromPolyTree(Z).map(Le).map(H=>H.sort((F,X)=>v(F,f)-v(X,f))).filter(H=>Vt(H)>.1).sort((H,F)=>v(H[0],f)-v(F[0],f));_%2&&(ot.reverse(),ot.forEach(H=>H.reverse()));for(let H of ot)b.push({row:_,a:H[0],b:H.at(-1),length:it(H[0],H.at(-1))})}return b}function fi(i){let l=new Set,a=i.flat().filter(f=>{let m=f.join(",");return l.has(m)?!1:(l.add(m),!0)});if(a.length>350)throw new Error("Simplify the boundary/exclusions to fewer than 350 offset corners before routing.");let h=a.map(()=>[]);for(let f=0;f<a.length;f++)for(let m=f+1;m<a.length;m++)if(oe(i,a[f],a[m])){let v=it(a[f],a[m]);h[f].push([m,v]),h[m].push([f,v])}return(f,m)=>{if(oe(i,f,m))return[f,m];if(!at(i,f)||!at(i,m))return null;let v=a.length,y=[...a,f,m],c=h.map(I=>[...I]);c.push([],[]);for(let I=v;I<v+2;I++)for(let b=0;b<v;b++)if(oe(i,y[b],y[I])){let _=it(y[b],y[I]);c[b].push([I,_]),c[I].push([b,_])}let x=new Float64Array(v+2).fill(1/0),N=new Int32Array(v+2).fill(-1),O=new Uint8Array(v+2);x[v]=0;for(let I=0;I<v+2;I++){let b=-1;for(let _=0;_<v+2;_++)!O[_]&&(b===-1||x[_]<x[b])&&(b=_);if(b===-1||!Number.isFinite(x[b]))return null;if(b===v+1){let _=[];for(let D=b;D!==-1;D=N[D])_.push(y[D]);return _.reverse()}O[b]=1;for(let[_,D]of c[b])x[b]+D<x[_]&&(x[_]=x[b]+D,N[_]=b)}return null}}function pi(i,l){if(i?.crs)throw new Error("Export the boundary as standard WGS 84 GeoJSON without a custom CRS.");let a=[],h=[];function f(y,c="Imported area",x=0,N=null){if(!y||x>8)throw new Error("Invalid GeoJSON geometry.");if(y.crs)throw new Error("Use standard WGS 84 GeoJSON without a custom CRS.");if(y.type==="FeatureCollection"){if(!Array.isArray(y.features)||y.features.length>32)throw new Error("Import at most 32 site features.");for(let O of y.features)f(O,c,x+1)}else if(y.type==="Feature")f(y.geometry,String(y.properties?.name||c).slice(0,100),x+1,["boundary","exclusion"].includes(y.properties?.kind)?y.properties.kind:N);else if(y.type==="Polygon")a.push({name:c,kind:N,coordinates:y.coordinates});else if(y.type==="MultiPolygon"){if(!Array.isArray(y.coordinates)||y.coordinates.length>32)throw new Error("Import at most 32 polygons.");for(let O of y.coordinates)a.push({name:c,kind:N,coordinates:O})}else if(y.type==="Point")h.push({name:c,coordinate:vt(y.coordinates)});else throw new Error("Import polygon boundaries and optional point markers. Lines and geometry collections need conversion first.")}if(f(i),!a.length&&!h.length)throw new Error("No site geometry was found.");if(a.length+h.length>32)throw new Error("Import at most 32 polygons and markers.");let m=vt(l||a[0]?.coordinates?.[0]?.[0]||h[0].coordinate),v=a.map(({name:y,kind:c,coordinates:x})=>{if(!Array.isArray(x)||!x.length||x.length>21)throw new Error("Invalid polygon rings.");let N=x.map((I,b)=>{if(!Array.isArray(I)||I.length<4||it(vt(I[0]),vt(I.at(-1)))>wt)throw new Error("GeoJSON polygon rings must be closed.");return Ne(I.map(_=>Pe(m,vt(_))),y+(b?" hole":""))}),O=N.slice(1);for(let I=0;I<O.length;I++){if(Rt(se([O[I]],[N[0]]))>.01)throw new Error(y+" has a hole outside its boundary.");if(O.slice(0,I).some(b=>Rt(le([b],[O[I]]))>.01))throw new Error(y+" has overlapping holes.")}return{name:y,kind:c,boundary:N[0],holes:O}});return{origin:m,areas:v,points:h.map(y=>({name:y.name,point:Pe(m,y.coordinate)}))}}var Bt="Level ground at takeoff elevation; a nadir camera aligned with each survey run. Geometry and nominal time only: terrain, obstacles, airspace, wind, positioning error and aircraft dynamics are not verified.",Pt=i=>JSON.parse(JSON.stringify(i)),Mt=(i,l,a=120)=>{if(typeof i!="string"||!i.trim()||i.length>a)throw new Error(l+" must be a nonempty text of at most "+a+" characters.");return i},Tt=(i,l,a,h)=>{if(!Number.isFinite(i)||i<a||i>h)throw new Error(`${l} must be between ${a} and ${h}.`);return i};function di(i,l){if(!Array.isArray(i)||i.length!==2||!i.every(Number.isFinite)||Math.hypot(...i)>5e3)throw new Error(l+" needs an east/north coordinate within 5 km.");return[...i]}function Dt(i){if(!i||new TextEncoder().encode(JSON.stringify(i)).length>8e6||i.schema!=="vector/2")throw new Error("Open a Vector 2 project smaller than 8 MB.");let l=Pt(i);if(Mt(l.id,"Project ID"),Mt(l.title,"Title"),Mt(l.brief,"Brief",4e3),l.origin=vt(l.origin),l.home=di(l.home,"Takeoff"),!Array.isArray(l.areas)||!l.areas.length||l.areas.length>32)throw new Error("Use 1\u201332 named boundaries and exclusions.");let a=new Set,h=0;for(let y of l.areas){if(Mt(y.id,"Area ID"),a.has(y.id))throw new Error("Area IDs must be unique.");if(a.add(y.id),Mt(y.name,"Area name"),!["boundary","exclusion"].includes(y.kind)||typeof y.locked!="boolean")throw new Error("Each area needs a boundary/exclusion kind and a lock state.");y.ring=Ne(y.ring,y.name),h+=y.ring.length}if(h>200||!l.areas.some(y=>y.kind==="boundary"))throw new Error("Use at least one boundary and at most 200 total vertices.");let f=[l.home,...l.areas.flatMap(y=>y.ring)].map(y=>St(l.origin,y)[0]);if(Math.max(...f)-Math.min(...f)>180)throw new Error("Split a site crossing the 180\xB0 meridian before planning; this exporter does not cut antimeridian polygons.");let m=l.camera,v=l.settings;if(!m||!v)throw new Error("Camera and planning settings are required.");Mt(m.name,"Camera name");for(let y of["sensorWidth","sensorHeight","focalLength"])Tt(m[y],"Camera "+y+" (mm)",1,100);for(let y of["imageWidth","imageHeight"])if(!Number.isInteger(Tt(m[y],y+" (pixels)",100,3e4)))throw new Error("Image dimensions must be whole pixels.");Tt(m.minInterval,"Minimum capture interval (s)",.05,60);for(let[y,c,x]of[["height",5,500],["speed",.2,30],["angle",0,179.9],["frontOverlap",0,.95],["sideOverlap",0,.95],["margin",0,100],["usableMinutes",1,120],["reservePercent",0,80],["climbSpeed",.2,10],["descentSpeed",.2,10],["turnSeconds",0,60]])Tt(v[y],y,c,x);if(l.log!=null){if(Mt(l.log.name,"Flight file name",240),Mt(l.log.sha256,"Flight source hash",64),!/^[a-f0-9]{64}$/.test(l.log.sha256)||!l.log.mapping||!Array.isArray(l.log.records)||l.log.records.length<2||l.log.records.length>12e3)throw new Error("Flight records or provenance are invalid.");if(typeof l.log.raw!="string"||new TextEncoder().encode(l.log.raw).length>3e6)throw new Error("Keep the original UTF-8 CSV, up to 3 MB, with its recorded flight.");if(l.log.maxGap!=null&&Tt(l.log.maxGap,"Track continuity limit (seconds)",.1,120),l.log.comparisonSortie!=null&&(!Number.isInteger(l.log.comparisonSortie)||l.log.comparisonSortie<1||l.log.comparisonSortie>80))throw new Error("Choose a valid comparison sortie.");let y=-1;for(let c of l.log.records){if(Tt(c.time,"Flight elapsed seconds",0,172800),c.time<=y)throw new Error("Flight timestamps must be strictly increasing.");if(y=c.time,c.point=di(c.point,"Flight record"),c.altitude!==null&&Tt(c.altitude,"Flight altitude (m)",-1e3,1e4),c.battery!==null&&Tt(c.battery,"Recorded battery (%)",0,100),c.heading!==null&&Tt(c.heading,"Recorded heading (degrees)",0,360),![null,!0,!1].includes(c.capture))throw new Error("Capture events must be true, false or unknown.");if(typeof c.breakBefore!="boolean"||!Number.isInteger(c.sourceRow)||c.sourceRow<2)throw new Error("Keep flight row provenance and track breaks.")}if(l.log.records.filter(c=>c.capture).length>3e3)throw new Error("Use at most 3,000 recorded capture events.")}return l}function ae(i,l,a,h){let f=l*Math.PI/180,m=[Math.cos(f),Math.sin(f)],v=[-m[1],m[0]];return Ee([[-1,-1],[1,-1],[1,1],[-1,1]].map(([y,c])=>i.map((x,N)=>x+m[N]*y*h/2+v[N]*c*a/2)))}function Xe(i,l=i.settings.height){let a=i.camera,h=l*a.sensorWidth/a.focalLength,f=l*a.sensorHeight/a.focalLength;return{width:h,along:f,gsdX:h/a.imageWidth*100,gsdY:f/a.imageHeight*100,lineSpacing:h*(1-i.settings.sideOverlap),photoSpacing:f*(1-i.settings.frontOverlap)}}function Ae(i,{coverage:l=!0}={}){let a=Dt(i),h=a.settings,f=Xe(a),m=a.areas.filter(E=>E.kind==="boundary").map(E=>E.ring),v=a.areas.filter(E=>E.kind==="exclusion").map(E=>E.ring),y=se(At(m),At(v)),c=xe(m,v,h.margin),x=Rt(y);if(x<1||!c.length)throw new Error("The boundary and margin leave no survey area.");if(!at(c,a.home))throw new Error("Move takeoff inside the inset boundary and outside expanded exclusions.");let N=fi(c),O=hi(c,f.lineSpacing,h.angle),I=[],b=[];if(!O.length)throw new Error("No survey runs fit inside the flight area.");for(let E of O){let R=Math.max(1,Math.ceil(E.length/f.photoSpacing)),Q=E.length/R;if(b.length+R>3e3)throw new Error("This plan exceeds 3,000 photos. Split the site or revise capture requirements.");if(R>1&&Q/h.speed+1e-8<a.camera.minInterval)throw new Error(`The camera cannot capture this fast. Reduce speed to at most ${(Q/a.camera.minInterval).toFixed(2)} m/s, raise height, or change capture requirements.`);let st=Math.atan2(E.b[1]-E.a[1],E.b[0]-E.a[0])*180/Math.PI,mt=Array.from({length:R},(kt,_t)=>({id:b.length+_t+1,point:E.a.map((yt,Ot)=>yt+(E.b[Ot]-yt)*(_t+.5)/R),heading:st,run:I.length+1}));b.push(...mt),I.push({id:I.length+1,row:E.row,photos:mt,spacing:Q,heading:st})}let _=h.usableMinutes*60*(1-h.reservePercent/100);if(h.height/h.climbSpeed+h.height/h.descentSpeed>=_)throw new Error("Climb and descent consume the whole time budget. Revise the plan.");let Y=[],L=null,Z=new Map;function ot(E){if(!Z.has(E.id)){let R=N(E.point,a.home);if(!R)throw new Error(`Photo ${E.id} is in an area disconnected from takeoff. Split the site or move takeoff.`);Z.set(E.id,R)}return Z.get(E.id)}function H(){L={id:Y.length+1,path:[[...a.home]],legs:[],photos:[],seconds:h.height/h.climbSpeed,distance:0,lastCapture:-1/0}}function F(E,R,Q=Vt(E)/h.speed){L.legs.push({kind:R,points:E.map(st=>[...st]),start:L.seconds,seconds:Q}),L.path.push(...E.slice(1)),L.distance+=Vt(E),L.seconds+=Q}function X(){if(L?.photos.length&&(F(ot(L.photos.at(-1)),"return"),L.seconds+=h.height/h.descentSpeed,L.remainingSeconds=_-L.seconds,delete L.lastCapture,Y.push(L),L=null,Y.length>80))throw new Error("This plan needs more than 80 sorties. Split the job or revise the time budget.")}H();for(let E of I){let R=0;for(;R<E.photos.length;){let Q=E.photos[R],st=L.path.at(-1),mt=N(st,Q.point);if(!mt)throw new Error(`Survey run ${E.id} is disconnected from takeoff. Split the site.`);let kt=L.seconds+Vt(mt)/h.speed,_t=Math.max(h.turnSeconds,a.camera.minInterval-(kt-L.lastCapture),0),yt=R-1;for(let ft=R;ft<E.photos.length;ft++){let me=E.photos[ft];if(kt+_t+it(Q.point,me.point)/h.speed+Vt(ot(me))/h.speed+h.height/h.descentSpeed<=_+1e-7)yt=ft;else break}if(yt<R){if(!L.photos.length)throw new Error(`Photo ${Q.id} cannot fit a return trip within the time budget. Move takeoff, increase usable time, or split the site.`);X(),H();continue}F(mt,"transit"),F([Q.point],"settle",_t);let Ot=E.photos.slice(R,yt+1),ee=L.seconds;for(let ft of Ot)ft.sortie=L.id,ft.time=ee+it(Q.point,ft.point)/h.speed,L.photos.push(ft);F(Ot.map(ft=>ft.point),"survey"),L.lastCapture=L.photos.at(-1).time,R=yt+1,R<E.photos.length&&(X(),H())}}X();let G=l?At(b.map(E=>ae(E.point,E.heading,f.width,f.along))):[],et=l?le(y,G):[],ct=l?se(y,G):[];return{project:a,assumptions:Bt,target:y,region:c,area:x,camera:f,runs:I,photos:b,sorties:Y,covered:et,gaps:ct,coverage:l?Math.min(1,Rt(et)/x):null,totalDistance:Y.reduce((E,R)=>E+R.distance,0),totalSeconds:Y.reduce((E,R)=>E+R.seconds,0),budgetSeconds:_}}function Ce(i){let l=[Pt(i)],a=0;return{get value(){return Pt(l[a])},get canUndo(){return a>0},get canRedo(){return a<l.length-1},push(h){let f=Dt(h);return l=[...l.slice(0,a+1),f].slice(-40),a=l.length-1,this.value},undo(){return a>0&&a--,this.value},redo(){return a<l.length-1&&a++,this.value}}}function Ye(i){if(typeof i!="string"||new TextEncoder().encode(i).length>3e6)throw new Error("Use a UTF-8 CSV smaller than 3 MB.");i=i.replace(/^\uFEFF/,"");let l=[],a=[],h="",f=!1,m=!1;for(let y=0;y<=i.length;y++){let c=i[y];if(f){if(c===void 0)throw new Error("The CSV has an unclosed quote.");c==='"'?i[y+1]==='"'?(h+='"',y++):(f=!1,m=!0):h+=c}else if(c==='"'){if(h.length||m)throw new Error("A CSV quote is in the wrong position.");f=!0}else if(c===","||c===`+`||c==="\r"||c===void 0){if(a.push(h),h="",m=!1,a.length>80)throw new Error("Use a CSV with at most 80 columns.");c!==","&&(a.some(x=>x.trim())&&l.push(a),a=[],c==="\r"&&i[y+1]===`+`&&y++)}else{if(m)throw new Error("Unexpected content after a quoted CSV field.");h+=c}if(l.length>12001)throw new Error("Use at most 12,000 recorded samples.")}let v=l.shift()?.map(y=>y.trim());if(!v?.length||v.some(y=>!y)||new Set(v).size!==v.length)throw new Error("CSV column names must be present and unique.");if(l.length<2||l.some(y=>y.length!==v.length))throw new Error("Use at least two data rows, with the same columns as the header.");return{headers:v,rows:l}}async function Me(i,l,a,h){let f=Ye(i),m=["time","latitude","longitude"];for(let _ of m)if(!f.headers.includes(a[_]))throw new Error("Choose a "+_+" column.");for(let _ of["altitude","battery","heading","capture"])if(a[_]&&!f.headers.includes(a[_]))throw new Error("Unknown "+_+" column.");if(!["seconds","milliseconds","iso"].includes(a.timeUnit))throw new Error("Choose elapsed seconds, elapsed milliseconds or ISO 8601 with timezone.");if(a.altitude&&(!["meters","feet"].includes(a.altitudeUnit)||!["takeoff","amsl"].includes(a.altitudeReference)))throw new Error("Choose altitude units and reference.");if(a.altitudeReference==="amsl"&&(!Number.isFinite(a.homeElevation)||a.homeElevation<-500||a.homeElevation>9e3))throw new Error("Provide takeoff elevation in meters AMSL to convert the log.");let v=Object.fromEntries(Object.entries(a).map(([_,D])=>[_,f.headers.indexOf(D)])),y=[],c=null,x=-1/0,N=0,O=!1,I=(_,D,Y=!1)=>{if(!_?.trim()){if(Y)throw new Error(D+" is missing.");return null}let L=Number(_);if(!Number.isFinite(L))throw new Error(D+" is not a finite number.");return L};for(let _=0;_<f.rows.length;_++){let D=f.rows[_],Y=E=>v[E]<0?"":D[v[E]],L="CSV row "+(_+2),Z;if(a.timeUnit==="iso"){let E=Y("time"),R=E?.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$/);if(!R||!Number.isFinite(Date.parse(E)))throw new Error(L+": use ISO 8601 timestamps with an explicit timezone.");let[Q,st,mt,kt,_t,yt]=R.slice(1,7).map(Number),Ot=Q%4===0&&(Q%100!==0||Q%400===0),ee=[31,Ot?29:28,31,30,31,30,31,31,30,31,30,31];if(st<1||st>12||mt<1||mt>ee[st-1]||kt>23||_t>59||yt>59)throw new Error(L+": the timestamp is not a valid calendar date and time.");Z=Date.parse(E)/1e3}else Z=I(Y("time"),L+" time",!0)/(a.timeUnit==="milliseconds"?1e3:1);if(Z<=x)throw new Error(L+": timestamps must be strictly increasing. Split repeated flights before importing.");if(x=Z,c===null&&(c=Z),Z-c>172800)throw new Error("A flight log must span no more than 48 hours.");let ot=I(Y("latitude"),L+" latitude"),H=I(Y("longitude"),L+" longitude");if(ot===null||H===null){N++,O=!0;continue}let F=Pe(h,[H,ot]),X=I(Y("altitude"),L+" altitude"),G=I(Y("battery"),L+" battery"),et=I(Y("heading"),L+" heading"),ct=null;if(X!==null&&(X*=a.altitudeUnit==="feet"?.3048:1,a.altitudeReference==="amsl"&&(X-=a.homeElevation),X<-1e3||X>1e4))throw new Error(L+": altitude is outside the supported range.");if(G!==null&&(G<0||G>100))throw new Error(L+": battery must be a percentage from 0 to 100.");if(et!==null&&(et<0||et>360))throw new Error(L+": heading must be degrees clockwise from north, 0\u2013360.");if(Y("capture")?.trim()){let E=Y("capture").trim().toLowerCase();if(["1","true","yes"].includes(E))ct=!0;else if(["0","false","no"].includes(E))ct=!1;else throw new Error(L+": capture events must be 1/0, true/false, yes/no, or blank for unknown.")}y.push({time:Z-c,point:F,altitude:X,battery:G,heading:et,capture:ct,sourceRow:_+2,breakBefore:O}),O=!1}if(y.length<2)throw new Error("At least two rows need valid coordinates.");if(y.filter(_=>_.capture).length>3e3)throw new Error("Use at most 3,000 recorded capture events per site.");let b=[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)))].map(_=>_.toString(16).padStart(2,"0")).join("");return{name:l,sha256:b,mapping:{...a},raw:i,sourceRows:f.rows.length,missingCoordinates:N,startTime:a.timeUnit==="iso"?new Date(c*1e3).toISOString():null,records:y}}async function ci(i){if(!i.log)return;let l=i.log,a=await Me(l.raw,l.name,l.mapping,i.origin);for(let h of["sha256","sourceRows","missingCoordinates","startTime"])if(JSON.stringify(l[h])!==JSON.stringify(a[h]))throw new Error("Recorded "+h+" differs from the retained CSV and mapping. Reimport the original flight instead of editing evidence.");if(l.records.length!==a.records.length)throw new Error("Recorded samples differ from the retained CSV.");for(let h=0;h<l.records.length;h++){let f=l.records[h],m=a.records[h];if(it(f.point,m.point)>1e-5||["time","altitude","battery","heading","capture","sourceRow","breakBefore"].some(v=>f[v]!==m[v]))throw new Error("Recorded samples differ from the retained CSV and mapping. Reimport the original flight instead of editing evidence.")}}function Kt(i,l=i.project.log,a=l?.maxGap??10){if(!l)return null;if(!Number.isFinite(a)||a<.1||a>120)throw new Error("Choose a continuity limit between 0.1 and 120 seconds.");let h=i.project,f=l.records,m=[],v=[],y=0,c=0,x=0,N=l.comparisonSortie?i.sorties.filter(F=>F.id===l.comparisonSortie):i.sorties;if(!N.length)throw new Error("The recorded flight refers to a sortie this revision no longer has. Choose the comparison again.");let O=N.flatMap(F=>F.path.slice(1).map((X,G)=>[F.path[G],X]));function I(F,X,G){let et=G[0]-X[0],ct=G[1]-X[1],E=et*et+ct*ct,R=E?Math.max(0,Math.min(1,((F[0]-X[0])*et+(F[1]-X[1])*ct)/E)):0;return it(F,[X[0]+R*et,X[1]+R*ct])}let b=f.map(F=>Math.min(...O.map(([X,G])=>I(F.point,X,G)))).sort((F,X)=>F-X),_=0,D=0,Y=0,L=0,Z=[];for(let F=0;F<f.length;F++){let X=f[F],G=f[F-1];if(at(i.region,X.point)||_++,G&&(X.breakBefore||X.time-G.time>a)?(v.length&&m.push(v),v=[],c++):G&&(y+=it(G.point,X.point),oe(i.region,G.point,X.point)||x++),v.push(X.point),X.capture===null&&L++,X.capture===!0){if(D++,!(X.altitude>0)||X.heading===null){Y++;continue}let et=Xe(h,X.altitude);Z.push(ae(X.point,90-X.heading,et.width,et.along))}}v.length&&m.push(v);let ot=Z.length?le(i.target,At(Z)):[],H=f.filter(F=>F.battery!==null);return{paths:m,measuredDistance:y,elapsedSeconds:f.at(-1).time-f[0].time,outsideSamples:_,outsideSegments:x,discontinuities:c,missingCoordinates:l.missingCoordinates??0,captureEvents:D,unmodeledCaptures:Y,unknownCaptureSamples:L,modeledCaptures:Z.length,covered:ot,coverage:Z.length?Math.min(1,Rt(ot)/i.area):null,startBattery:H[0]?.battery??null,endBattery:H.at(-1)?.battery??null,maxGap:a,comparisonSortie:l.comparisonSortie??null,deviationP95:b[Math.min(b.length-1,Math.floor(b.length*.95))],deviationMax:b.at(-1),interpretation:"Recorded event footprints are estimates from logged position, altitude and heading plus the current camera and level-ground/nadir assumptions. They do not establish that images exist, are sharp or form a usable map. Track gaps are not connected."}}var z=i=>String(i).replace(/[&<>"']/g,l=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[l]),bt=i=>String(i).normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,70)||"survey",or=i=>{let l=String(i??"");return/[",\r\n]/.test(l)?'"'+l.replace(/"/g,'""')+'"':l},Be=i=>i.map(l=>l.map(or).join(",")).join(`\r+`)+`\r+`,K=(i,l=3)=>Number(i.toFixed(l));function we(i,l){let a=l.filter(v=>Yt(v)>0),h=l.filter(v=>Yt(v)<0),f=v=>[...v,v[0]].map(y=>St(i,y).map(c=>K(c,9))),m=h.map(v=>a.map((y,c)=>({i:c,area:Math.abs(Yt(y)),contains:at([y],v[0])})).filter(y=>y.contains).sort((y,c)=>y.area-c.area)[0]?.i);return{type:"MultiPolygon",coordinates:a.map((v,y)=>[f(v),...h.filter((c,x)=>m[x]===y).map(f)])}}function De(i){let l=zt(i.project.areas.map(x=>x.ring)),a=940,h=540,f=Math.min((a-100)/l.size[0],(h-100)/l.size[1]),m=x=>50+(x[0]-l.min[0])*f,v=x=>h-50-(x[1]-l.min[1])*f,y=x=>x.map((N,O)=>(O?"L":"M")+m(N).toFixed(2)+" "+v(N).toFixed(2)).join(" "),c=Kt(i);return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${a} ${h}" role="img" aria-label="Survey plan and recorded track" style="width:100%;height:auto;background:#f0f3e8;border-radius:8px"><title>${z(i.project.title)}</title>${i.project.areas.map(x=>`<path d="${y(x.ring)}Z" fill="${x.kind==="exclusion"?"#e7d4c1":"#d8e3c7"}" stroke="${x.kind==="exclusion"?"#b78869":"#8fA579"}" stroke-width="1.5"/>`).join("")}${i.sorties.map(x=>`<path d="${y(x.path)}" fill="none" stroke="#c26d43" stroke-width="1.25"/>`).join("")}${c?c.paths.map(x=>`<path d="${y(x)}" fill="none" stroke="#267d81" stroke-width="2.5"/>`).join(""):""}<circle cx="${m(i.project.home)}" cy="${v(i.project.home)}" r="7" fill="#28462e" stroke="white" stroke-width="2"/><text x="${m(i.project.home)+12}" y="${v(i.project.home)+4}" fill="#28462e" font-family="system-ui" font-size="11">Takeoff</text><text x="${a-40}" y="35" font-family="system-ui" font-size="17" fill="#7a8b6c">N \u2191</text><text x="24" y="${h-16}" font-family="system-ui" font-size="11" fill="#68775a">Orange: planned routes${c?" \xB7 Teal: recorded track (gaps unconnected)":""} \xB7 Level-ground model</text></svg>`}function ke(i){let l=i.project,a=v=>St(l.origin,v).map(y=>K(y,9)),h=(v,y,c,x={})=>({type:"Feature",properties:{name:v,kind:y,...x},geometry:c}),f=l.areas.map(v=>h(v.name,v.kind,{type:"Polygon",coordinates:[[...v.ring,v.ring[0]].map(a)]},{id:v.id,locked:v.locked}));f.push(h("Takeoff","takeoff",{type:"Point",coordinates:a(l.home)})),f.push(h("Inset flight region","flight-region",we(l.origin,i.region))),f.push(h("Nominal image coverage","planned-footprints",we(l.origin,i.covered))),f.push(h("Nominal coverage gaps","planned-gaps",we(l.origin,i.gaps)));for(let v of i.sorties)f.push(h("Sortie "+v.id,"planned-route",{type:"LineString",coordinates:v.path.map(a)},{sortie:v.id,heightAboveTakeoffM:l.settings.height,nominalSeconds:K(v.seconds)}));for(let v of i.photos)f.push(h("Photo "+v.id,"planned-photo",{type:"Point",coordinates:a(v.point)},{photo:v.id,sortie:v.sortie,run:v.run,secondsAfterTakeoff:K(v.time),heightAboveTakeoffM:l.settings.height,headingDegreesFromNorth:K((90-v.heading+360)%360)}));let m=Kt(i);if(m){for(let[v,y]of m.paths.entries())y.length>1&&f.push(h("Recorded track "+(v+1),"recorded-track",{type:"LineString",coordinates:y.map(a)},{source:l.log.name,sha256:l.log.sha256}));m.covered.length&&f.push(h("Estimated recorded-event footprints","recorded-footprints",we(l.origin,m.covered),{interpretation:m.interpretation}))}return{type:"FeatureCollection",name:l.title,assumptions:Bt,features:f}}function mi(i){let l=i.project;return Be([["photo","sortie","run","longitude_deg","latitude_deg","height_above_takeoff_m","heading_from_north_deg","nominal_elapsed_s"],...i.photos.map(a=>[a.id,a.sortie,a.run,...St(l.origin,a.point).map(h=>K(h,9)),l.settings.height,K((90-a.heading+360)%360),K(a.time)])])}function yi(i){let l=i.project,a=[["sortie","sequence","phase","longitude_deg","latitude_deg","height_above_takeoff_m","nominal_elapsed_s"]];for(let h of i.sorties){let f=0;for(let m of h.legs){let v=m.start;for(let y=0;y<m.points.length;y++)y&&(v+=Math.hypot(...m.points[y].map((c,x)=>c-m.points[y-1][x]))/l.settings.speed),a.push([h.id,++f,m.kind,...St(l.origin,m.points[y]).map(c=>K(c,9)),l.settings.height,K(v)])}}return Be(a)}function vi(i){return i.project.log?Be([["elapsed_s","longitude_deg","latitude_deg","height_above_takeoff_m","heading_from_north_deg","battery_percent","capture_event","break_before","source_row"],...i.project.log.records.map(l=>[l.time,...St(i.project.origin,l.point).map(a=>K(a,9)),l.altitude,l.heading,l.battery,l.capture===null?"":l.capture?1:0,l.breakBefore?1:0,l.sourceRow])]):null}function Fe(i){let l=i.project,a=f=>f.map(m=>St(l.origin,m).map(v=>K(v,9)).join(",")+",0").join(" "),h=f=>`<Placemark><name>${z(f.name)}</name><styleUrl>#${f.kind}</styleUrl><Polygon><altitudeMode>clampToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>${a([...f.ring,f.ring[0]])}</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>`;return`<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>${z(l.title)}</name><description>${z(Bt+" Map overlay only; all KML geometry is clamped to ground. Heights and photo timing are in the CSV files. This is not an aircraft mission file.")}</description><Style id="boundary"><LineStyle><color>ff5c794c</color><width>2</width></LineStyle><PolyStyle><color>334f7c5c</color></PolyStyle></Style><Style id="exclusion"><LineStyle><color>ff5353c2</color><width>2</width></LineStyle><PolyStyle><color>335353c2</color></PolyStyle></Style><Style id="route"><LineStyle><color>ff236cf0</color><width>2</width></LineStyle></Style>${l.areas.map(h).join("")}${i.sorties.map(f=>`<Placemark><name>Sortie ${f.id} \xB7 ${(f.seconds/60).toFixed(1)} nominal minutes</name><styleUrl>#route</styleUrl><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>${a(f.path)}</coordinates></LineString></Placemark>`).join("")}<Placemark><name>Takeoff</name><Point><coordinates>${a([l.home])}</coordinates></Point></Placemark></Document></kml>`}function $e(i){let l=Kt(i);return{schema:"vector-report/2",project:i.project.title,assumptions:Bt,siteAreaM2:K(i.area),camera:i.camera,nominalCoveragePercent:K(i.coverage*100),photos:i.photos.length,flightLines:i.runs.length,nominalDistanceM:K(i.totalDistance),nominalSeconds:K(i.totalSeconds),sortieBudgetSeconds:i.budgetSeconds,sorties:i.sorties.map(a=>({id:a.id,photos:a.photos.length,distanceM:K(a.distance),seconds:K(a.seconds),remainingBudgetSeconds:K(a.remainingSeconds)})),recorded:l?{...l,paths:void 0,covered:void 0,source:i.project.log.name,sourceSHA256:i.project.log.sha256,mapping:i.project.log.mapping}:null}}function Re(i){let l=$e(i),a=i.project,h=l.recorded,f=z;return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${f(a.title)} \xB7 survey report</title><style>body{font:16px/1.6 system-ui;max-width:950px;padding:40px;margin:auto;color:#21362c}h1{font-size:42px;line-height:1.1}small{color:#57655c}table{border-collapse:collapse;width:100%}td,th{padding:10px;text-align:left;border-bottom:1px solid #dce4dc}section{margin:32px 0}.cards{display:flex;gap:30px;flex-wrap:wrap}.cards b{display:block;font-size:27px}pre{white-space:pre-wrap;word-break:break-word;font:12px monospace}button{padding:10px 15px}@media print{button{display:none}body{padding:0;font-size:13px;line-height:1.5}h1{font-size:32px}h2{font-size:19px;break-after:avoid}section{margin:18px 0}p,pre,tr,.cards,svg{break-inside:avoid}td,th{padding:7px 8px}.cards{gap:23px}.cards b{font-size:23px}pre{font-size:10px}svg{max-height:265px}table{break-inside:avoid}}@page{margin:18mm;@bottom-right{content:"Vector \xB7 " counter(page);font:9px system-ui;color:#60715e}}</style><small>VECTOR / FIELD SURVEY REPORT</small><h1>${f(a.title)}</h1><p>${f(a.brief)}</p><button onclick="print()">Print / Save PDF</button><section>${De(i)}</section><section class="cards"><div><b>${(l.siteAreaM2/1e4).toFixed(2)} ha</b>Supplied target area</div><div><b>${l.nominalCoveragePercent.toFixed(1)}%</b>Nominal footprint coverage</div><div><b>${l.photos}</b>Planned captures</div><div><b>${l.sorties.length}</b>Sorties</div></section><p>${f(Bt)}</p><p>GSD ${l.camera.gsdX.toFixed(2)} \xD7 ${l.camera.gsdY.toFixed(2)} cm/px; footprint ${l.camera.width.toFixed(1)} \xD7 ${l.camera.along.toFixed(1)} m. Height ${a.settings.height} m above takeoff; speed ${a.settings.speed} m/s. Requested front/side overlap ${(a.settings.frontOverlap*100).toFixed(0)}% / ${(a.settings.sideOverlap*100).toFixed(0)}%; overlaps apply along regular survey runs. Exclusions and boundaries can leave gaps.</p><p>Budget: ${a.settings.usableMinutes} measured usable minutes minus ${a.settings.reservePercent}% reserve. Nominal time includes climb, descent, survey, connected transits, configured turn allowance and a routed return to takeoff. No battery or flight-dynamics model is implied.</p><table><thead><tr><th>Sortie</th><th>Captures</th><th>Distance</th><th>Nominal duration</th><th>Unused budget</th></tr></thead><tbody>${l.sorties.map(m=>`<tr><td>${m.id}</td><td>${m.photos}</td><td>${m.distanceM.toFixed(0)} m</td><td>${(m.seconds/60).toFixed(1)} min</td><td>${m.remainingBudgetSeconds.toFixed(0)} s</td></tr>`).join("")}</tbody></table>${h?`<section><h2>Recorded evidence</h2><p>${f(h.source)} \xB7 comparison: ${h.comparisonSortie?"sortie "+h.comparisonSortie:"all planned routes"}. ${f(h.interpretation)}</p><p>${h.captureEvents} recorded capture events; ${h.modeledCaptures} footprint estimates; ${h.unmodeledCaptures} events lack height or heading. ${h.unknownCaptureSamples} samples have unknown capture state. Estimated event coverage of the whole target: ${h.coverage===null?"unavailable":(h.coverage*100).toFixed(1)+"%"}.</p><p>${h.outsideSamples} logged positions and ${h.outsideSegments} connected segments fall outside the inset flight area. ${h.discontinuities} track breaks; ${h.missingCoordinates} rows lack coordinates. Segments longer than ${h.maxGap} seconds are not connected. 95th-percentile distance from the nearest compared route: ${h.deviationP95.toFixed(1)} m.</p><pre>Source SHA-256: ${f(h.sourceSHA256)}+Mapping: ${f(JSON.stringify(h.mapping,null,2))}</pre></section>`:""}<section><h2>Files & coordinates</h2><p>GeoJSON and KML support map review; CSVs retain coordinates, height above takeoff and nominal timing. Keep planner.html and project JSON to edit. Origin: ${a.origin[0]}, ${a.origin[1]} (WGS 84 longitude, latitude); local vertices use east/north meters. Coordinate precision does not establish survey accuracy. No aircraft mission is included.</p></section></html>`}function Pi(i){let l=new TextEncoder,a=[],h=[],f=0;for(let[c,x]of i){let N=l.encode(c),O=typeof x=="string"?l.encode(x):new Uint8Array(x),I=4294967295;for(let L of O){I^=L;for(let Z=0;Z<8;Z++)I=I>>>1^3988292384&-(I&1)}I=(I^4294967295)>>>0;let b=new Uint8Array(30+N.length),_=new DataView(b.buffer);_.setUint32(0,67324752,!0),_.setUint16(4,20,!0),_.setUint16(6,2048,!0),_.setUint16(12,33,!0),_.setUint32(14,I,!0),_.setUint32(18,O.length,!0),_.setUint32(22,O.length,!0),_.setUint16(26,N.length,!0),b.set(N,30);let D=new Uint8Array(46+N.length),Y=new DataView(D.buffer);Y.setUint32(0,33639248,!0),Y.setUint16(4,20,!0),Y.setUint16(6,20,!0),Y.setUint16(8,2048,!0),Y.setUint16(14,33,!0),Y.setUint32(16,I,!0),Y.setUint32(20,O.length,!0),Y.setUint32(24,O.length,!0),Y.setUint16(28,N.length,!0),Y.setUint32(42,f,!0),D.set(N,46),a.push(b,O),h.push(D),f+=b.length+O.length}let m=h.reduce((c,x)=>c+x.length,0),v=new Uint8Array(22),y=new DataView(v.buffer);return y.setUint32(0,101010256,!0),y.setUint16(8,i.length,!0),y.setUint16(10,i.length,!0),y.setUint32(12,m,!0),y.setUint32(16,f,!0),new Blob([...a,...h,v],{type:"application/zip"})}var sr="<!doctype html>"+document.documentElement.outerHTML,qe=JSON.parse(document.getElementById("vector-data").textContent),g=i=>document.getElementById(i),Nt=i=>[...document.querySelectorAll(i)],q=(i,l=0)=>i.toLocaleString(void 0,{maximumFractionDigits:l,minimumFractionDigits:l}),Ie=i=>i+"-"+crypto.randomUUID().slice(0,8),dt=i=>{g("status").textContent=i},qt=(i,l,a="application/octet-stream")=>{let h=URL.createObjectURL(l instanceof Blob?l:new Blob([l],{type:a})),f=document.createElement("a");f.href=h,f.download=i,f.click(),setTimeout(()=>URL.revokeObjectURL(h),1e4)},T=Dt(qe.project),fe=T.revision,Et=Ce(T),$=null,It=null,tt=null,rt=null,Qt=null,Wt=null,gt="select",Lt=[],J=null,We=null,Ut=!1,xt=!1,ue=!1,te=null,Ue=0,pt=null,Ze="vector-draft:"+location.pathname+":"+location.port;function W(i){return async(...l)=>{try{Nt(".dialog-error").forEach(a=>a.remove()),await i(...l)}catch(a){dt(a.message);let h=document.querySelector("dialog[open]");if(h){let f=document.createElement("p");f.className="dialog-error",f.setAttribute("role","alert"),f.textContent=a.message,h.append(f)}else g("plan-error").textContent=a.message,g("plan-error").hidden=!1}}}function pe(){try{localStorage.setItem(Ze,JSON.stringify({project:T,revision:fe}))}catch{dt("Draft storage is full. Save a project file or save to the workspace.")}}function he(){g("save-state").textContent=xt?"Unsaved draft":Ut?"Saved in workspace":"Editable offline project",g("save-source").hidden=!Ut,g("save-source").disabled=!xt||ue||!!te,g("undo").disabled=!Et.canUndo,g("redo").disabled=!Et.canRedo,g("deliver").disabled=!$}function ht(i,l="Plan updated"){let a=Pt(T);i(a),T=Et.push(a),xt=!0,Zt(),pe(),dt(l)}async function He(i,l="Project opened as a draft"){let a=Dt(i);await ci(a),T=Et.push(a),tt=null,rt=null,J=null,xt=!0,Zt(),pe(),dt(l)}function je(i){T=Dt(i),fe=T.revision,Et=Ce(T),xt=!1,tt=null,rt=null,J=null;try{localStorage.removeItem(Ze)}catch{}Zt()}var nt=(i,l,a,h=1,f="settings")=>`<label>${z(i)}<input type="number" data-field="${l}" data-group="${f}" value="${a}" step="${h}"></label>`;function lr(){let i=T.settings,l=T.camera;g("settings-panel").innerHTML=`<section><div class="section-title">CAPTURE GEOMETRY</div><div class="two">${nt("Height above takeoff \xB7 m","height",i.height,1)}${nt("Survey speed \xB7 m/s","speed",i.speed,.1)}</div><div class="two">${nt("Front overlap \xB7 %","frontOverlap",i.frontOverlap*100,1)}${nt("Side overlap \xB7 %","sideOverlap",i.sideOverlap*100,1)}</div><div class="two">${nt("Line angle \xB7 degrees","angle",i.angle,1)}${nt("Horizontal margin \xB7 m","margin",i.margin,.5)}</div><p>0\xB0 is east; 90\xB0 is north. Margins inset boundaries and expand exclusions. Image coverage can extend beyond the flight region.</p></section><section><div class="section-title">TIME PER SORTIE</div><div class="two">${nt("Measured usable \xB7 min","usableMinutes",i.usableMinutes,.5)}${nt("Reserve \xB7 %","reservePercent",i.reservePercent,1)}</div><div class="two">${nt("Climb \xB7 m/s","climbSpeed",i.climbSpeed,.1)}${nt("Descent \xB7 m/s","descentSpeed",i.descentSpeed,.1)}</div>${nt("Allowance per capture run \xB7 s","turnSeconds",i.turnSeconds,.5)}<p>Return, climb and descent are included. A fixed turn allowance is not an aircraft dynamics model.</p></section><section><div class="section-title">YOUR CAMERA</div><label>Camera name<input id="camera-name" value="${z(l.name)}" maxlength="120"></label><div class="two">${nt("Sensor width \xB7 mm","sensorWidth",l.sensorWidth,.1,"camera")}${nt("Sensor height \xB7 mm","sensorHeight",l.sensorHeight,.1,"camera")}</div><div class="two">${nt("Focal length \xB7 mm","focalLength",l.focalLength,.1,"camera")}${nt("Min. interval \xB7 s","minInterval",l.minInterval,.1,"camera")}</div><details><summary>Image dimensions</summary><div class="two">${nt("Width \xB7 pixels","imageWidth",l.imageWidth,1,"camera")}${nt("Height \xB7 pixels","imageHeight",l.imageHeight,1,"camera")}</div></details></section>`,Nt("[data-field]").forEach(h=>h.onchange=W(()=>ht(f=>{let m=Number(h.value);if(!h.value.trim())throw new Error("Enter a value.");["frontOverlap","sideOverlap"].includes(h.dataset.field)&&(m/=100),f[h.dataset.group][h.dataset.field]=m}))),g("camera-name").onchange=W(h=>ht(f=>{f.camera.name=h.target.value}));let a=document.createElement("button");a.id="compare-angles",a.textContent="Compare line directions \u2197",a.style.width="100%",a.onclick=W(hr),g("settings-panel").querySelector("section").append(a)}function ar(){let i=$?[["Target area",q($.area/1e4,2),"ha"],["Ground sampling",q($.camera.gsdX,2),"cm/px"],["Planned captures",q($.photos.length),"photos"],["Nominal coverage",q($.coverage*100,1),"%"],["Sorties",q($.sorties.length),"returns included"],["Nominal time",q($.totalSeconds/60,1),"min"]]:[["Target area","\u2014",""],["Ground sampling","\u2014",""],["Planned captures","\u2014",""],["Nominal coverage","\u2014",""],["Sorties","\u2014",""],["Nominal time","\u2014",""]];g("metrics").innerHTML=i.map(([l,a,h])=>`<div class="metric"><small>${l}</small><b>${a}<em>${h}</em></b></div>`).join("")}function _e(){T.areas.some(l=>l.id===tt)||(tt=null),g("area-count").textContent=T.areas.length,g("area-list").innerHTML=T.areas.map(l=>`<button class="area-row ${l.id===tt?"active":""}" data-area="${z(l.id)}"><i style="background:${l.kind==="boundary"?"#829f72":"#cb8e7d"}"></i><span>${z(l.name)}</span><small>${l.locked?"Locked":l.ring.length+" pts"}</small></button>`).join(""),Nt("[data-area]").forEach(l=>l.onclick=()=>{tt=l.dataset.area,_e(),V()});let i=T.areas.find(l=>l.id===tt);g("area-editor").innerHTML=i?`<label>Layer name<input id="area-name" value="${z(i.name)}" ${i.locked?"disabled":""}></label><div class="row-actions"><button id="lock-area">${i.locked?"Unlock geometry":"Lock geometry"}</button><button id="delete-area" ${i.locked?"disabled":""}>Remove</button></div><details><summary>Vertices \xB7 east, north meters</summary><textarea id="vertices" rows="6" ${i.locked?"disabled":""}>${i.ring.map(l=>l.map(a=>q(a,2).replaceAll(",","")).join(", ")).join(`+`)}</textarea><button id="apply-vertices" ${i.locked?"disabled":""}>Apply vertices</button></details><p>${i.locked?"Unlock to change this geometry.":"Drag its corner handles on the map. Enter coordinates for precise edits."}</p>`:"",i&&(g("area-name").onchange=W(l=>ht(a=>{a.areas.find(h=>h.id===tt).name=l.target.value})),g("lock-area").onclick=W(()=>ht(l=>{let a=l.areas.find(h=>h.id===tt);a.locked=!a.locked})),g("delete-area").onclick=W(()=>ht(l=>{l.areas=l.areas.filter(a=>a.id!==tt)})),g("apply-vertices").onclick=W(()=>{let l=g("vertices").value.trim().split(/\n/).map(a=>a.split(",").map(h=>Number(h.trim())));ht(a=>{a.areas.find(h=>h.id===tt).ring=l})}))}function Je(){if(rt&&!$?.sorties.some(i=>i.id===rt)&&(rt=null),g("sortie-list").innerHTML=$?$.sorties.map(i=>`<button class="sortie ${rt===i.id?"active":""}" data-sortie="${i.id}"><span class="row"><b>Sortie ${String(i.id).padStart(2,"0")}</b><span>${q(i.seconds/60,1)} min</span></span><small>${i.photos.length} captures \xB7 ${q(i.distance)} m \xB7 ${q(i.remainingSeconds)} s unused</small><div class="bar"><i style="width:${Math.min(100,i.seconds/$.budgetSeconds*100)}%"></i></div></button>`).join(""):"<p>Resolve the planning issue to generate sorties.</p>",Nt("[data-sortie]").forEach(i=>i.onclick=()=>{rt=Number(i.dataset.sortie),Qt=$.sorties.find(l=>l.id===rt).photos[0].id,Je(),V()}),$&&rt){let i=$.sorties.find(f=>f.id===rt);i.photos.some(f=>f.id===Qt)||(Qt=i.photos[0].id);let l=i.photos.findIndex(f=>f.id===Qt),a=i.photos[l],h=document.createElement("div");h.className="hint",h.innerHTML=`<label>Inspect planned capture<input id="inspect-photo" type="range" min="0" max="${i.photos.length-1}" value="${l}"></label><span id="photo-details">Photo ${a.id} \xB7 ${q(a.time/60,1)} min after takeoff</span><p>Outlined rectangle = ideal image footprint. Drag the slider to inspect each capture.</p>`,g("sortie-list").append(h),g("inspect-photo").oninput=f=>{let m=i.photos[Number(f.target.value)];Qt=m.id,g("photo-details").textContent=`Photo ${m.id} \xB7 ${q(m.time/60,1)} min after takeoff`,V()}}}function ur(){let i=T.log;if(!i)g("evidence-panel").innerHTML='<section><div class="section-title">FROM PLAN TO EVIDENCE</div><p>Bring a flight CSV to inspect recorded positions, capture events, timing and gaps against this plan.</p><button id="import-log" class="primary">Import flight CSV\u2026</button><p>Choose the columns and units yourself. The original CSV stays in your editable project and exported kit.</p><div class="hint">No flight has been recorded in this example.</div></section>';else{let l=It;g("evidence-panel").innerHTML=`<section><div class="section-title">RECORDED SOURCE</div><strong style="font-size:12px;word-break:break-word">${z(i.name)}</strong><p>${i.records.length} coordinate samples \xB7 ${i.sourceRows} source rows<br>${i.startTime?z(i.startTime):"Elapsed time from first source row"}</p><div class="row-actions"><button id="import-log">Replace log</button><button id="remove-log">Remove</button></div><label>Compare nearest route<select id="compare-sortie"><option value="">All planned routes</option>${($?.sorties??[]).map(a=>`<option value="${a.id}" ${i.comparisonSortie===a.id?"selected":""}>Sortie ${a.id}</option>`).join("")}</select></label><label>Break track after a gap \xB7 seconds<input id="gap-limit" type="number" min=".1" max="120" step=".5" value="${i.maxGap??10}"></label>${l?`<div class="evidence-metrics"><div><b>${l.captureEvents}</b>Recorded capture events</div><div><b>${l.coverage===null?"\u2014":q(l.coverage*100,1)+"%"}</b>Estimated event coverage</div><div><b>${q(l.deviationP95,1)} m</b>P95 nearest-route distance</div><div><b>${l.outsideSamples}</b>Positions outside flight area</div></div><p>${l.modeledCaptures} event footprints modeled; ${l.unmodeledCaptures} events lack height or heading. ${l.unknownCaptureSamples} samples have unknown capture state.</p><p>${l.discontinuities} track breaks \xB7 ${l.missingCoordinates} rows without coordinates \xB7 ${q(l.measuredDistance)} m connected track.</p><p>Recorded span ${q(l.elapsedSeconds/60,1)} min. Battery: ${l.startBattery===null?"unknown":q(l.startBattery)+"%"} \u2192 ${l.endBattery===null?"unknown":q(l.endBattery)+"%"}.</p><div class="hint">Event coverage is an estimate of the whole target. Images, camera orientation and mapping quality have not been verified.</div>`:"<p>Resolve the plan or comparison selection to analyze this log.</p>"}</section><details><summary>Column mapping & source hash</summary><pre style="font-size:9px;white-space:pre-wrap;word-break:break-word">${z(JSON.stringify(i.mapping,null,2))}+SHA-256 ${z(i.sha256)}</pre></details>`,g("remove-log").onclick=W(()=>ht(a=>{delete a.log},"Recorded log removed from draft")),g("compare-sortie").onchange=W(a=>ht(h=>{h.log.comparisonSortie=a.target.value?Number(a.target.value):null})),g("gap-limit").onchange=W(a=>ht(h=>{let f=Number(a.target.value);if(f<.1||f>120)throw new Error("Use a gap threshold between 0.1 and 120 seconds.");h.log.maxGap=f}))}if(g("import-log").onclick=()=>{g("log-file").value="",g("log-file").click()},i&&It){let l=document.createElement("section");Wt=Math.min(Wt??0,i.records.length-1),l.innerHTML=`<div class="section-title">INSPECT A LOG SAMPLE</div><input id="inspect-log" aria-label="Recorded sample" type="range" min="0" max="${i.records.length-1}" value="${Wt}"><p id="sample-details"></p>`,g("evidence-panel").append(l);let a=()=>{let h=i.records[Wt];g("sample-details").textContent=`Row ${h.sourceRow} \xB7 ${q(h.time,1)} s \xB7 height ${h.altitude===null?"unknown":q(h.altitude,1)+" m"} \xB7 capture ${h.capture===null?"unknown":h.capture?"recorded":"no event"}`};a(),g("inspect-log").oninput=h=>{Wt=Number(h.target.value),a(),V()}}g("log-legend").hidden=!i}function Ge(){let i=zt(T.areas.map(f=>f.ring)),l=g("map").getBoundingClientRect(),a=Math.max(.5,l.width/l.height),h=Math.max(i.size[0]*1.45,i.size[1]*1.75*a,60);J={center:i.min.map((f,m)=>(f+i.max[m])/2),width:h}}function V(){J||Ge();let i=g("map").getBoundingClientRect(),l=Math.max(.5,i.width/i.height),a=J.width/l,h=J.width/Math.max(1,i.width),f=J.center;g("map").setAttribute("viewBox",`${f[0]-J.width/2} ${-f[1]-a/2} ${J.width} ${a}`);let m=I=>I.map((b,_)=>(_?"L":"M")+b[0].toFixed(3)+" "+(-b[1]).toFixed(3)).join(" "),v=I=>m(I)+"Z",y=Math.pow(10,Math.floor(Math.log10(J.width/10))),c=y*(J.width/y>25?5:1),x=`<defs><pattern id="grid" width="${c}" height="${c}" patternUnits="userSpaceOnUse"><path d="M ${c} 0 H 0 V ${c}" fill="none" stroke="#d7decd" stroke-width="${h*.55}"/></pattern><pattern id="hatch" width="${h*7}" height="${h*7}" patternUnits="userSpaceOnUse" patternTransform="rotate(40)"><line x1="0" x2="0" y2="${h*7}" stroke="#c58870" stroke-width="${h*1}" opacity=".35"/></pattern></defs><rect x="${f[0]-J.width/2}" y="${-f[1]-a/2}" width="${J.width}" height="${a}" fill="url(#grid)"/>`;for(let I of T.areas){let b=I.id===tt,_=I.kind==="exclusion";x+=`<path class="area" data-map-area="${z(I.id)}" d="${v(I.ring)}" fill="${_?"#e9d7c6":"#d7e1c7"}" stroke="${b?"#48623c":_?"#b6806b":"#94a77f"}" stroke-width="${b?2:1.3}"/>`,_&&(x+=`<path pointer-events="none" d="${v(I.ring)}" fill="url(#hatch)"/>`)}if($){x+=`<path d="${$.region.map(v).join(" ")}" fill="none" stroke="#91a278" stroke-width="1" stroke-dasharray="4 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`,g("show-coverage").checked&&(x+=`<path d="${$.covered.map(v).join(" ")}" fill="#75a895" fill-rule="evenodd" opacity=".3" pointer-events="none"/>`),g("show-gaps").checked&&(x+=`<path d="${$.gaps.map(v).join(" ")}" fill="#df9138" fill-rule="evenodd" opacity=".5" pointer-events="none"/>`);for(let b of $.sorties){let _=!rt||rt===b.id;if(x+=`<path d="${m(b.path)}" fill="none" stroke="${_?"#c66537":"#aeb99d"}" stroke-width="${rt===b.id?2:1.2}" opacity="${_?.85:.25}" vector-effect="non-scaling-stroke" pointer-events="none"/>`,_)for(let D of b.photos)x+=`<circle cx="${D.point[0]}" cy="${-D.point[1]}" r="${h*(rt?2:1.4)}" fill="#a74f2b" pointer-events="none"/>`}let I=rt&&$.photos.find(b=>b.id===Qt);I&&(x+=`<path d="${v(ae(I.point,I.heading,$.camera.width,$.camera.along))}" fill="#c65a32" fill-opacity=".12" stroke="#b45632" stroke-width="2" vector-effect="non-scaling-stroke" pointer-events="none"/><circle cx="${I.point[0]}" cy="${-I.point[1]}" r="${h*4}" fill="#9a4024"/>`)}if(It){g("show-coverage").checked&&(x+=`<path d="${It.covered.map(v).join(" ")}" fill="#328f97" fill-rule="evenodd" opacity=".22" pointer-events="none"/>`);for(let I of It.paths)x+=`<path d="${m(I)}" fill="none" stroke="#267d81" stroke-width="2.7" vector-effect="non-scaling-stroke" pointer-events="none"/>`}if(It&&Wt!==null&&!g("evidence-panel").hidden){let I=T.log.records[Wt];x+=`<circle cx="${I.point[0]}" cy="${-I.point[1]}" r="${h*6}" fill="#267d81" stroke="#fff" stroke-width="${h*2}" pointer-events="none"/>`}for(let I of T.areas){let b=zt([I.ring]),_=[(b.min[0]+b.max[0])/2,(b.min[1]+b.max[1])/2];if(I.kind==="exclusion"&&(x+=`<text x="${_[0]}" y="${-_[1]}" fill="#976a55" text-anchor="middle" font-size="${h*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#e9d7c6" stroke-width="${h*3}">${z(I.name)}</text>`),I.id===tt&&!I.locked)for(let[D,Y]of I.ring.entries())x+=`<circle class="handle" data-handle="${D}" cx="${Y[0]}" cy="${-Y[1]}" r="${h*5}" fill="#fffdf3" stroke="#526d42" stroke-width="1.5"/>`}let[N,O]=T.home;if(x+=`<g data-home="true"><circle cx="${N}" cy="${-O}" r="${h*9}" fill="#263d30" stroke="#fffdf3" stroke-width="${h*2}"/><text x="${N}" y="${-O+h*3.2}" text-anchor="middle" fill="#fffdf3" font-size="${h*9}" font-family="system-ui">H</text></g><text x="${N+h*14}" y="${-O+h*3}" fill="#425d36" font-size="${h*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#eef2e6" stroke-width="${h*3}">TAKEOFF</text>`,Lt.length){x+=`<path d="${m(Lt)}" fill="none" stroke="#344f31" stroke-width="2" stroke-dasharray="5 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`;for(let I of Lt)x+=`<circle cx="${I[0]}" cy="${-I[1]}" r="${h*4}" fill="#344f31"/>`}g("map").innerHTML=x,g("scale").textContent="Grid "+q(c)+" m",g("map").style.cursor=gt==="select"?"default":"crosshair"}function Zt(){let i="";try{$=Ae(T)}catch(l){$=null,i=l.message}if(It=null,$&&T.log)try{It=Kt($)}catch(l){i=l.message}g("plan-error").hidden=!i,g("plan-error").textContent=i,g("project-title").textContent=T.title,g("map-title").textContent=T.title,g("map-subtitle").textContent=$?`${$.runs.length} survey runs \xB7 ${q(T.settings.height)} m above takeoff \xB7 ${q(T.settings.frontOverlap*100)} / ${q(T.settings.sideOverlap*100)}% overlap`:"Edit your boundary and planning settings",g("map-origin").textContent=`WGS 84 \xB7 ${T.origin[1].toFixed(5)}, ${T.origin[0].toFixed(5)}`,document.title=T.title+" \xB7 Vector",ar(),lr(),_e(),Je(),ur(),V(),he()}function gi(i){let l=new DOMPoint(i.clientX,i.clientY).matrixTransform(g("map").getScreenCTM().inverse());return[Math.round(l.x*10)/10,Math.round(-l.y*10)/10]}function de(i){gt=i,Lt=[],Nt("[data-tool]").forEach(l=>l.classList.toggle("active",l.dataset.tool===gt)),g("draw-help").hidden=!["boundary","exclusion"].includes(gt),V()}function Ve(){if(Lt.length<3)throw new Error("Draw at least three different corners.");let i=Ie(gt),l=Lt.map(a=>[...a]);ht(a=>{a.areas.push({id:i,name:gt==="boundary"?"New survey area":"New exclusion",kind:gt,locked:!1,ring:l})},"Polygon added; drag its vertices or enter precise coordinates"),tt=i,de("select"),_e(),V()}Nt("[data-tool]").forEach(i=>i.onclick=()=>de(i.dataset.tool));g("finish-draw").onclick=W(Ve);g("cancel-draw").onclick=()=>de("select");g("map").onpointerdown=i=>{if(i.button!==0)return;let l=gi(i),a=i.target.closest("[data-handle]"),h=i.target.closest("[data-home]"),f=i.target.closest("[data-map-area]");if(gt==="home"){W(()=>ht(m=>{m.home=l},"Takeoff moved"))(),de("select");return}if(gt!=="select"){(!Lt.length||it(Lt.at(-1),l)>.2)&&Lt.push(l),V();return}if(a)pt={kind:"vertex",index:Number(a.dataset.handle),start:l,ring:Pt(T.areas.find(m=>m.id===tt).ring),pointer:i.pointerId};else if(h)pt={kind:"home",start:l,home:[...T.home],pointer:i.pointerId};else if(f){tt=f.dataset.mapArea,_e(),V();return}else pt={kind:"pan",start:l,center:[...J.center],pointer:i.pointerId};g("map").setPointerCapture(i.pointerId)};g("map").onpointermove=i=>{if(!pt)return;let l=gi(i);pt.kind==="pan"?(J.center=J.center.map((a,h)=>a+pt.start[h]-l[h]),V()):(pt.kind==="home"?T.home=l:T.areas.find(a=>a.id===tt).ring[pt.index]=l,V())};function xi(i,l=!1){if(!pt)return;let a=pt;if(pt=null,g("map").hasPointerCapture(a.pointer)&&g("map").releasePointerCapture(a.pointer),a.kind==="pan")return;let h=Pt(T);if(a.kind==="home"?T.home=a.home:T.areas.find(f=>f.id===tt).ring=a.ring,l){V();return}try{T=Et.push(h),xt=!0,Zt(),pe(),dt("Map geometry updated")}catch(f){V(),dt(f.message)}}g("map").onpointerup=i=>xi(i);g("map").onpointercancel=i=>xi(i,!0);g("map").ondblclick=W(()=>{["boundary","exclusion"].includes(gt)&&Ve()});g("map").addEventListener("wheel",i=>{i.preventDefault(),J||Ge(),J.width=Math.max(20,Math.min(15e3,J.width*Math.exp(i.deltaY*.001))),V()},{passive:!1});g("zoom-in").onclick=()=>{J.width=Math.max(20,J.width*.8),V()};g("zoom-out").onclick=()=>{J.width=Math.min(15e3,J.width/.8),V()};g("frame-site").onclick=()=>{Ge(),V()};g("undo").onclick=()=>{T=Et.undo(),xt=!0,Zt(),pe(),dt("Edit undone")};g("redo").onclick=()=>{T=Et.redo(),xt=!0,Zt(),pe(),dt("Edit restored")};g("show-all").onclick=()=>{rt=null,Je(),V()};g("show-coverage").onchange=V;g("show-gaps").onchange=V;function ze(i){g("plan-tab").classList.toggle("active",!i),g("evidence-tab").classList.toggle("active",i),g("settings-panel").hidden=i,g("evidence-panel").hidden=!i,V()}g("plan-tab").onclick=()=>ze(!1);g("evidence-tab").onclick=()=>ze(!0);Nt("[data-close]").forEach(i=>i.onclick=()=>i.closest("dialog").close());g("model-details").onclick=()=>g("model-dialog").showModal();g("project-details").onclick=()=>{g("title-input").value=T.title,g("brief-input").value=T.brief,g("origin-lon").value=T.origin[0],g("origin-lat").value=T.origin[1],g("project-dialog").showModal()};g("apply-project").onclick=W(()=>{let i=[Number(g("origin-lon").value),Number(g("origin-lat").value)];if(T.log&&it(i,T.origin)>1e-10)throw new Error("Remove the recorded log before relocating this project.");ht(l=>{l.title=g("title-input").value,l.brief=g("brief-input").value,l.origin=i}),g("project-dialog").close()});async function Ke(i,l=8e6){let a=i.files[0];if(!a)return null;if(a.size>l)throw new Error("Choose a file smaller than "+l/1e6+" MB.");let h;try{h=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(await a.arrayBuffer())}catch{throw new Error("Save this file as UTF-8 text before importing.")}return{name:a.name,raw:h}}g("choose-project").onclick=()=>{g("project-file").value="",g("project-file").click()};g("project-file").onchange=W(async()=>{let i=await Ke(g("project-file"));i&&(await He(JSON.parse(i.raw.replace(/^\uFEFF/,""))),g("open-dialog").close())});g("open-project").onclick=W(async()=>{if(g("native-open").hidden=!Ut,g("open-dialog").showModal(),Ut){let i=await fetch("/api/files"),l=await i.json();g("recent-projects").replaceChildren();for(let a of l.files??[]){let h=document.createElement("button");h.textContent=a.name+" \xB7 "+a.folder,h.onclick=W(()=>Ci(a.path)),g("recent-projects").append(h)}}});async function Ci(i){let l=await fetch("/api/open",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:i})}),a=await l.json();if(!l.ok)throw new Error(a.error||"Could not open project.");await He(a.project),g("open-dialog").close()}g("open-path").onclick=W(()=>Ci(g("project-path").value));g("save-project").onclick=()=>qt(bt(T.title)+".vector.json",JSON.stringify(T,null,2),"application/json");g("import-geo").onclick=()=>g("geo-dialog").showModal();g("choose-geo").onclick=()=>{g("geo-file").value="",g("geo-file").click()};g("geo-file").onchange=W(async()=>{let i=await Ke(g("geo-file"),3e6);if(!i)return;let l=g("geo-mode").value==="replace",a=g("geo-kind").value;if(l&&a==="exclusion")throw new Error("Start a site with boundaries, then add exclusions.");let h=pi(JSON.parse(i.raw.replace(/^\uFEFF/,"")),l?void 0:T.origin);if(!h.areas.length)throw new Error("Choose a file containing polygon boundaries.");let f=Pt(T);l&&(f.origin=h.origin,f.areas=[],f.id=Ie("site"),f.title=i.name.replace(/\.(geojson|json)$/i,""),f.brief="Site geometry imported from "+i.name+". Review takeoff, exclusions, camera specifications and model assumptions.",delete f.log);for(let v of h.areas){let y=v.kind||a;f.areas.push({id:Ie(y),name:v.name,kind:y,locked:!1,ring:v.boundary});for(let c of v.holes)f.areas.push({id:Ie("exclusion"),name:v.name+" interior",kind:"exclusion",locked:!1,ring:c})}let m=xe(f.areas.filter(v=>v.kind==="boundary").map(v=>v.ring),f.areas.filter(v=>v.kind==="exclusion").map(v=>v.ring),f.settings.margin);if(l||!at(m,f.home)){let v=h.points.find(c=>at(m,c.point))?.point,y=zt(m);for(let c=1;c<20&&!v;c++)for(let x=1;x<20&&!v;x++){let N=y.min.map((O,I)=>O+y.size[I]*(I?c:x)/20);at(m,N)&&(v=N)}if(!v)throw new Error("No takeoff position fits the current margin. Reduce the margin before importing.");f.home=v}await He(f,"Site imported; review the proposed takeoff and capture settings"),g("geo-dialog").close()});g("log-file").onchange=W(async()=>{let i=await Ke(g("log-file"),3e6);if(!i)return;let l=Ye(i.raw);We=i,g("log-name").textContent=i.name+" \xB7 "+l.rows.length+" source rows";let a=h=>(h?'<option value="">Not supplied</option>':'<option value="">Choose column\u2026</option>')+l.headers.map(f=>`<option value="${z(f)}">${z(f)}</option>`).join("");g("log-mapping").innerHTML=["time","latitude","longitude","altitude","heading","battery","capture"].map(h=>`<label>${h[0].toUpperCase()+h.slice(1)} column<select data-map="${h}">${a(!["time","latitude","longitude"].includes(h))}</select></label>`).join("")+'<label>Time format<select data-map="timeUnit"><option value="seconds">Elapsed seconds</option><option value="milliseconds">Elapsed milliseconds</option><option value="iso">ISO 8601 with timezone</option></select></label><label>Altitude units<select data-map="altitudeUnit"><option value="meters">Meters</option><option value="feet">Feet</option></select></label><label>Altitude reference<select data-map="altitudeReference"><option value="takeoff">Height above takeoff</option><option value="amsl">AMSL elevation</option></select></label><label>Takeoff elevation \xB7 meters AMSL<input data-map="homeElevation" type="number" step="any" placeholder="Required for AMSL data"></label>',g("log-dialog").showModal()});g("apply-log").onclick=W(async()=>{let i=Object.fromEntries(Nt("[data-map]").map(a=>[a.dataset.map,a.dataset.map==="homeElevation"?a.value.trim()?Number(a.value):null:a.value])),l=await Me(We.raw,We.name,i,T.origin);ht(a=>{a.log=l},"Recorded flight imported with original CSV and column mapping"),ze(!0),g("log-dialog").close()});function wi(){return sr.replace(/(<script id="vector-data" type="application\/json">)[\s\S]*?(<\/script>)/,(i,l,a)=>l+JSON.stringify({project:T,licenses:qe.licenses}).replace(/</g,"\\u003c")+a)}function ce(){if(!$)throw new Error("Resolve the planning issue before exporting.");if(T.log&&!It)throw new Error("Resolve the recorded-flight comparison before exporting.");return $}async function hr(){let i=Pt(T),l=JSON.stringify(T),a=g("angles-dialog");a||(a=document.createElement("dialog"),a.id="angles-dialog",document.body.append(a)),a.innerHTML='<h2>Compare line directions</h2><p>Same site, camera, overlaps and time budget. Comparing 12 directions in 15\xB0 steps, plus your current angle. These are sampled alternatives, not a global optimum.</p><p id="angle-progress" role="status">Calculating\u2026</p><div id="angle-results"></div><div class="dialog-actions"><button id="close-angles">Close</button></div>',a.showModal(),g("close-angles").onclick=()=>a.close();let h=[],f=[...new Set([i.settings.angle,...Array.from({length:12},(m,v)=>v*15)])];for(let m of f){if(await new Promise(y=>setTimeout(y,15)),!a.open||JSON.stringify(T)!==l)return;let v=Pt(i);v.settings.angle=m;try{let y=Ae(v);h.push({angle:m,minutes:y.totalSeconds/60,sorties:y.sorties.length,photos:y.photos.length,coverage:y.coverage})}catch(y){h.push({angle:m,error:y.message})}g("angle-progress").textContent=`Compared ${h.length} of ${f.length} directions`}h.sort((m,v)=>(m.error?1/0:m.minutes)-(v.error?1/0:v.minutes)),g("angle-progress").textContent="Sorted by nominal total time. Compare coverage before applying a direction.",g("angle-results").innerHTML=h.map(m=>m.error?`<p>${m.angle}\xB0 \xB7 ${z(m.error)}</p>`:`<button data-angle="${m.angle}" style="display:flex;width:100%;justify-content:space-between;margin:7px 0;font-size:11px"><b>${m.angle}\xB0${m.angle===i.settings.angle?" \xB7 current":""}</b><span>${q(m.minutes,1)} min \xB7 ${m.sorties} sorties \xB7 ${q(m.coverage*100,1)}% coverage</span></button>`).join(""),Nt("[data-angle]").forEach(m=>m.onclick=W(()=>{if(JSON.stringify(T)!==l)throw new Error("The source changed during comparison. Run the comparison again.");ht(v=>{v.settings.angle=Number(m.dataset.angle)},"Compared direction applied; other requirements preserved"),a.close()}))}g("deliver").onclick=W(()=>{let i=ce();g("export-summary").textContent=`${T.title} \xB7 ${i.photos.length} planned captures \xB7 ${i.sorties.length} sorties \xB7 ${q(i.area/1e4,2)} hectares`,g("export-dialog").showModal()});g("export-geo").onclick=W(()=>qt(bt(T.title)+".geojson",JSON.stringify(ke(ce()),null,2),"application/geo+json"));g("export-kml").onclick=W(()=>qt(bt(T.title)+".kml",Fe(ce()),"application/vnd.google-earth.kml+xml"));g("export-report").onclick=W(()=>qt(bt(T.title)+"-report.html",Re(ce()),"text/html"));g("export-kit").onclick=W(()=>{let i=ce(),l=[[bt(T.title)+".vector.json",JSON.stringify(T,null,2)],["planner.html",wi()],["survey.geojson",JSON.stringify(ke(i),null,2)],["overlay.kml",Fe(i)],["site-map.svg",De(i)],["planned-photos.csv",mi(i)],["planned-route.csv",yi(i)],["report.json",JSON.stringify($e(i),null,2)],["report.html",Re(i)],["LICENSES.txt",qe.licenses||"See the embedded upstream licenses in planner.html."],["README.md",`# ${T.title}-function flightCourse(seed, count = 12) {- const r = random(seed, "gates"),- phase = r() * 6.28;- return Array.from({ length: count }, (_, i) => ({- x: Math.sin(i * 0.62 + phase) * 17,- y: 13 + Math.sin(i * 0.85 + phase) * 5,- z: 45 + i * 42,- radius: 6,- index: i,- }));-}-function flightStart() {- return {- x: 0,- y: 13,- z: 0,- vx: 0,- vy: 0,- speed: 22,- next: 0,- passed: 0,- missed: 0,- steps: 0,- time: 0,- finished: false,- crashed: false,- };-}-function flightStep(state, course, input = {}, dt = 1 / 60) {- const s = { ...state };- if (s.finished || s.crashed) return s;- const target = course[Math.min(s.next, course.length - 1)];- const auto = input.autopilot !== false;- const desiredX = auto- ? clamp((target.x - s.x) * 2, -15, 15)- : (input.x || 0) * 14;- const desiredY = auto- ? clamp((target.y - s.y) * 2, -10, 10)- : (input.y || 0) * 10;- s.vx = lerp(s.vx, desiredX, 1 - Math.exp(-dt * 4));- s.vy = lerp(s.vy, desiredY, 1 - Math.exp(-dt * 4));- s.speed = lerp(- s.speed,- input.brake ? 7 : input.boost ? 34 : 22,- 1 - Math.exp(-dt * 3),- );- s.x = clamp(s.x + s.vx * dt, -65, 65);- s.y += s.vy * dt;- s.z += s.speed * dt;- s.steps++;- s.time = s.steps / 60;- if (s.y < 1.5) {- s.crashed = true;- s.y = 1.5;- return s;- }- s.y = Math.min(48, s.y);- if (s.next < course.length && s.z >= target.z) {- if (Math.hypot(s.x - target.x, s.y - target.y) <= target.radius) s.passed++;- else s.missed++;- s.next++;- }- if (s.z >= course.at(-1).z + 25) s.finished = true;- return s;-}-function flyAutopilot(seed) {- const course = flightCourse(seed);- let state = flightStart();- for (let i = 0; i < 6000 && !state.finished && !state.crashed; i++)- state = flightStep(state, course);- return state;-}+${T.brief}-</script>-<script>-'use strict';-const $ = (s) => document.querySelector(s);-const $$ = (s) => [...document.querySelectorAll(s)];-const params = new URLSearchParams(location.search);-let seed = (params.get("seed") || "42").slice(0, 128);-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;-const parentMessage = (message) => {- if (parent !== window) parent.postMessage(message, "*");-};-function toast(message) {- $("#toast").textContent = message;- clearTimeout(toast.timer);- toast.timer = setTimeout(() => {- $("#toast").textContent = "";- }, 3500);-}-function saveFile(name, content, type = "application/json") {- const blob =- content instanceof Blob ? content : new Blob([content], { type });- const url = URL.createObjectURL(blob),- a = document.createElement("a");- a.href = url;- a.download = name;- document.body.append(a);- a.click();- a.remove();- setTimeout(() => URL.revokeObjectURL(url), 30000);-}-function canvasPNG(canvas, name) {- canvas.toBlob((blob) => {- if (blob) saveFile(name, blob);- else toast("Image export failed. Please try again.");- });-}-function setSeed(value) {- seed = String(value).trim().slice(0, 128) || "42";- $("#seed").value = seed;- const url = new URL(location.href);- url.searchParams.set("seed", seed);- try {- history.replaceState(null, "", url);- } catch {- /* Opaque-origin iframe: the shell owns its URL. */- }- parentMessage({ type: "harness:state", seed });- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));-}-$("#seed").value = seed;-$("#seed-form").addEventListener("submit", (e) => {- e.preventDefault();- setSeed($("#seed").value);-});-$("#next-seed").addEventListener("click", () =>- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),-);-function fitCanvas(canvas, draw, maxDpr = 2) {- const observer = new ResizeObserver(() => {- const box = canvas.getBoundingClientRect(),- dpr = Math.min(devicePixelRatio || 1, maxDpr);- canvas.width = Math.max(1, Math.round(box.width * dpr));- canvas.height = Math.max(1, Math.round(box.height * dpr));- draw?.();- });- observer.observe(canvas);- return observer;-}-const editable = (target) =>- target instanceof Element &&- !!target.closest("input,textarea,select,[contenteditable=true]");-addEventListener("error", (e) =>- parentMessage({ type: "harness:error", message: e.message }),-);-addEventListener("unhandledrejection", (e) =>- parentMessage({- type: "harness:error",- message: String(e.reason?.message || e.reason),- }),-);-function ready() {- document.body.dataset.ready = "true";- parentMessage({ type: "harness:ready", title: document.title, seed });-}+Open planner.html to edit offline. Keep the .vector.json source. Load survey.geojson in GIS or overlay.kml in a map viewer; KML is ground-clamped. CSV coordinates are longitude/latitude degrees, with explicit height above takeoff and nominal timing. These files are for planning and review, not aircraft upload. Print report.html to PDF.-let course,- state,- flightRunning = false,- autopilot = true,- telemetry = [],- keys = {},- touchInput = { x: 0, y: 0 },- accumulator = 0,- previousTime = 0;-function projectFlight(x, y, z, w, h) {- const dz = z - state.z;- if (dz < 0.6) return null;- const scale = (w * 0.8) / dz;- return {- x: w / 2 + (x - state.x) * scale,- y: h * 0.47 - (y - state.y) * scale,- scale,- };-}-function drawFlight() {- if (!state) return;- const c = $("#flight"),- ctx = c.getContext("2d"),- w = c.width,- h = c.height;- const sky = ctx.createLinearGradient(0, 0, 0, h);- sky.addColorStop(0, "#243e4a");- sky.addColorStop(0.53, "#849c9a");- sky.addColorStop(1, "#576654");- ctx.fillStyle = sky;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#d7d9af";- ctx.beginPath();- ctx.arc(w * 0.72, h * 0.23, w * 0.035, 0, Math.PI * 2);- ctx.fill();- ctx.save();- ctx.translate(w / 2, h * 0.5);- ctx.rotate(-state.vx * 0.009);- ctx.translate(-w / 2, -h * 0.5);- for (let layer = 0; layer < 3; layer++) {- ctx.fillStyle = ["#708989", "#5d7777", "#476164"][layer];- ctx.beginPath();- ctx.moveTo(-w, h);- for (let i = -1; i <= 24; i++) {- const x = (i * w) / 22;- const y =- h * (0.4 + layer * 0.035) -- Math.sin(i * 1.2 + layer * 2.2 + (hash(seed) % 20)) * h * 0.05 -- Math.cos(i * 2.7) * h * 0.025;- ctx.lineTo(x, y);- }- ctx.lineTo(w * 2, h);- ctx.fill();- }- const base = Math.floor(state.z / 14) * 14;- for (let z = base + 250; z > state.z + 1; z -= 14) {- const a = projectFlight(-80, 0, z, w, h),- b = projectFlight(80, 0, z, w, h);- if (!a || !b) continue;- ctx.strokeStyle = "#bed3ae24";- ctx.lineWidth = 1;- ctx.beginPath();- ctx.moveTo(a.x, a.y);- ctx.lineTo(b.x, b.y);- ctx.stroke();- }- for (let x = -80; x <= 80; x += 10) {- const a = projectFlight(x, 0, state.z + 2, w, h),- b = projectFlight(x, 0, state.z + 270, w, h);- ctx.strokeStyle = "#bed3ae20";- ctx.beginPath();- ctx.moveTo(a.x, a.y);- ctx.lineTo(b.x, b.y);- ctx.stroke();- }- // Cliff columns are projected in world space; their parallax makes steering legible.- const boxes = [];- for (let i = Math.floor(state.z / 28); i < Math.floor(state.z / 28) + 12; i++)- for (const side of [-1, 1]) {- const r = random(seed, `rock:${i}:${side}`);- boxes.push({- x: side * (34 + r() * 22),- z: i * 28 + 12,- y: 12 + r() * 35,- width: 8 + r() * 7,- });- }- for (const box of boxes.sort((a, b) => b.z - a.z)) {- const p = [- projectFlight(box.x - box.width, 0, box.z, w, h),- projectFlight(box.x + box.width, 0, box.z, w, h),- projectFlight(box.x + box.width, box.y, box.z, w, h),- projectFlight(box.x - box.width, box.y, box.z, w, h),- ];- if (p.some((v) => !v)) continue;- ctx.fillStyle = box.x < 0 ? "#344f53" : "#3d5558";- ctx.beginPath();- p.forEach((v, i) => (i ? ctx.lineTo(v.x, v.y) : ctx.moveTo(v.x, v.y)));- ctx.closePath();- ctx.fill();- ctx.strokeStyle = "#768d7744";- ctx.stroke();- }- for (let i = course.length - 1; i >= state.next; i--) {- const gate = course[i],- p = projectFlight(gate.x, gate.y, gate.z, w, h);- if (!p || gate.z - state.z > 260) continue;- const radius = gate.radius * p.scale;- ctx.strokeStyle = i === state.next ? "#d9f0a7" : "#bfd9bc66";- ctx.lineWidth = Math.max(2, p.scale * 0.35);- ctx.shadowColor = "#ddf7af";- ctx.shadowBlur = i === state.next ? 9 : 0;- ctx.beginPath();- for (let j = 0; j <= 8; j++) {- const a = Math.PI / 8 + (j * Math.PI) / 4,- x = p.x + Math.cos(a) * radius,- y = p.y + Math.sin(a) * radius;- j ? ctx.lineTo(x, y) : ctx.moveTo(x, y);- }- ctx.stroke();- ctx.shadowBlur = 0;- ctx.font = `${clamp(p.scale * 1.8, 10, 50)}px monospace`;- ctx.textAlign = "center";- ctx.fillStyle = "#e6f3cc";- ctx.fillText(String(i + 1).padStart(2, "0"), p.x, p.y - radius - 8);- }- ctx.restore();- drawMinimap();-}-function drawMinimap() {- const c = $("#minimap"),- ctx = c.getContext("2d"),- w = c.width,- h = c.height;- if (!course) return;- ctx.clearRect(0, 0, w, h);- const pos = (x, z) => ({- x: w / 2 + (x / 90) * w,- y: h - 12 - (z / (course.at(-1).z + 30)) * (h - 24),- });- ctx.strokeStyle = "#94b2a95c";- ctx.beginPath();- course.forEach((g, i) => {- const p = pos(g.x, g.z);- i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y);- });- ctx.stroke();- course.forEach((g, i) => {- const p = pos(g.x, g.z);- ctx.fillStyle = i < state.next ? "#8eac99" : "#cde4a1";- ctx.fillRect(p.x - 3, p.y - 3, 6, 6);- });- ctx.strokeStyle = "#dfa578";- ctx.beginPath();- telemetry.forEach((t, i) => {- const p = pos(t.x, t.z);- i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y);- });- ctx.stroke();- const p = pos(state.x, state.z);- ctx.fillStyle = "#f4eac7";- ctx.beginPath();- ctx.arc(p.x, p.y, 5, 0, Math.PI * 2);- ctx.fill();-}-function updateFlightHUD() {- $("#velocity").textContent = flightRunning ? state.speed.toFixed(1) : "0";- $("#altitude").textContent = state.y.toFixed(1);- $("#gates").textContent = `${state.passed} / ${course.length}`;- $("#flight-clock").textContent =- `${String(Math.floor(state.time / 60)).padStart(2, "0")}:${(state.time % 60).toFixed(2).padStart(5, "0")}`;- $("#flight-mode").textContent =- `${flightRunning ? "FLYING" : "PAUSED"} / ${autopilot ? "AUTOPILOT" : "MANUAL"}`;- $("#gate-hint").textContent =- state.next < course.length- ? `GATE ${String(state.next + 1).padStart(2, "0")} · ${Math.max(0, course[state.next].z - state.z).toFixed(0)} m · ${state.missed} missed`- : "Course complete";- $("#start-flight").textContent = flightRunning- ? "Ⅱ Pause flight"- : autopilot- ? "▶ Watch autopilot"- : "▶ Resume flight";- $("#manual").textContent = autopilot ? "Take control" : "Engage autopilot";-}-function resetFlight() {- course = flightCourse(seed);- state = flightStart();- telemetry = [{ ...state }];- flightRunning = false;- accumulator = 0;- keys = {};- $("#flight-summary").hidden = true;- updateFlightHUD();- drawFlight();-}-$("#start-flight").onclick = () => {- if (state.finished || state.crashed) resetFlight();- flightRunning = !flightRunning;- updateFlightHUD();- $("#flight").focus();-};-$("#manual").onclick = () => {- autopilot = !autopilot;- flightRunning = true;- updateFlightHUD();- $("#flight").focus();-};-$("#reset-flight").onclick = resetFlight;-addEventListener("keydown", (e) => {- if (editable(e.target)) return;- if (- [- "w",- "a",- "s",- "d",- "arrowup",- "arrowdown",- "arrowleft",- "arrowright",- " ",- "shift",- ].includes(e.key.toLowerCase())- ) {- e.preventDefault();- keys[e.key.toLowerCase()] = true;- }-});-addEventListener("keyup", (e) => {- keys[e.key.toLowerCase()] = false;-});-addEventListener("blur", () => {- keys = {};- touchInput = { x: 0, y: 0 };-});-$$(".flight-pad button").forEach((b) => {- b.onpointerdown = (e) => {- e.preventDefault();- autopilot = false;- flightRunning = true;- touchInput[b.dataset.axis] = +b.dataset.value;- b.setPointerCapture(e.pointerId);- updateFlightHUD();- };- b.onpointerup = b.onpointercancel = () => {- touchInput[b.dataset.axis] = 0;- };-});-$("#export-flight").onclick = () =>- saveFile(- `vector-${hash(seed)}.json`,- JSON.stringify(- {- seed,- mode: autopilot ? "autopilot" : "manual",- step: 1 / 60,- course,- telemetry,- result: state,- },- null,- 2,- ),- );-function flightFrame(time) {- const delta = Math.min(0.1, (time - previousTime) / 1000 || 0);- previousTime = time;- if (flightRunning && !document.hidden) {- accumulator += delta;- while (accumulator >= 1 / 60) {- state = flightStep(state, course, {- autopilot,- x:- touchInput.x +- (keys.d || keys.arrowright ? 1 : 0) -- (keys.a || keys.arrowleft ? 1 : 0),- y:- touchInput.y +- (keys.w || keys.arrowup ? 1 : 0) -- (keys.s || keys.arrowdown ? 1 : 0),- brake: keys[" "],- boost: keys.shift,- });- accumulator -= 1 / 60;- if (state.steps % 12 === 0) telemetry.push({ ...state });- if (state.finished || state.crashed) {- flightRunning = false;- $("#flight-summary").hidden = false;- $("#flight-summary").replaceChildren(- document.createTextNode(- state.crashed- ? "Back to the flight line."- : state.missed- ? "A line to improve."- : "A clean run.",- ),- );- const span = document.createElement("span");- span.textContent = `${state.passed} / ${course.length} gates · ${state.time.toFixed(2)} s · ${state.missed} missed`;- $("#flight-summary").append(span);- break;- }- }- updateFlightHUD();- drawFlight();- }- requestAnimationFrame(flightFrame);-}-fitCanvas($("#flight"), drawFlight);-fitCanvas($("#minimap"), drawMinimap);-addEventListener("seedchange", resetFlight);-resetFlight();-requestAnimationFrame(flightFrame);-ready();+${Bt}+A recorded CSV, if supplied, is retained unchanged with SHA-256 and explicit column/unit mapping. Event footprints do not prove image existence or quality.+`]];T.log&&l.push(["recorded-source.csv",T.log.raw],["recorded-normalized.csv",vi(i)]),qt(bt(T.title)+"-field-kit.zip",Pi(l)),dt("Field kit exported with editable source and review files")});function Ii(i,l){te=i,g("source-notice").hidden=!1,document.querySelector("#source-notice span").textContent=l,he()}g("draft-keep").onclick=()=>qt(bt(T.title)+"-draft.vector.json",JSON.stringify(T,null,2),"application/json");g("source-load").onclick=()=>{if(!te)return;qt(bt(T.title)+"-before-restore.vector.json",JSON.stringify(T,null,2),"application/json");let i=te;te=null,g("source-notice").hidden=!0,je(i),dt("Draft downloaded; source version restored")};g("save-source").onclick=W(async()=>{if(!(!Ut||te)){ue=!0,Ue++,he();try{let i=await fetch("/api/project",{method:"PUT",headers:{"content-type":"application/json","if-match":fe},body:JSON.stringify(T)}),l=await i.json();if(i.status===409){Ii(l.project,"The source changed. Keep your draft before switching versions.");return}if(!i.ok)throw new Error(l.error||"Save failed.");je(l.project),dt("Saved to workspace; previous source retained in history.")}finally{ue=!1,he()}}});async function _i(){if(location.protocol==="file:"||ue||pt)return;let i=++Ue;try{let l=await fetch("/api/project");if(!l.ok)return;let a=await l.json();if(i!==Ue||ue||pt||!a.project)return;Ut=!0;let h=Dt(a.project);h.revision!==fe&&(xt?Ii(h,"Your agent changed the source. Keep your draft before switching versions."):(je(h),dt("Agent changes loaded from source"))),he()}catch{}}document.addEventListener("keydown",i=>{i.target.closest("input,textarea,select")||((i.metaKey||i.ctrlKey)&&i.key.toLowerCase()==="z"&&(i.preventDefault(),(i.shiftKey?g("redo"):g("undo")).click()),i.key==="Escape"&&de("select"),i.key==="Enter"&&["boundary","exclusion"].includes(gt)&&W(Ve)())});new ResizeObserver(()=>{T&&V()}).observe(g("map"));try{let i=JSON.parse(localStorage.getItem(Ze));i?.project&&(T=Dt(i.project),fe=i.revision,Et=Ce(T),xt=!0,dt("Recovered your unsaved draft"))}catch{}Zt();_i();setInterval(_i,1800);window.vector={get project(){return Pt(T)},get plan(){return $},get evidence(){return It},get connected(){return Ut},get dirty(){return xt},screenPoint(i){let l=new DOMPoint(i[0],-i[1]).matrixTransform(g("map").getScreenCTM());return{x:l.x,y:l.y}},portable:wi};})();</script></body></html>diff --git a/store/agents/drone-pilot/template/flight/project.json b/store/agents/drone-pilot/template/flight/project.jsonnew file mode 100644index 000000000..8cc495ae6--- /dev/null+++ b/store/agents/drone-pilot/template/flight/project.json@@ -0,0 +1,94 @@+{+ "schema": "vector/2",+ "id": "alder-orchard",+ "title": "Alder Orchard",+ "brief": "Example geometry, not a surveyed or authorized site. Document the orchard blocks, avoid the irrigation pond and keep a return allowance in each sortie. Replace the boundary and camera with measured values before doing your own planning.",+ "origin": [+ -122.802,+ 38.466+ ],+ "home": [+ 20,+ 20+ ],+ "areas": [+ {+ "id": "orchard",+ "name": "Orchard blocks",+ "kind": "boundary",+ "locked": false,+ "ring": [+ [+ 0,+ 0+ ],+ [+ 420,+ 0+ ],+ [+ 420,+ 260+ ],+ [+ 280,+ 300+ ],+ [+ 0,+ 300+ ]+ ]+ },+ {+ "id": "pond",+ "name": "Irrigation pond",+ "kind": "exclusion",+ "locked": true,+ "ring": [+ [+ 200,+ 100+ ],+ [+ 265,+ 95+ ],+ [+ 285,+ 150+ ],+ [+ 240,+ 175+ ],+ [+ 200,+ 150+ ]+ ]+ }+ ],+ "camera": {+ "name": "Example camera — enter your measured specs",+ "sensorWidth": 13.2,+ "sensorHeight": 8.8,+ "focalLength": 8.8,+ "imageWidth": 5472,+ "imageHeight": 3648,+ "minInterval": 1+ },+ "settings": {+ "height": 55,+ "speed": 6,+ "angle": 0,+ "frontOverlap": 0.75,+ "sideOverlap": 0.7,+ "margin": 6,+ "usableMinutes": 14,+ "reservePercent": 20,+ "climbSpeed": 3,+ "descentSpeed": 2,+ "turnSeconds": 3+ }+}diff --git a/store/agents/drone-pilot/template/studio/app.js b/store/agents/drone-pilot/template/studio/app.jsnew file mode 100644index 000000000..7f27357dc--- /dev/null+++ b/store/agents/drone-pilot/template/studio/app.js@@ -0,0 +1,186 @@+import { validateProject, planProject, footprint, history, clone, ASSUMPTIONS } from './project.mjs';+import { bounds, distance, parseGeoJSON, flightRegion, pointIn, toLonLat } from './geo.mjs';+import { parseCSV, importFlight, analyzeFlight, verifyFlightSource } from './log.mjs';+import { geoJSON, photoCSV, routeCSV, flightCSV, kml, report as createReport, reportHTML, mapSVG, escapeHTML as esc, slug } from './formats.mjs';+import { zipFiles } from './archive.mjs';++const originalHTML = '<!doctype html>' + document.documentElement.outerHTML;+const payload = JSON.parse(document.getElementById('vector-data').textContent);+const $ = id => document.getElementById(id), $$ = selector => [...document.querySelectorAll(selector)];+const num = (n, digits=0) => n.toLocaleString(undefined,{maximumFractionDigits:digits,minimumFractionDigits:digits});+const uid = prefix => prefix + '-' + crypto.randomUUID().slice(0,8);+const notify = message => { $('status').textContent=message; };+const download = (name,body,type='application/octet-stream') => { const url=URL.createObjectURL(body instanceof Blob?body:new Blob([body],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000); };+let project=validateProject(payload.project), revision=project.revision, journal=history(project), plan=null, evidence=null, selected=null, selectedSortie=null, selectedPhoto=null, logSample=null, tool='select', drawn=[], view=null, logInput=null;+let connected=false,dirty=false,saving=false,pendingSource=null,pollEpoch=0,drag=null;+const draftKey='vector-draft:'+location.pathname+':'+location.port;+function guard(fn) { return async (...args) => { try { $$('.dialog-error').forEach(e=>e.remove()); await fn(...args); } catch(error) { notify(error.message); const dialog=document.querySelector('dialog[open]'); if(dialog){const message=document.createElement('p');message.className='dialog-error';message.setAttribute('role','alert');message.textContent=error.message;dialog.append(message);}else{$('plan-error').textContent=error.message;$('plan-error').hidden=false;} } }; }+function stash() { try { localStorage.setItem(draftKey,JSON.stringify({project,revision})); } catch { notify('Draft storage is full. Save a project file or save to the workspace.'); } }+function status() {+ $('save-state').textContent=dirty?'Unsaved draft':connected?'Saved in workspace':'Editable offline project';+ $('save-source').hidden=!connected;$('save-source').disabled=!dirty||saving||Boolean(pendingSource);+ $('undo').disabled=!journal.canUndo;$('redo').disabled=!journal.canRedo;$('deliver').disabled=!plan;+}+function change(edit,message='Plan updated') {+ const next=clone(project);edit(next);project=journal.push(next);dirty=true;rebuild();stash();notify(message);+}+async function open(next,message='Project opened as a draft') { const checked=validateProject(next);await verifyFlightSource(checked);project=journal.push(checked);selected=null;selectedSortie=null;view=null;dirty=true;rebuild();stash();notify(message); }+function resetSource(next) {project=validateProject(next);revision=project.revision;journal=history(project);dirty=false;selected=null;selectedSortie=null;view=null;try{localStorage.removeItem(draftKey);}catch{}rebuild();}+const input = (label,key,value,step=1,group='settings') => `<label>${esc(label)}<input type="number" data-field="${key}" data-group="${group}" value="${value}" step="${step}"></label>`;+function renderSettings() {+ const s=project.settings,c=project.camera;+ $('settings-panel').innerHTML=`<section><div class="section-title">CAPTURE GEOMETRY</div><div class="two">${input('Height above takeoff · m','height',s.height,1)}${input('Survey speed · m/s','speed',s.speed,.1)}</div><div class="two">${input('Front overlap · %','frontOverlap',s.frontOverlap*100,1)}${input('Side overlap · %','sideOverlap',s.sideOverlap*100,1)}</div><div class="two">${input('Line angle · degrees','angle',s.angle,1)}${input('Horizontal margin · m','margin',s.margin,.5)}</div><p>0° is east; 90° is north. Margins inset boundaries and expand exclusions. Image coverage can extend beyond the flight region.</p></section><section><div class="section-title">TIME PER SORTIE</div><div class="two">${input('Measured usable · min','usableMinutes',s.usableMinutes,.5)}${input('Reserve · %','reservePercent',s.reservePercent,1)}</div><div class="two">${input('Climb · m/s','climbSpeed',s.climbSpeed,.1)}${input('Descent · m/s','descentSpeed',s.descentSpeed,.1)}</div>${input('Allowance per capture run · s','turnSeconds',s.turnSeconds,.5)}<p>Return, climb and descent are included. A fixed turn allowance is not an aircraft dynamics model.</p></section><section><div class="section-title">YOUR CAMERA</div><label>Camera name<input id="camera-name" value="${esc(c.name)}" maxlength="120"></label><div class="two">${input('Sensor width · mm','sensorWidth',c.sensorWidth,.1,'camera')}${input('Sensor height · mm','sensorHeight',c.sensorHeight,.1,'camera')}</div><div class="two">${input('Focal length · mm','focalLength',c.focalLength,.1,'camera')}${input('Min. interval · s','minInterval',c.minInterval,.1,'camera')}</div><details><summary>Image dimensions</summary><div class="two">${input('Width · pixels','imageWidth',c.imageWidth,1,'camera')}${input('Height · pixels','imageHeight',c.imageHeight,1,'camera')}</div></details></section>`;+ $$('[data-field]').forEach(el=>el.onchange=guard(()=>change(p=>{let value=Number(el.value);if(!el.value.trim())throw new Error('Enter a value.');if(['frontOverlap','sideOverlap'].includes(el.dataset.field))value/=100;p[el.dataset.group][el.dataset.field]=value;})));+ $('camera-name').onchange=guard(e=>change(p=>{p.camera.name=e.target.value;}));+ const compare=document.createElement('button');compare.id='compare-angles';compare.textContent='Compare line directions ↗';compare.style.width='100%';compare.onclick=guard(compareAngles);$('settings-panel').querySelector('section').append(compare);+}+function renderMetrics() {+ const items=plan?[['Target area',num(plan.area/10000,2),'ha'],['Ground sampling',num(plan.camera.gsdX,2),'cm/px'],['Planned captures',num(plan.photos.length),'photos'],['Nominal coverage',num(plan.coverage*100,1),'%'],['Sorties',num(plan.sorties.length),'returns included'],['Nominal time',num(plan.totalSeconds/60,1),'min']]:[['Target area','—',''],['Ground sampling','—',''],['Planned captures','—',''],['Nominal coverage','—',''],['Sorties','—',''],['Nominal time','—','']];+ $('metrics').innerHTML=items.map(([label,value,unit])=>`<div class="metric"><small>${label}</small><b>${value}<em>${unit}</em></b></div>`).join('');+}+function renderAreas() {+ if(!project.areas.some(a=>a.id===selected))selected=null;+ $('area-count').textContent=project.areas.length;+ $('area-list').innerHTML=project.areas.map(a=>`<button class="area-row ${a.id===selected?'active':''}" data-area="${esc(a.id)}"><i style="background:${a.kind==='boundary'?'#829f72':'#cb8e7d'}"></i><span>${esc(a.name)}</span><small>${a.locked?'Locked':a.ring.length+' pts'}</small></button>`).join('');+ $$('[data-area]').forEach(el=>el.onclick=()=>{selected=el.dataset.area;renderAreas();renderMap();});+ const area=project.areas.find(a=>a.id===selected);+ $('area-editor').innerHTML=area?`<label>Layer name<input id="area-name" value="${esc(area.name)}" ${area.locked?'disabled':''}></label><div class="row-actions"><button id="lock-area">${area.locked?'Unlock geometry':'Lock geometry'}</button><button id="delete-area" ${area.locked?'disabled':''}>Remove</button></div><details><summary>Vertices · east, north meters</summary><textarea id="vertices" rows="6" ${area.locked?'disabled':''}>${area.ring.map(p=>p.map(n=>num(n,2).replaceAll(',','')).join(', ')).join('\n')}</textarea><button id="apply-vertices" ${area.locked?'disabled':''}>Apply vertices</button></details><p>${area.locked?'Unlock to change this geometry.':'Drag its corner handles on the map. Enter coordinates for precise edits.'}</p>`:'';+ if(area){$('area-name').onchange=guard(e=>change(p=>{p.areas.find(a=>a.id===selected).name=e.target.value;}));$('lock-area').onclick=guard(()=>change(p=>{const a=p.areas.find(a=>a.id===selected);a.locked=!a.locked;}));$('delete-area').onclick=guard(()=>change(p=>{p.areas=p.areas.filter(a=>a.id!==selected);}));$('apply-vertices').onclick=guard(()=>{const points=$('vertices').value.trim().split(/\n/).map(row=>row.split(',').map(v=>Number(v.trim())));change(p=>{p.areas.find(a=>a.id===selected).ring=points;});});}+}+function renderSorties() {+ if(selectedSortie&&!plan?.sorties.some(s=>s.id===selectedSortie))selectedSortie=null;+ $('sortie-list').innerHTML=plan?plan.sorties.map(s=>`<button class="sortie ${selectedSortie===s.id?'active':''}" data-sortie="${s.id}"><span class="row"><b>Sortie ${String(s.id).padStart(2,'0')}</b><span>${num(s.seconds/60,1)} min</span></span><small>${s.photos.length} captures · ${num(s.distance)} m · ${num(s.remainingSeconds)} s unused</small><div class="bar"><i style="width:${Math.min(100,s.seconds/plan.budgetSeconds*100)}%"></i></div></button>`).join(''):'<p>Resolve the planning issue to generate sorties.</p>';+ $$('[data-sortie]').forEach(el=>el.onclick=()=>{selectedSortie=Number(el.dataset.sortie);selectedPhoto=plan.sorties.find(s=>s.id===selectedSortie).photos[0].id;renderSorties();renderMap();});+ if(plan&&selectedSortie){const sortie=plan.sorties.find(s=>s.id===selectedSortie);if(!sortie.photos.some(p=>p.id===selectedPhoto))selectedPhoto=sortie.photos[0].id;const i=sortie.photos.findIndex(p=>p.id===selectedPhoto),p=sortie.photos[i],inspector=document.createElement('div');inspector.className='hint';inspector.innerHTML=`<label>Inspect planned capture<input id="inspect-photo" type="range" min="0" max="${sortie.photos.length-1}" value="${i}"></label><span id="photo-details">Photo ${p.id} · ${num(p.time/60,1)} min after takeoff</span><p>Outlined rectangle = ideal image footprint. Drag the slider to inspect each capture.</p>`;$('sortie-list').append(inspector);$('inspect-photo').oninput=e=>{const p=sortie.photos[Number(e.target.value)];selectedPhoto=p.id;$('photo-details').textContent=`Photo ${p.id} · ${num(p.time/60,1)} min after takeoff`;renderMap();};}+}+function renderEvidence() {+ const log=project.log;+ if(!log){$('evidence-panel').innerHTML='<section><div class="section-title">FROM PLAN TO EVIDENCE</div><p>Bring a flight CSV to inspect recorded positions, capture events, timing and gaps against this plan.</p><button id="import-log" class="primary">Import flight CSV…</button><p>Choose the columns and units yourself. The original CSV stays in your editable project and exported kit.</p><div class="hint">No flight has been recorded in this example.</div></section>';}+ else{const e=evidence;$('evidence-panel').innerHTML=`<section><div class="section-title">RECORDED SOURCE</div><strong style="font-size:12px;word-break:break-word">${esc(log.name)}</strong><p>${log.records.length} coordinate samples · ${log.sourceRows} source rows<br>${log.startTime?esc(log.startTime):'Elapsed time from first source row'}</p><div class="row-actions"><button id="import-log">Replace log</button><button id="remove-log">Remove</button></div><label>Compare nearest route<select id="compare-sortie"><option value="">All planned routes</option>${(plan?.sorties??[]).map(s=>`<option value="${s.id}" ${log.comparisonSortie===s.id?'selected':''}>Sortie ${s.id}</option>`).join('')}</select></label><label>Break track after a gap · seconds<input id="gap-limit" type="number" min=".1" max="120" step=".5" value="${log.maxGap??10}"></label>${e?`<div class="evidence-metrics"><div><b>${e.captureEvents}</b>Recorded capture events</div><div><b>${e.coverage===null?'—':num(e.coverage*100,1)+'%'}</b>Estimated event coverage</div><div><b>${num(e.deviationP95,1)} m</b>P95 nearest-route distance</div><div><b>${e.outsideSamples}</b>Positions outside flight area</div></div><p>${e.modeledCaptures} event footprints modeled; ${e.unmodeledCaptures} events lack height or heading. ${e.unknownCaptureSamples} samples have unknown capture state.</p><p>${e.discontinuities} track breaks · ${e.missingCoordinates} rows without coordinates · ${num(e.measuredDistance)} m connected track.</p><p>Recorded span ${num(e.elapsedSeconds/60,1)} min. Battery: ${e.startBattery===null?'unknown':num(e.startBattery)+'%'} → ${e.endBattery===null?'unknown':num(e.endBattery)+'%'}.</p><div class="hint">Event coverage is an estimate of the whole target. Images, camera orientation and mapping quality have not been verified.</div>`:'<p>Resolve the plan or comparison selection to analyze this log.</p>'}</section><details><summary>Column mapping & source hash</summary><pre style="font-size:9px;white-space:pre-wrap;word-break:break-word">${esc(JSON.stringify(log.mapping,null,2))}\nSHA-256 ${esc(log.sha256)}</pre></details>`;+ $('remove-log').onclick=guard(()=>change(p=>{delete p.log;},'Recorded log removed from draft'));+ $('compare-sortie').onchange=guard(e=>change(p=>{p.log.comparisonSortie=e.target.value?Number(e.target.value):null;}));+ $('gap-limit').onchange=guard(e=>change(p=>{const n=Number(e.target.value);if(n<.1||n>120)throw new Error('Use a gap threshold between 0.1 and 120 seconds.');p.log.maxGap=n;}));+ }+ $('import-log').onclick=()=>{$('log-file').value='';$('log-file').click();};+ if(log&&evidence){const inspector=document.createElement('section');logSample=Math.min(logSample??0,log.records.length-1);inspector.innerHTML=`<div class="section-title">INSPECT A LOG SAMPLE</div><input id="inspect-log" aria-label="Recorded sample" type="range" min="0" max="${log.records.length-1}" value="${logSample}"><p id="sample-details"></p>`;$('evidence-panel').append(inspector);const detail=()=>{const row=log.records[logSample];$('sample-details').textContent=`Row ${row.sourceRow} · ${num(row.time,1)} s · height ${row.altitude===null?'unknown':num(row.altitude,1)+' m'} · capture ${row.capture===null?'unknown':row.capture?'recorded':'no event'}`;};detail();$('inspect-log').oninput=e=>{logSample=Number(e.target.value);detail();renderMap();};}+ $('log-legend').hidden=!log;+}+function fit() {+ const b=bounds(project.areas.map(a=>a.ring)),rect=$('map').getBoundingClientRect(),aspect=Math.max(.5,rect.width/rect.height);+ const width=Math.max(b.size[0]*1.45,b.size[1]*1.75*aspect,60);view={center:b.min.map((n,i)=>(n+b.max[i])/2),width};+}+function renderMap() {+ if(!view)fit();const rect=$('map').getBoundingClientRect(),aspect=Math.max(.5,rect.width/rect.height),height=view.width/aspect,unit=view.width/Math.max(1,rect.width),v=view.center;+ $('map').setAttribute('viewBox',`${v[0]-view.width/2} ${-v[1]-height/2} ${view.width} ${height}`);+ const path=points=>points.map((p,i)=>(i?'L':'M')+p[0].toFixed(3)+' '+(-p[1]).toFixed(3)).join(' '),polygon=ring=>path(ring)+'Z';+ const grid=Math.pow(10,Math.floor(Math.log10(view.width/10))),gridSize=grid*(view.width/grid>25?5:1);+ let html=`<defs><pattern id="grid" width="${gridSize}" height="${gridSize}" patternUnits="userSpaceOnUse"><path d="M ${gridSize} 0 H 0 V ${gridSize}" fill="none" stroke="#d7decd" stroke-width="${unit*.55}"/></pattern><pattern id="hatch" width="${unit*7}" height="${unit*7}" patternUnits="userSpaceOnUse" patternTransform="rotate(40)"><line x1="0" x2="0" y2="${unit*7}" stroke="#c58870" stroke-width="${unit*1}" opacity=".35"/></pattern></defs><rect x="${v[0]-view.width/2}" y="${-v[1]-height/2}" width="${view.width}" height="${height}" fill="url(#grid)"/>`;+ for(const a of project.areas){const active=a.id===selected,exclude=a.kind==='exclusion';html+=`<path class="area" data-map-area="${esc(a.id)}" d="${polygon(a.ring)}" fill="${exclude?'#e9d7c6':'#d7e1c7'}" stroke="${active?'#48623c':exclude?'#b6806b':'#94a77f'}" stroke-width="${active?2:1.3}"/>`;if(exclude)html+=`<path pointer-events="none" d="${polygon(a.ring)}" fill="url(#hatch)"/>`;}+ if(plan){+ html+=`<path d="${plan.region.map(polygon).join(' ')}" fill="none" stroke="#91a278" stroke-width="1" stroke-dasharray="4 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`;+ if($('show-coverage').checked)html+=`<path d="${plan.covered.map(polygon).join(' ')}" fill="#75a895" fill-rule="evenodd" opacity=".3" pointer-events="none"/>`;+ if($('show-gaps').checked)html+=`<path d="${plan.gaps.map(polygon).join(' ')}" fill="#df9138" fill-rule="evenodd" opacity=".5" pointer-events="none"/>`;+ for(const s of plan.sorties){const visible=!selectedSortie||selectedSortie===s.id;html+=`<path d="${path(s.path)}" fill="none" stroke="${visible?'#c66537':'#aeb99d'}" stroke-width="${selectedSortie===s.id?2:1.2}" opacity="${visible?.85:.25}" vector-effect="non-scaling-stroke" pointer-events="none"/>`;if(visible)for(const photo of s.photos)html+=`<circle cx="${photo.point[0]}" cy="${-photo.point[1]}" r="${unit*(selectedSortie?2:1.4)}" fill="#a74f2b" pointer-events="none"/>`;}+ const shot=selectedSortie&&plan.photos.find(p=>p.id===selectedPhoto);if(shot)html+=`<path d="${polygon(footprint(shot.point,shot.heading,plan.camera.width,plan.camera.along))}" fill="#c65a32" fill-opacity=".12" stroke="#b45632" stroke-width="2" vector-effect="non-scaling-stroke" pointer-events="none"/><circle cx="${shot.point[0]}" cy="${-shot.point[1]}" r="${unit*4}" fill="#9a4024"/>`;+ }+ if(evidence){if($('show-coverage').checked)html+=`<path d="${evidence.covered.map(polygon).join(' ')}" fill="#328f97" fill-rule="evenodd" opacity=".22" pointer-events="none"/>`;for(const points of evidence.paths)html+=`<path d="${path(points)}" fill="none" stroke="#267d81" stroke-width="2.7" vector-effect="non-scaling-stroke" pointer-events="none"/>`;}+ if(evidence&&logSample!==null&&!$('evidence-panel').hidden){const row=project.log.records[logSample];html+=`<circle cx="${row.point[0]}" cy="${-row.point[1]}" r="${unit*6}" fill="#267d81" stroke="#fff" stroke-width="${unit*2}" pointer-events="none"/>`;}+ for(const a of project.areas){const b=bounds([a.ring]),mid=[(b.min[0]+b.max[0])/2,(b.min[1]+b.max[1])/2];if(a.kind==='exclusion')html+=`<text x="${mid[0]}" y="${-mid[1]}" fill="#976a55" text-anchor="middle" font-size="${unit*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#e9d7c6" stroke-width="${unit*3}">${esc(a.name)}</text>`;if(a.id===selected&&!a.locked)for(const [i,p] of a.ring.entries())html+=`<circle class="handle" data-handle="${i}" cx="${p[0]}" cy="${-p[1]}" r="${unit*5}" fill="#fffdf3" stroke="#526d42" stroke-width="1.5"/>`;}+ const [hx,hy]=project.home;html+=`<g data-home="true"><circle cx="${hx}" cy="${-hy}" r="${unit*9}" fill="#263d30" stroke="#fffdf3" stroke-width="${unit*2}"/><text x="${hx}" y="${-hy+unit*3.2}" text-anchor="middle" fill="#fffdf3" font-size="${unit*9}" font-family="system-ui">H</text></g><text x="${hx+unit*14}" y="${-hy+unit*3}" fill="#425d36" font-size="${unit*9}" font-family="system-ui" pointer-events="none" paint-order="stroke" stroke="#eef2e6" stroke-width="${unit*3}">TAKEOFF</text>`;+ if(drawn.length){html+=`<path d="${path(drawn)}" fill="none" stroke="#344f31" stroke-width="2" stroke-dasharray="5 4" vector-effect="non-scaling-stroke" pointer-events="none"/>`;for(const point of drawn)html+=`<circle cx="${point[0]}" cy="${-point[1]}" r="${unit*4}" fill="#344f31"/>`;}+ $('map').innerHTML=html;$('scale').textContent='Grid '+num(gridSize)+' m';+ $('map').style.cursor=tool==='select'?'default':'crosshair';+}+function rebuild() {+ let error='';try{plan=planProject(project);}catch(e){plan=null;error=e.message;}+ evidence=null;if(plan&&project.log)try{evidence=analyzeFlight(plan);}catch(e){error=e.message;}+ $('plan-error').hidden=!error;$('plan-error').textContent=error;+ $('project-title').textContent=project.title;$('map-title').textContent=project.title;+ $('map-subtitle').textContent=plan?`${plan.runs.length} survey runs · ${num(project.settings.height)} m above takeoff · ${num(project.settings.frontOverlap*100)} / ${num(project.settings.sideOverlap*100)}% overlap`:'Edit your boundary and planning settings';+ $('map-origin').textContent=`WGS 84 · ${project.origin[1].toFixed(5)}, ${project.origin[0].toFixed(5)}`;+ document.title=project.title+' · Vector';renderMetrics();renderSettings();renderAreas();renderSorties();renderEvidence();renderMap();status();+}+function point(event) { const p=new DOMPoint(event.clientX,event.clientY).matrixTransform($('map').getScreenCTM().inverse());return [Math.round(p.x*10)/10,Math.round(-p.y*10)/10]; }+function setTool(next) {tool=next;drawn=[];$$('[data-tool]').forEach(b=>b.classList.toggle('active',b.dataset.tool===tool));$('draw-help').hidden=!['boundary','exclusion'].includes(tool);renderMap();}+function finishDrawing(){if(drawn.length<3)throw new Error('Draw at least three different corners.');const id=uid(tool),ring=drawn.map(p=>[...p]);change(p=>{p.areas.push({id,name:tool==='boundary'?'New survey area':'New exclusion',kind:tool,locked:false,ring});},'Polygon added; drag its vertices or enter precise coordinates');selected=id;setTool('select');renderAreas();renderMap();}+$$('[data-tool]').forEach(b=>b.onclick=()=>setTool(b.dataset.tool));+$('finish-draw').onclick=guard(finishDrawing);$('cancel-draw').onclick=()=>setTool('select');+$('map').onpointerdown=event=>{+ if(event.button!==0)return;const p=point(event),handle=event.target.closest('[data-handle]'),home=event.target.closest('[data-home]'),area=event.target.closest('[data-map-area]');+ if(tool==='home'){guard(()=>change(next=>{next.home=p;},'Takeoff moved'))();setTool('select');return;}+ if(tool!=='select'){if(!drawn.length||distance(drawn.at(-1),p)>.2)drawn.push(p);renderMap();return;}+ if(handle){drag={kind:'vertex',index:Number(handle.dataset.handle),start:p,ring:clone(project.areas.find(a=>a.id===selected).ring),pointer:event.pointerId};}+ else if(home){drag={kind:'home',start:p,home:[...project.home],pointer:event.pointerId};}+ else if(area){selected=area.dataset.mapArea;renderAreas();renderMap();return;}+ else{drag={kind:'pan',start:p,center:[...view.center],pointer:event.pointerId};}+ $('map').setPointerCapture(event.pointerId);+};+$('map').onpointermove=event=>{if(!drag)return;const p=point(event);if(drag.kind==='pan'){view.center=view.center.map((n,i)=>n+drag.start[i]-p[i]);renderMap();}else{if(drag.kind==='home')project.home=p;else project.areas.find(a=>a.id===selected).ring[drag.index]=p;renderMap();}};+function endDrag(event,cancel=false){if(!drag)return;const d=drag;drag=null;if($('map').hasPointerCapture(d.pointer))$('map').releasePointerCapture(d.pointer);if(d.kind==='pan')return;const edited=clone(project);if(d.kind==='home')project.home=d.home;else project.areas.find(a=>a.id===selected).ring=d.ring;if(cancel){renderMap();return;}try{project=journal.push(edited);dirty=true;rebuild();stash();notify('Map geometry updated');}catch(error){renderMap();notify(error.message);}}+$('map').onpointerup=event=>endDrag(event);$('map').onpointercancel=event=>endDrag(event,true);+$('map').ondblclick=guard(()=>{if(['boundary','exclusion'].includes(tool))finishDrawing();});+$('map').addEventListener('wheel',event=>{event.preventDefault();if(!view)fit();view.width=Math.max(20,Math.min(15000,view.width*Math.exp(event.deltaY*.001)));renderMap();},{passive:false});+$('zoom-in').onclick=()=>{view.width=Math.max(20,view.width*.8);renderMap();};$('zoom-out').onclick=()=>{view.width=Math.min(15000,view.width/ .8);renderMap();};$('frame-site').onclick=()=>{fit();renderMap();};+$('undo').onclick=()=>{project=journal.undo();dirty=true;rebuild();stash();notify('Edit undone');};$('redo').onclick=()=>{project=journal.redo();dirty=true;rebuild();stash();notify('Edit restored');};+$('show-all').onclick=()=>{selectedSortie=null;renderSorties();renderMap();};$('show-coverage').onchange=renderMap;$('show-gaps').onchange=renderMap;+function tab(evidenceTab){$('plan-tab').classList.toggle('active',!evidenceTab);$('evidence-tab').classList.toggle('active',evidenceTab);$('settings-panel').hidden=evidenceTab;$('evidence-panel').hidden=!evidenceTab;renderMap();}+$('plan-tab').onclick=()=>tab(false);$('evidence-tab').onclick=()=>tab(true);+$$('[data-close]').forEach(b=>b.onclick=()=>b.closest('dialog').close());+$('model-details').onclick=()=>$('model-dialog').showModal();+$('project-details').onclick=()=>{$('title-input').value=project.title;$('brief-input').value=project.brief;$('origin-lon').value=project.origin[0];$('origin-lat').value=project.origin[1];$('project-dialog').showModal();};+$('apply-project').onclick=guard(()=>{const origin=[Number($('origin-lon').value),Number($('origin-lat').value)];if(project.log&&distance(origin,project.origin)>1e-10)throw new Error('Remove the recorded log before relocating this project.');change(p=>{p.title=$('title-input').value;p.brief=$('brief-input').value;p.origin=origin;});$('project-dialog').close();});+async function readFile(input,max=8000000){const file=input.files[0];if(!file)return null;if(file.size>max)throw new Error('Choose a file smaller than '+max/1000000+' MB.');let raw;try{raw=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(await file.arrayBuffer());}catch{throw new Error('Save this file as UTF-8 text before importing.');}return {name:file.name,raw};}+$('choose-project').onclick=()=>{$('project-file').value='';$('project-file').click();};+$('project-file').onchange=guard(async()=>{const file=await readFile($('project-file'));if(file){await open(JSON.parse(file.raw.replace(/^\uFEFF/,'')));$('open-dialog').close();}});+$('open-project').onclick=guard(async()=>{$('native-open').hidden=!connected;$('open-dialog').showModal();if(connected){const response=await fetch('/api/files'),result=await response.json();$('recent-projects').replaceChildren();for(const file of result.files??[]){const b=document.createElement('button');b.textContent=file.name+' · '+file.folder;b.onclick=guard(()=>openPath(file.path));$('recent-projects').append(b);}}});+async function openPath(path){const response=await fetch('/api/open',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({path})}),result=await response.json();if(!response.ok)throw new Error(result.error||'Could not open project.');await open(result.project);$('open-dialog').close();}+$('open-path').onclick=guard(()=>openPath($('project-path').value));+$('save-project').onclick=()=>download(slug(project.title)+'.vector.json',JSON.stringify(project,null,2),'application/json');+$('import-geo').onclick=()=>$('geo-dialog').showModal();$('choose-geo').onclick=()=>{$('geo-file').value='';$('geo-file').click();};+$('geo-file').onchange=guard(async()=>{+ const file=await readFile($('geo-file'),3000000);if(!file)return;const replace=$('geo-mode').value==='replace',kind=$('geo-kind').value;+ if(replace&&kind==='exclusion')throw new Error('Start a site with boundaries, then add exclusions.');+ const source=parseGeoJSON(JSON.parse(file.raw.replace(/^\uFEFF/,'')),replace?undefined:project.origin);if(!source.areas.length)throw new Error('Choose a file containing polygon boundaries.');+ const next=clone(project);if(replace){next.origin=source.origin;next.areas=[];next.id=uid('site');next.title=file.name.replace(/\.(geojson|json)$/i,'');next.brief='Site geometry imported from '+file.name+'. Review takeoff, exclusions, camera specifications and model assumptions.';delete next.log;}+ for(const area of source.areas){const areaKind=area.kind||kind;next.areas.push({id:uid(areaKind),name:area.name,kind:areaKind,locked:false,ring:area.boundary});for(const hole of area.holes)next.areas.push({id:uid('exclusion'),name:area.name+' interior',kind:'exclusion',locked:false,ring:hole});}+ const region=flightRegion(next.areas.filter(a=>a.kind==='boundary').map(a=>a.ring),next.areas.filter(a=>a.kind==='exclusion').map(a=>a.ring),next.settings.margin);+ if(replace||!pointIn(region,next.home)){let found=source.points.find(p=>pointIn(region,p.point))?.point;const b=bounds(region);for(let y=1;y<20&&!found;y++)for(let x=1;x<20&&!found;x++){const point=b.min.map((n,i)=>n+b.size[i]*(i?y:x)/20);if(pointIn(region,point))found=point;}if(!found)throw new Error('No takeoff position fits the current margin. Reduce the margin before importing.');next.home=found;}+ await open(next,'Site imported; review the proposed takeoff and capture settings');$('geo-dialog').close();+});+$('log-file').onchange=guard(async()=>{+ const file=await readFile($('log-file'),3000000);if(!file)return;const table=parseCSV(file.raw);logInput=file;$('log-name').textContent=file.name+' · '+table.rows.length+' source rows';+ const options=optional=>(optional?'<option value="">Not supplied</option>':'<option value="">Choose column…</option>')+table.headers.map(name=>`<option value="${esc(name)}">${esc(name)}</option>`).join('');+ $('log-mapping').innerHTML=['time','latitude','longitude','altitude','heading','battery','capture'].map(field=>`<label>${field[0].toUpperCase()+field.slice(1)} column<select data-map="${field}">${options(!['time','latitude','longitude'].includes(field))}</select></label>`).join('')+`<label>Time format<select data-map="timeUnit"><option value="seconds">Elapsed seconds</option><option value="milliseconds">Elapsed milliseconds</option><option value="iso">ISO 8601 with timezone</option></select></label><label>Altitude units<select data-map="altitudeUnit"><option value="meters">Meters</option><option value="feet">Feet</option></select></label><label>Altitude reference<select data-map="altitudeReference"><option value="takeoff">Height above takeoff</option><option value="amsl">AMSL elevation</option></select></label><label>Takeoff elevation · meters AMSL<input data-map="homeElevation" type="number" step="any" placeholder="Required for AMSL data"></label>`;+ $('log-dialog').showModal();+});+$('apply-log').onclick=guard(async()=>{const mapping=Object.fromEntries($$('[data-map]').map(el=>[el.dataset.map,el.dataset.map==='homeElevation'?(el.value.trim()?Number(el.value):null):el.value]));const log=await importFlight(logInput.raw,logInput.name,mapping,project.origin);change(p=>{p.log=log;},'Recorded flight imported with original CSV and column mapping');tab(true);$('log-dialog').close();});+function portable(){return originalHTML.replace(/(<script id="vector-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+JSON.stringify({project,licenses:payload.licenses}).replace(/</g,'\\u003c')+b);}+function requirePlan(){if(!plan)throw new Error('Resolve the planning issue before exporting.');if(project.log&&!evidence)throw new Error('Resolve the recorded-flight comparison before exporting.');return plan;}+async function compareAngles(){+ const baseline=clone(project),signature=JSON.stringify(project);let dialog=$('angles-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='angles-dialog';document.body.append(dialog);}+ dialog.innerHTML='<h2>Compare line directions</h2><p>Same site, camera, overlaps and time budget. Comparing 12 directions in 15° steps, plus your current angle. These are sampled alternatives, not a global optimum.</p><p id="angle-progress" role="status">Calculating…</p><div id="angle-results"></div><div class="dialog-actions"><button id="close-angles">Close</button></div>';dialog.showModal();$('close-angles').onclick=()=>dialog.close();+ const results=[],angles=[...new Set([baseline.settings.angle,...Array.from({length:12},(_,i)=>i*15)])];+ for(const angle of angles){await new Promise(r=>setTimeout(r,15));if(!dialog.open||JSON.stringify(project)!==signature)return;const candidate=clone(baseline);candidate.settings.angle=angle;try{const p=planProject(candidate);results.push({angle,minutes:p.totalSeconds/60,sorties:p.sorties.length,photos:p.photos.length,coverage:p.coverage});}catch(error){results.push({angle,error:error.message});}$('angle-progress').textContent=`Compared ${results.length} of ${angles.length} directions`;}results.sort((a,b)=>(a.error?Infinity:a.minutes)-(b.error?Infinity:b.minutes));+ $('angle-progress').textContent='Sorted by nominal total time. Compare coverage before applying a direction.';+ $('angle-results').innerHTML=results.map(r=>r.error?`<p>${r.angle}° · ${esc(r.error)}</p>`:`<button data-angle="${r.angle}" style="display:flex;width:100%;justify-content:space-between;margin:7px 0;font-size:11px"><b>${r.angle}°${r.angle===baseline.settings.angle?' · current':''}</b><span>${num(r.minutes,1)} min · ${r.sorties} sorties · ${num(r.coverage*100,1)}% coverage</span></button>`).join('');+ $$('[data-angle]').forEach(b=>b.onclick=guard(()=>{if(JSON.stringify(project)!==signature)throw new Error('The source changed during comparison. Run the comparison again.');change(p=>{p.settings.angle=Number(b.dataset.angle);},'Compared direction applied; other requirements preserved');dialog.close();}));+}+$('deliver').onclick=guard(()=>{const p=requirePlan();$('export-summary').textContent=`${project.title} · ${p.photos.length} planned captures · ${p.sorties.length} sorties · ${num(p.area/10000,2)} hectares`;$('export-dialog').showModal();});+$('export-geo').onclick=guard(()=>download(slug(project.title)+'.geojson',JSON.stringify(geoJSON(requirePlan()),null,2),'application/geo+json'));+$('export-kml').onclick=guard(()=>download(slug(project.title)+'.kml',kml(requirePlan()),'application/vnd.google-earth.kml+xml'));+$('export-report').onclick=guard(()=>download(slug(project.title)+'-report.html',reportHTML(requirePlan()),'text/html'));+$('export-kit').onclick=guard(()=>{+ const p=requirePlan(),files=[[slug(project.title)+'.vector.json',JSON.stringify(project,null,2)],['planner.html',portable()],['survey.geojson',JSON.stringify(geoJSON(p),null,2)],['overlay.kml',kml(p)],['site-map.svg',mapSVG(p)],['planned-photos.csv',photoCSV(p)],['planned-route.csv',routeCSV(p)],['report.json',JSON.stringify(createReport(p),null,2)],['report.html',reportHTML(p)],['LICENSES.txt',payload.licenses||'See the embedded upstream licenses in planner.html.'],['README.md',`# ${project.title}\n\n${project.brief}\n\nOpen planner.html to edit offline. Keep the .vector.json source. Load survey.geojson in GIS or overlay.kml in a map viewer; KML is ground-clamped. CSV coordinates are longitude/latitude degrees, with explicit height above takeoff and nominal timing. These files are for planning and review, not aircraft upload. Print report.html to PDF.\n\n${ASSUMPTIONS}\n\nA recorded CSV, if supplied, is retained unchanged with SHA-256 and explicit column/unit mapping. Event footprints do not prove image existence or quality.\n`]];+ if(project.log){files.push(['recorded-source.csv',project.log.raw],['recorded-normalized.csv',flightCSV(p)]);}+ download(slug(project.title)+'-field-kit.zip',zipFiles(files));notify('Field kit exported with editable source and review files');+});+function sourceNotice(next,message){pendingSource=next;$('source-notice').hidden=false;document.querySelector('#source-notice span').textContent=message;status();}+$('draft-keep').onclick=()=>download(slug(project.title)+'-draft.vector.json',JSON.stringify(project,null,2),'application/json');+$('source-load').onclick=()=>{if(!pendingSource)return;download(slug(project.title)+'-before-restore.vector.json',JSON.stringify(project,null,2),'application/json');const next=pendingSource;pendingSource=null;$('source-notice').hidden=true;resetSource(next);notify('Draft downloaded; source version restored');};+$('save-source').onclick=guard(async()=>{if(!connected||pendingSource)return;saving=true;pollEpoch++;status();try{const response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':revision},body:JSON.stringify(project)}),result=await response.json();if(response.status===409){sourceNotice(result.project,'The source changed. Keep your draft before switching versions.');return;}if(!response.ok)throw new Error(result.error||'Save failed.');resetSource(result.project);notify('Saved to workspace; previous source retained in history.');}finally{saving=false;status();}});+async function poll(){if(location.protocol==='file:'||saving||drag)return;const epoch=++pollEpoch;try{const response=await fetch('/api/project');if(!response.ok)return;const result=await response.json();if(epoch!==pollEpoch||saving||drag||!result.project)return;connected=true;const next=validateProject(result.project);if(next.revision!==revision){if(dirty)sourceNotice(next,'Your agent changed the source. Keep your draft before switching versions.');else{resetSource(next);notify('Agent changes loaded from source');}}status();}catch{}}+document.addEventListener('keydown',event=>{if(event.target.closest('input,textarea,select'))return;if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='z'){event.preventDefault();(event.shiftKey?$('redo'):$('undo')).click();}if(event.key==='Escape')setTool('select');if(event.key==='Enter'&&['boundary','exclusion'].includes(tool))guard(finishDrawing)();});+new ResizeObserver(()=>{if(project)renderMap();}).observe($('map'));+try{const saved=JSON.parse(localStorage.getItem(draftKey));if(saved?.project){project=validateProject(saved.project);revision=saved.revision;journal=history(project);dirty=true;notify('Recovered your unsaved draft');}}catch{}+rebuild();poll();setInterval(poll,1800);+window.vector={get project(){return clone(project);},get plan(){return plan;},get evidence(){return evidence;},get connected(){return connected;},get dirty(){return dirty;},screenPoint(point){const q=new DOMPoint(point[0],-point[1]).matrixTransform($('map').getScreenCTM());return {x:q.x,y:q.y};},portable};diff --git a/store/agents/drone-pilot/template/studio/archive.mjs b/store/agents/drone-pilot/template/studio/archive.mjsnew file mode 100644index 000000000..ff64bbf68--- /dev/null+++ b/store/agents/drone-pilot/template/studio/archive.mjs@@ -0,0 +1,20 @@+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.+export function zipFiles(files) {+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;+ for (const [name, body] of files) {+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);+ let crc = 0xffffffff;+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }+ crc = (crc ^ 0xffffffff) >>> 0;+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;+ }+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });+}diff --git a/store/agents/drone-pilot/template/studio/formats.mjs b/store/agents/drone-pilot/template/studio/formats.mjsnew file mode 100644index 000000000..871bc7d77--- /dev/null+++ b/store/agents/drone-pilot/template/studio/formats.mjs@@ -0,0 +1,57 @@+import { toLonLat, signedArea, pointIn, bounds } from './geo.mjs';+import { analyzeFlight } from './log.mjs';+import { ASSUMPTIONS } from './project.mjs';+export const escapeHTML = value => String(value).replace(/[&<>"']/g,c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+export const slug = value => String(value).normalize('NFKD').replace(/[\u0300-\u036f]/g,'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,70) || 'survey';+const csvCell = value => { const s = String(value ?? ''); return /[",\r\n]/.test(s) ? '"'+s.replace(/"/g,'""')+'"' : s; };+const csv = rows => rows.map(row => row.map(csvCell).join(',')).join('\r\n')+'\r\n';+const round = (n,d=3) => Number(n.toFixed(d));+export function regionGeometry(origin,rings) {+ const outers=rings.filter(r => signedArea(r)>0), holes=rings.filter(r => signedArea(r)<0);+ const closed=ring => [...ring,ring[0]].map(p => toLonLat(origin,p).map(n => round(n,9)));+ const owners=holes.map(hole=>outers.map((outer,i)=>({i,area:Math.abs(signedArea(outer)),contains:pointIn([outer],hole[0])})).filter(o=>o.contains).sort((a,b)=>a.area-b.area)[0]?.i);+ return {type:'MultiPolygon',coordinates:outers.map((outer,i) => [closed(outer),...holes.filter((_,j) => owners[j]===i).map(closed)])};+}+export function mapSVG(plan) {+ const b=bounds(plan.project.areas.map(a=>a.ring)),w=940,h=540,scale=Math.min((w-100)/b.size[0],(h-100)/b.size[1]),x=p=>50+(p[0]-b.min[0])*scale,y=p=>h-50-(p[1]-b.min[1])*scale;+ const path=points=>points.map((p,i)=>(i?'L':'M')+x(p).toFixed(2)+' '+y(p).toFixed(2)).join(' '),e=analyzeFlight(plan);+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" role="img" aria-label="Survey plan and recorded track" style="width:100%;height:auto;background:#f0f3e8;border-radius:8px"><title>${escapeHTML(plan.project.title)}</title>${plan.project.areas.map(a=>`<path d="${path(a.ring)}Z" fill="${a.kind==='exclusion'?'#e7d4c1':'#d8e3c7'}" stroke="${a.kind==='exclusion'?'#b78869':'#8fA579'}" stroke-width="1.5"/>`).join('')}${plan.sorties.map(s=>`<path d="${path(s.path)}" fill="none" stroke="#c26d43" stroke-width="1.25"/>`).join('')}${e?e.paths.map(points=>`<path d="${path(points)}" fill="none" stroke="#267d81" stroke-width="2.5"/>`).join(''):''}<circle cx="${x(plan.project.home)}" cy="${y(plan.project.home)}" r="7" fill="#28462e" stroke="white" stroke-width="2"/><text x="${x(plan.project.home)+12}" y="${y(plan.project.home)+4}" fill="#28462e" font-family="system-ui" font-size="11">Takeoff</text><text x="${w-40}" y="35" font-family="system-ui" font-size="17" fill="#7a8b6c">N ↑</text><text x="24" y="${h-16}" font-family="system-ui" font-size="11" fill="#68775a">Orange: planned routes${e?' · Teal: recorded track (gaps unconnected)':''} · Level-ground model</text></svg>`;+}+export function geoJSON(plan) {+ const p=plan.project, point=pnt => toLonLat(p.origin,pnt).map(n => round(n,9)), feature=(name,kind,geometry,extra={}) => ({type:'Feature',properties:{name,kind,...extra},geometry});+ const features=p.areas.map(area => feature(area.name,area.kind,{type:'Polygon',coordinates:[[...area.ring,area.ring[0]].map(point)]},{id:area.id,locked:area.locked}));+ features.push(feature('Takeoff','takeoff',{type:'Point',coordinates:point(p.home)}));+ features.push(feature('Inset flight region','flight-region',regionGeometry(p.origin,plan.region)));+ features.push(feature('Nominal image coverage','planned-footprints',regionGeometry(p.origin,plan.covered)));+ features.push(feature('Nominal coverage gaps','planned-gaps',regionGeometry(p.origin,plan.gaps)));+ for (const sortie of plan.sorties) features.push(feature('Sortie '+sortie.id,'planned-route',{type:'LineString',coordinates:sortie.path.map(point)},{sortie:sortie.id,heightAboveTakeoffM:p.settings.height,nominalSeconds:round(sortie.seconds)}));+ for (const photo of plan.photos) features.push(feature('Photo '+photo.id,'planned-photo',{type:'Point',coordinates:point(photo.point)},{photo:photo.id,sortie:photo.sortie,run:photo.run,secondsAfterTakeoff:round(photo.time),heightAboveTakeoffM:p.settings.height,headingDegreesFromNorth:round((90-photo.heading+360)%360)}));+ const evidence=analyzeFlight(plan);+ if(evidence){for(const [i,path] of evidence.paths.entries())if(path.length>1)features.push(feature('Recorded track '+(i+1),'recorded-track',{type:'LineString',coordinates:path.map(point)},{source:p.log.name,sha256:p.log.sha256}));if(evidence.covered.length)features.push(feature('Estimated recorded-event footprints','recorded-footprints',regionGeometry(p.origin,evidence.covered),{interpretation:evidence.interpretation}));}+ return {type:'FeatureCollection',name:p.title,assumptions:ASSUMPTIONS,features};+}+export function photoCSV(plan) {+ const p=plan.project;+ return csv([['photo','sortie','run','longitude_deg','latitude_deg','height_above_takeoff_m','heading_from_north_deg','nominal_elapsed_s'],...plan.photos.map(shot => [shot.id,shot.sortie,shot.run,...toLonLat(p.origin,shot.point).map(n => round(n,9)),p.settings.height,round((90-shot.heading+360)%360),round(shot.time)])]);+}+export function routeCSV(plan) {+ const p=plan.project,rows=[['sortie','sequence','phase','longitude_deg','latitude_deg','height_above_takeoff_m','nominal_elapsed_s']];+ for(const sortie of plan.sorties){let index=0;for(const leg of sortie.legs){let elapsed=leg.start;for(let i=0;i<leg.points.length;i++){if(i)elapsed+=Math.hypot(...leg.points[i].map((n,j)=>n-leg.points[i-1][j]))/p.settings.speed;rows.push([sortie.id,++index,leg.kind,...toLonLat(p.origin,leg.points[i]).map(n=>round(n,9)),p.settings.height,round(elapsed)]);}}}+ return csv(rows);+}+export function flightCSV(plan) {+ if(!plan.project.log)return null;+ return csv([['elapsed_s','longitude_deg','latitude_deg','height_above_takeoff_m','heading_from_north_deg','battery_percent','capture_event','break_before','source_row'],...plan.project.log.records.map(row=>[row.time,...toLonLat(plan.project.origin,row.point).map(n=>round(n,9)),row.altitude,row.heading,row.battery,row.capture===null?'':row.capture?1:0,row.breakBefore?1:0,row.sourceRow])]);+}+export function kml(plan) {+ const p=plan.project, coords=points=>points.map(point=>toLonLat(p.origin,point).map(n=>round(n,9)).join(',')+',0').join(' '), polygon=area=>`<Placemark><name>${escapeHTML(area.name)}</name><styleUrl>#${area.kind}</styleUrl><Polygon><altitudeMode>clampToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>${coords([...area.ring,area.ring[0]])}</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>`;+ return `<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>${escapeHTML(p.title)}</name><description>${escapeHTML(ASSUMPTIONS+' Map overlay only; all KML geometry is clamped to ground. Heights and photo timing are in the CSV files. This is not an aircraft mission file.')}</description><Style id="boundary"><LineStyle><color>ff5c794c</color><width>2</width></LineStyle><PolyStyle><color>334f7c5c</color></PolyStyle></Style><Style id="exclusion"><LineStyle><color>ff5353c2</color><width>2</width></LineStyle><PolyStyle><color>335353c2</color></PolyStyle></Style><Style id="route"><LineStyle><color>ff236cf0</color><width>2</width></LineStyle></Style>${p.areas.map(polygon).join('')}${plan.sorties.map(s=>`<Placemark><name>Sortie ${s.id} · ${(s.seconds/60).toFixed(1)} nominal minutes</name><styleUrl>#route</styleUrl><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>${coords(s.path)}</coordinates></LineString></Placemark>`).join('')}<Placemark><name>Takeoff</name><Point><coordinates>${coords([p.home])}</coordinates></Point></Placemark></Document></kml>`;+}+export function report(plan) {+ const evidence=analyzeFlight(plan);+ return {schema:'vector-report/2',project:plan.project.title,assumptions:ASSUMPTIONS,siteAreaM2:round(plan.area),camera:plan.camera,nominalCoveragePercent:round(plan.coverage*100),photos:plan.photos.length,flightLines:plan.runs.length,nominalDistanceM:round(plan.totalDistance),nominalSeconds:round(plan.totalSeconds),sortieBudgetSeconds:plan.budgetSeconds,sorties:plan.sorties.map(s=>({id:s.id,photos:s.photos.length,distanceM:round(s.distance),seconds:round(s.seconds),remainingBudgetSeconds:round(s.remainingSeconds)})),recorded:evidence?{...evidence,paths:undefined,covered:undefined,source:plan.project.log.name,sourceSHA256:plan.project.log.sha256,mapping:plan.project.log.mapping}:null};+}+export function reportHTML(plan) {+ const r=report(plan),p=plan.project,e=r.recorded,esc=escapeHTML;+ return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${esc(p.title)} · survey report</title><style>body{font:16px/1.6 system-ui;max-width:950px;padding:40px;margin:auto;color:#21362c}h1{font-size:42px;line-height:1.1}small{color:#57655c}table{border-collapse:collapse;width:100%}td,th{padding:10px;text-align:left;border-bottom:1px solid #dce4dc}section{margin:32px 0}.cards{display:flex;gap:30px;flex-wrap:wrap}.cards b{display:block;font-size:27px}pre{white-space:pre-wrap;word-break:break-word;font:12px monospace}button{padding:10px 15px}@media print{button{display:none}body{padding:0;font-size:13px;line-height:1.5}h1{font-size:32px}h2{font-size:19px;break-after:avoid}section{margin:18px 0}p,pre,tr,.cards,svg{break-inside:avoid}td,th{padding:7px 8px}.cards{gap:23px}.cards b{font-size:23px}pre{font-size:10px}svg{max-height:265px}table{break-inside:avoid}}@page{margin:18mm;@bottom-right{content:"Vector · " counter(page);font:9px system-ui;color:#60715e}}</style><small>VECTOR / FIELD SURVEY REPORT</small><h1>${esc(p.title)}</h1><p>${esc(p.brief)}</p><button onclick="print()">Print / Save PDF</button><section>${mapSVG(plan)}</section><section class="cards"><div><b>${(r.siteAreaM2/10000).toFixed(2)} ha</b>Supplied target area</div><div><b>${r.nominalCoveragePercent.toFixed(1)}%</b>Nominal footprint coverage</div><div><b>${r.photos}</b>Planned captures</div><div><b>${r.sorties.length}</b>Sorties</div></section><p>${esc(ASSUMPTIONS)}</p><p>GSD ${r.camera.gsdX.toFixed(2)} × ${r.camera.gsdY.toFixed(2)} cm/px; footprint ${r.camera.width.toFixed(1)} × ${r.camera.along.toFixed(1)} m. Height ${p.settings.height} m above takeoff; speed ${p.settings.speed} m/s. Requested front/side overlap ${(p.settings.frontOverlap*100).toFixed(0)}% / ${(p.settings.sideOverlap*100).toFixed(0)}%; overlaps apply along regular survey runs. Exclusions and boundaries can leave gaps.</p><p>Budget: ${p.settings.usableMinutes} measured usable minutes minus ${p.settings.reservePercent}% reserve. Nominal time includes climb, descent, survey, connected transits, configured turn allowance and a routed return to takeoff. No battery or flight-dynamics model is implied.</p><table><thead><tr><th>Sortie</th><th>Captures</th><th>Distance</th><th>Nominal duration</th><th>Unused budget</th></tr></thead><tbody>${r.sorties.map(s=>`<tr><td>${s.id}</td><td>${s.photos}</td><td>${s.distanceM.toFixed(0)} m</td><td>${(s.seconds/60).toFixed(1)} min</td><td>${s.remainingBudgetSeconds.toFixed(0)} s</td></tr>`).join('')}</tbody></table>${e?`<section><h2>Recorded evidence</h2><p>${esc(e.source)} · comparison: ${e.comparisonSortie?'sortie '+e.comparisonSortie:'all planned routes'}. ${esc(e.interpretation)}</p><p>${e.captureEvents} recorded capture events; ${e.modeledCaptures} footprint estimates; ${e.unmodeledCaptures} events lack height or heading. ${e.unknownCaptureSamples} samples have unknown capture state. Estimated event coverage of the whole target: ${e.coverage===null?'unavailable':(e.coverage*100).toFixed(1)+'%'}.</p><p>${e.outsideSamples} logged positions and ${e.outsideSegments} connected segments fall outside the inset flight area. ${e.discontinuities} track breaks; ${e.missingCoordinates} rows lack coordinates. Segments longer than ${e.maxGap} seconds are not connected. 95th-percentile distance from the nearest compared route: ${e.deviationP95.toFixed(1)} m.</p><pre>Source SHA-256: ${esc(e.sourceSHA256)}\nMapping: ${esc(JSON.stringify(e.mapping,null,2))}</pre></section>`:''}<section><h2>Files & coordinates</h2><p>GeoJSON and KML support map review; CSVs retain coordinates, height above takeoff and nominal timing. Keep planner.html and project JSON to edit. Origin: ${p.origin[0]}, ${p.origin[1]} (WGS 84 longitude, latitude); local vertices use east/north meters. Coordinate precision does not establish survey accuracy. No aircraft mission is included.</p></section></html>`;+}diff --git a/store/agents/drone-pilot/template/studio/geo.mjs b/store/agents/drone-pilot/template/studio/geo.mjsnew file mode 100644index 000000000..8a38de54f--- /dev/null+++ b/store/agents/drone-pilot/template/studio/geo.mjs@@ -0,0 +1,177 @@+import Clipper from './vendor/clipper.cjs';++// Small-site coordinates: WGS 84 ECEF projected into the origin's east/north plane.+// Clipping uses integer millimeters. No map or location is sent to a remote service.+const A = 6378137, F = 1 / 298.257223563, E2 = F * (2 - F), B = A * (1 - F);+const rad = n => n * Math.PI / 180, deg = n => n * 180 / Math.PI;+const SCALE = 1000, EPS = 1e-8;+export const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);+export const length = points => points.slice(1).reduce((n, p, i) => n + distance(points[i], p), 0);+export const cross = (a, b) => a[0] * b[1] - a[1] * b[0];+export const signedArea = ring => ring.reduce((n, p, i) => n + cross(p, ring[(i + 1) % ring.length]), 0) / 2;+export const regionArea = rings => Math.abs(rings.reduce((n, ring) => n + signedArea(ring), 0));+const toPath = ring => ring.map(([x, y]) => ({ X: Math.round(x * SCALE), Y: Math.round(y * SCALE) }));+const fromPath = path => path.map(p => [p.X / SCALE, p.Y / SCALE]);+export function orient(ring, positive = true) {+ const result = ring.map(p => [...p]);+ if ((signedArea(result) > 0) !== positive) result.reverse();+ return result;+}+export function lonLat(value) {+ if (!Array.isArray(value) || value.length < 2 || !Number.isFinite(value[0]) || Math.abs(value[0]) > 180 || !Number.isFinite(value[1]) || Math.abs(value[1]) > 85) throw new Error('Use WGS 84 longitude, latitude coordinates between 85° south and north.');+ return value.slice(0, 2);+}+function ecef(value) {+ const [longitude, latitude] = lonLat(value).map(rad), n = A / Math.sqrt(1 - E2 * Math.sin(latitude) ** 2);+ return [n * Math.cos(latitude) * Math.cos(longitude), n * Math.cos(latitude) * Math.sin(longitude), n * (1 - E2) * Math.sin(latitude)];+}+export function toLocal(origin, coordinate) {+ const [longitude, latitude] = lonLat(origin).map(rad), center = ecef(origin), delta = ecef(coordinate).map((n, i) => n - center[i]);+ if (Math.hypot(...delta) > 5000) throw new Error('Keep each site within 5 km of its map origin. Split a larger job into sites.');+ return [-Math.sin(longitude) * delta[0] + Math.cos(longitude) * delta[1], -Math.sin(latitude) * Math.cos(longitude) * delta[0] - Math.sin(latitude) * Math.sin(longitude) * delta[1] + Math.cos(latitude) * delta[2]];+}+export function toLonLat(origin, point) {+ const [longitude, latitude] = lonLat(origin).map(rad), [e, n] = point, center = ecef(origin);+ if (!point.every(Number.isFinite) || Math.hypot(e, n) > 5000) throw new Error('A site coordinate is outside the supported local map.');+ const x = center[0] - Math.sin(longitude) * e - Math.sin(latitude) * Math.cos(longitude) * n;+ const y = center[1] + Math.cos(longitude) * e - Math.sin(latitude) * Math.sin(longitude) * n;+ const z = center[2] + Math.cos(latitude) * n, p = Math.hypot(x, y), theta = Math.atan2(z * A, p * B);+ const lon=deg(Math.atan2(y,x)),lat=deg(Math.atan2(z + E2 / (1 - E2) * B * Math.sin(theta) ** 3, p - E2 * A * Math.cos(theta) ** 3));+ return lonLat([lon===180?-180:lon,lat]);+}+export function bounds(rings) {+ const points = rings.flat();+ if (!points.length) return { min: [0, 0], max: [1, 1], size: [1, 1] };+ const min = [0, 1].map(i => Math.min(...points.map(p => p[i]))), max = [0, 1].map(i => Math.max(...points.map(p => p[i])));+ return { min, max, size: max.map((n, i) => n - min[i]) };+}+function cutParameters(a, b, c, d) {+ const u = b.map((n, i) => n - a[i]), v = d.map((n, i) => n - c[i]), q = c.map((n, i) => n - a[i]), den = cross(u, v);+ if (Math.abs(den) < EPS) {+ if (Math.abs(cross(q, u)) > EPS) return [];+ const axis = Math.abs(u[0]) > Math.abs(u[1]) ? 0 : 1;+ if (Math.abs(u[axis]) < EPS) return [];+ return [c, d].map(p => (p[axis] - a[axis]) / u[axis]).filter(t => t >= -EPS && t <= 1 + EPS);+ }+ const t = cross(q, v) / den, s = cross(q, u) / den;+ return t >= -EPS && t <= 1 + EPS && s >= -EPS && s <= 1 + EPS ? [Math.max(0, Math.min(1, t))] : [];+}+export function validateRing(input, label = 'Boundary') {+ if (!Array.isArray(input)) throw new Error(label + ' needs polygon vertices.');+ const ring = input.map(p => {+ if (!Array.isArray(p) || p.length !== 2 || !p.every(Number.isFinite) || Math.hypot(...p) > 5000) throw new Error(label + ' has an invalid local coordinate.');+ return [...p];+ });+ if (ring.length > 3 && distance(ring[0], ring.at(-1)) < .001) ring.pop();+ if (ring.length < 3 || ring.length > 128 || Math.abs(signedArea(ring)) < 1) throw new Error(label + ' needs 3–128 vertices and at least one square meter.');+ for (let i = 0; i < ring.length; i++) {+ if (distance(ring[i], ring[(i + 1) % ring.length]) < .01) throw new Error(label + ' has duplicate or nearly identical vertices.');+ for (let j = i + 1; j < ring.length; j++) {+ if (j === i + 1 || (i === 0 && j === ring.length - 1)) continue;+ if (cutParameters(ring[i], ring[(i + 1) % ring.length], ring[j], ring[(j + 1) % ring.length]).length) throw new Error(label + ' crosses itself. Move the crossing vertices.');+ }+ }+ return orient(ring);+}+function boolean(subject, clip, type) {+ if (!subject.length) return [];+ const operation = new Clipper.Clipper(); operation.StrictlySimple = true;+ operation.AddPaths(subject.map(toPath), Clipper.PolyType.ptSubject, true);+ if (clip.length) operation.AddPaths(clip.map(toPath), Clipper.PolyType.ptClip, true);+ const out = new Clipper.Paths();+ operation.Execute(type, out, Clipper.PolyFillType.pftNonZero, Clipper.PolyFillType.pftNonZero);+ return out.map(fromPath).filter(p => p.length >= 3 && Math.abs(signedArea(p)) > .000001);+}+export const union = rings => boolean(rings, [], Clipper.ClipType.ctUnion);+export const difference = (a, b) => boolean(a, b, Clipper.ClipType.ctDifference);+export const intersection = (a, b) => b.length ? boolean(a, b, Clipper.ClipType.ctIntersection) : [];+export function offset(rings, meters) {+ if (Math.abs(meters) < .0001) return rings.map(r => r.map(p => [...p]));+ const operation = new Clipper.ClipperOffset(2, .02 * SCALE), out = new Clipper.Paths();+ operation.AddPaths(rings.map(toPath), Clipper.JoinType.jtMiter, Clipper.EndType.etClosedPolygon);+ operation.Execute(out, meters * SCALE); return out.map(fromPath);+}+export function flightRegion(boundaries, exclusions, margin) {+ return difference(offset(union(boundaries), -margin), offset(union(exclusions), margin));+}+export function pointIn(rings, point) {+ const probe = { X: Math.round(point[0] * SCALE), Y: Math.round(point[1] * SCALE) }; let inside = false;+ for (const ring of rings) { const result = Clipper.Clipper.PointInPolygon(probe, toPath(ring)); if (result === -1) return true; if (result === 1) inside = !inside; }+ return inside;+}+export function segmentWithin(rings, a, b) {+ if (!pointIn(rings, a) || !pointIn(rings, b)) return false;+ const cuts = [0, 1];+ for (const ring of rings) for (let i = 0; i < ring.length; i++) cuts.push(...cutParameters(a, b, ring[i], ring[(i + 1) % ring.length]));+ cuts.sort((a, b) => a - b);+ for (let i = 1; i < cuts.length; i++) { const t = (cuts[i - 1] + cuts[i]) / 2; if (!pointIn(rings, a.map((n, j) => n + (b[j] - n) * t))) return false; }+ return true;+}+export function transects(rings, spacing, angleDegrees) {+ if (!rings.length) return [];+ if (!Number.isFinite(spacing) || spacing < .5) throw new Error('Flight lines must be at least 0.5 m apart.');+ const angle = rad(angleDegrees), along = [Math.cos(angle), Math.sin(angle)], across = [-along[1], along[0]], dot = (a, b) => a[0] * b[0] + a[1] * b[1];+ const points = rings.flat(), lo = Math.min(...points.map(p => dot(p, across))), hi = Math.max(...points.map(p => dot(p, across))), u0 = Math.min(...points.map(p => dot(p, along))) - 1, u1 = Math.max(...points.map(p => dot(p, along))) + 1;+ const count = Math.max(1, Math.ceil((hi - lo) / spacing)); if (count > 1000) throw new Error('This requires more than 1,000 flight lines. Split the site or revise capture requirements.');+ const rows = [];+ for (let i = 0; i < count; i++) {+ const v = lo + (i + .5) * (hi - lo) / count, end = u => along.map((n, j) => n * u + across[j] * v), operation = new Clipper.Clipper(), tree = new Clipper.PolyTree();+ operation.AddPath(toPath([end(u0), end(u1)]), Clipper.PolyType.ptSubject, false); operation.AddPaths(rings.map(toPath), Clipper.PolyType.ptClip, true);+ operation.Execute(Clipper.ClipType.ctIntersection, tree, Clipper.PolyFillType.pftNonZero, Clipper.PolyFillType.pftNonZero);+ const spans = Clipper.Clipper.OpenPathsFromPolyTree(tree).map(fromPath).map(path => path.sort((a, b) => dot(a, along) - dot(b, along))).filter(path => length(path) > .1).sort((a, b) => dot(a[0], along) - dot(b[0], along));+ if (i % 2) { spans.reverse(); spans.forEach(path => path.reverse()); }+ for (const path of spans) rows.push({ row: i, a: path[0], b: path.at(-1), length: distance(path[0], path.at(-1)) });+ }+ return rows;+}+export function navigatorFor(rings) {+ const seen = new Set(), vertices = rings.flat().filter(p => { const key = p.join(','); if (seen.has(key)) return false; seen.add(key); return true; });+ if (vertices.length > 350) throw new Error('Simplify the boundary/exclusions to fewer than 350 offset corners before routing.');+ const adjacency = vertices.map(() => []);+ for (let i = 0; i < vertices.length; i++) for (let j = i + 1; j < vertices.length; j++) if (segmentWithin(rings, vertices[i], vertices[j])) { const cost = distance(vertices[i], vertices[j]); adjacency[i].push([j, cost]); adjacency[j].push([i, cost]); }+ return (start, end) => {+ if (segmentWithin(rings, start, end)) return [start, end];+ if (!pointIn(rings, start) || !pointIn(rings, end)) return null;+ const n = vertices.length, points = [...vertices, start, end], edges = adjacency.map(row => [...row]); edges.push([], []);+ for (let j = n; j < n + 2; j++) for (let i = 0; i < n; i++) if (segmentWithin(rings, points[i], points[j])) { const cost = distance(points[i], points[j]); edges[i].push([j, cost]); edges[j].push([i, cost]); }+ const costs = new Float64Array(n + 2).fill(Infinity), previous = new Int32Array(n + 2).fill(-1), visited = new Uint8Array(n + 2); costs[n] = 0;+ for (let k = 0; k < n + 2; k++) {+ let at = -1; for (let i = 0; i < n + 2; i++) if (!visited[i] && (at === -1 || costs[i] < costs[at])) at = i;+ if (at === -1 || !Number.isFinite(costs[at])) return null;+ if (at === n + 1) { const path = []; for (let i = at; i !== -1; i = previous[i]) path.push(points[i]); return path.reverse(); }+ visited[at] = 1; for (const [next, cost] of edges[at]) if (costs[at] + cost < costs[next]) { costs[next] = costs[at] + cost; previous[next] = at; }+ }+ return null;+ };+}+export function parseGeoJSON(value, origin) {+ if (value?.crs) throw new Error('Export the boundary as standard WGS 84 GeoJSON without a custom CRS.');+ const polygons = [], points = [];+ function read(geometry, name = 'Imported area', depth = 0, kind = null) {+ if (!geometry || depth > 8) throw new Error('Invalid GeoJSON geometry.');+ if (geometry.crs) throw new Error('Use standard WGS 84 GeoJSON without a custom CRS.');+ if (geometry.type === 'FeatureCollection') { if (!Array.isArray(geometry.features) || geometry.features.length > 32) throw new Error('Import at most 32 site features.'); for (const f of geometry.features) read(f, name, depth + 1); }+ else if (geometry.type === 'Feature') read(geometry.geometry, String(geometry.properties?.name || name).slice(0, 100), depth + 1, ['boundary','exclusion'].includes(geometry.properties?.kind) ? geometry.properties.kind : kind);+ else if (geometry.type === 'Polygon') polygons.push({ name, kind, coordinates: geometry.coordinates });+ else if (geometry.type === 'MultiPolygon') { if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length > 32) throw new Error('Import at most 32 polygons.'); for (const coordinates of geometry.coordinates) polygons.push({ name, kind, coordinates }); }+ else if (geometry.type === 'Point') points.push({ name, coordinate: lonLat(geometry.coordinates) });+ else throw new Error('Import polygon boundaries and optional point markers. Lines and geometry collections need conversion first.');+ }+ read(value); if (!polygons.length && !points.length) throw new Error('No site geometry was found.');+ if (polygons.length + points.length > 32) throw new Error('Import at most 32 polygons and markers.');+ const center = lonLat(origin || polygons[0]?.coordinates?.[0]?.[0] || points[0].coordinate);+ const areas = polygons.map(({ name, kind, coordinates }) => {+ if (!Array.isArray(coordinates) || !coordinates.length || coordinates.length > 21) throw new Error('Invalid polygon rings.');+ const rings = coordinates.map((ring, i) => {+ if (!Array.isArray(ring) || ring.length < 4 || distance(lonLat(ring[0]), lonLat(ring.at(-1))) > EPS) throw new Error('GeoJSON polygon rings must be closed.');+ return validateRing(ring.map(p => toLocal(center, lonLat(p))), name + (i ? ' hole' : ''));+ });+ const holes = rings.slice(1);+ for (let i = 0; i < holes.length; i++) {+ if (regionArea(difference([holes[i]], [rings[0]])) > .01) throw new Error(name + ' has a hole outside its boundary.');+ if (holes.slice(0, i).some(other => regionArea(intersection([other], [holes[i]])) > .01)) throw new Error(name + ' has overlapping holes.');+ }+ return { name, kind, boundary: rings[0], holes };+ });+ return { origin: center, areas, points: points.map(p => ({ name: p.name, point: toLocal(center, p.coordinate) })) };+}diff --git a/store/agents/drone-pilot/template/studio/icon.svg b/store/agents/drone-pilot/template/studio/icon.svgnew file mode 100644index 000000000..d5dcec7c5--- /dev/null+++ b/store/agents/drone-pilot/template/studio/icon.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+ <title>Drone Pilot — vector through a gate</title>+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#18323b"/>+ <path d="m48 17 27 15v32L48 79 21 64V32Z" fill="none" stroke="#739798" stroke-width="5" stroke-linejoin="round"/>+ <path d="m29 60 34-31-9 40-8-15Z" fill="#d3eb9c"/>+ <path d="m21 75 9-9" stroke="#d3eb9c" stroke-width="5" stroke-linecap="round"/>+</svg>diff --git a/store/agents/drone-pilot/template/studio/log.mjs b/store/agents/drone-pilot/template/studio/log.mjsnew file mode 100644index 000000000..76edbf8e4--- /dev/null+++ b/store/agents/drone-pilot/template/studio/log.mjs@@ -0,0 +1,102 @@+import { toLocal, pointIn, segmentWithin, distance, union, intersection, regionArea } from './geo.mjs';+import { cameraGeometry, footprint } from './project.mjs';++export function parseCSV(text) {+ if (typeof text !== 'string' || new TextEncoder().encode(text).length > 3000000) throw new Error('Use a UTF-8 CSV smaller than 3 MB.');+ text = text.replace(/^\uFEFF/, ''); const rows = []; let row = [], field = '', quoted = false, ended = false;+ for (let i = 0; i <= text.length; i++) {+ const c = text[i];+ if (quoted) { if (c === undefined) throw new Error('The CSV has an unclosed quote.'); if (c === '"') { if (text[i + 1] === '"') { field += '"'; i++; } else { quoted = false; ended = true; } } else field += c; }+ else if (c === '"') { if (field.length || ended) throw new Error('A CSV quote is in the wrong position.'); quoted = true; }+ else if (c === ',' || c === '\n' || c === '\r' || c === undefined) {+ row.push(field); field = ''; ended = false;+ if (row.length > 80) throw new Error('Use a CSV with at most 80 columns.');+ if (c !== ',') { if (row.some(v => v.trim())) rows.push(row); row = []; if (c === '\r' && text[i + 1] === '\n') i++; }+ } else { if (ended) throw new Error('Unexpected content after a quoted CSV field.'); field += c; }+ if (rows.length > 12001) throw new Error('Use at most 12,000 recorded samples.');+ }+ const headers = rows.shift()?.map(v => v.trim());+ if (!headers?.length || headers.some(v => !v) || new Set(headers).size !== headers.length) throw new Error('CSV column names must be present and unique.');+ if (rows.length < 2 || rows.some(row => row.length !== headers.length)) throw new Error('Use at least two data rows, with the same columns as the header.');+ return { headers, rows };+}+export async function importFlight(raw, name, mapping, origin) {+ const table = parseCSV(raw), required = ['time', 'latitude', 'longitude'];+ for (const field of required) if (!table.headers.includes(mapping[field])) throw new Error('Choose a ' + field + ' column.');+ for (const field of ['altitude', 'battery', 'heading', 'capture']) if (mapping[field] && !table.headers.includes(mapping[field])) throw new Error('Unknown ' + field + ' column.');+ if (!['seconds', 'milliseconds', 'iso'].includes(mapping.timeUnit)) throw new Error('Choose elapsed seconds, elapsed milliseconds or ISO 8601 with timezone.');+ if (mapping.altitude && (!['meters', 'feet'].includes(mapping.altitudeUnit) || !['takeoff', 'amsl'].includes(mapping.altitudeReference))) throw new Error('Choose altitude units and reference.');+ if (mapping.altitudeReference === 'amsl' && (!Number.isFinite(mapping.homeElevation) || mapping.homeElevation < -500 || mapping.homeElevation > 9000)) throw new Error('Provide takeoff elevation in meters AMSL to convert the log.');+ const at = Object.fromEntries(Object.entries(mapping).map(([key, name]) => [key, table.headers.indexOf(name)]));+ const records = []; let firstTime = null, previous = -Infinity, missingCoordinates = 0, pendingBreak = false;+ const numeric = (value, label, required = false) => { if (!value?.trim()) { if (required) throw new Error(label + ' is missing.'); return null; } const n = Number(value); if (!Number.isFinite(n)) throw new Error(label + ' is not a finite number.'); return n; };+ for (let i = 0; i < table.rows.length; i++) {+ const row = table.rows[i], get = field => at[field] < 0 ? '' : row[at[field]], label = 'CSV row ' + (i + 2); let time;+ if (mapping.timeUnit === 'iso') {+ const value=get('time'),parts=value?.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$/);+ if(!parts||!Number.isFinite(Date.parse(value)))throw new Error(label + ': use ISO 8601 timestamps with an explicit timezone.');+ const [year,month,day,hour,minute,second]=parts.slice(1,7).map(Number),leap=year%4===0&&(year%100!==0||year%400===0),days=[31,leap?29:28,31,30,31,30,31,31,30,31,30,31];+ if(month<1||month>12||day<1||day>days[month-1]||hour>23||minute>59||second>59)throw new Error(label+': the timestamp is not a valid calendar date and time.');+ time=Date.parse(value)/1000;+ }+ else time = numeric(get('time'), label + ' time', true) / (mapping.timeUnit === 'milliseconds' ? 1000 : 1);+ if (time <= previous) throw new Error(label + ': timestamps must be strictly increasing. Split repeated flights before importing.');+ previous = time; if (firstTime === null) firstTime = time;+ if (time - firstTime > 172800) throw new Error('A flight log must span no more than 48 hours.');+ const lat = numeric(get('latitude'), label + ' latitude'), lon = numeric(get('longitude'), label + ' longitude');+ if (lat === null || lon === null) { missingCoordinates++; pendingBreak = true; continue; }+ const point = toLocal(origin, [lon, lat]);+ let altitude = numeric(get('altitude'), label + ' altitude'), battery = numeric(get('battery'), label + ' battery'), heading = numeric(get('heading'), label + ' heading'), capture = null;+ if (altitude !== null) { altitude *= mapping.altitudeUnit === 'feet' ? .3048 : 1; if (mapping.altitudeReference === 'amsl') altitude -= mapping.homeElevation; if (altitude < -1000 || altitude > 10000) throw new Error(label + ': altitude is outside the supported range.'); }+ if (battery !== null && (battery < 0 || battery > 100)) throw new Error(label + ': battery must be a percentage from 0 to 100.');+ if (heading !== null && (heading < 0 || heading > 360)) throw new Error(label + ': heading must be degrees clockwise from north, 0–360.');+ if (get('capture')?.trim()) { const value = get('capture').trim().toLowerCase(); if (['1', 'true', 'yes'].includes(value)) capture = true; else if (['0', 'false', 'no'].includes(value)) capture = false; else throw new Error(label + ': capture events must be 1/0, true/false, yes/no, or blank for unknown.'); }+ records.push({ time: time - firstTime, point, altitude, battery, heading, capture, sourceRow: i + 2, breakBefore: pendingBreak }); pendingBreak = false;+ }+ if (records.length < 2) throw new Error('At least two rows need valid coordinates.');+ if (records.filter(r => r.capture).length > 3000) throw new Error('Use at most 3,000 recorded capture events per site.');+ const sha256 = [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw)))].map(n => n.toString(16).padStart(2, '0')).join('');+ return { name, sha256, mapping: { ...mapping }, raw, sourceRows: table.rows.length, missingCoordinates, startTime: mapping.timeUnit === 'iso' ? new Date(firstTime * 1000).toISOString() : null, records };+}+export async function verifyFlightSource(project) {+ if (!project.log) return;+ const log=project.log, rebuilt=await importFlight(log.raw,log.name,log.mapping,project.origin);+ for (const field of ['sha256','sourceRows','missingCoordinates','startTime']) if (JSON.stringify(log[field])!==JSON.stringify(rebuilt[field])) throw new Error('Recorded '+field+' differs from the retained CSV and mapping. Reimport the original flight instead of editing evidence.');+ if(log.records.length!==rebuilt.records.length)throw new Error('Recorded samples differ from the retained CSV.');+ for(let i=0;i<log.records.length;i++){+ const a=log.records[i],b=rebuilt.records[i];+ // Math.sin/cos can differ between browser/Node V8 versions. Ten micrometers is+ // below our 1 mm clipping resolution; original geographic coordinates stay in raw CSV.+ if(distance(a.point,b.point)>1e-5||['time','altitude','battery','heading','capture','sourceRow','breakBefore'].some(key=>a[key]!==b[key]))throw new Error('Recorded samples differ from the retained CSV and mapping. Reimport the original flight instead of editing evidence.');+ }+}+export function analyzeFlight(plan, log = plan.project.log, maxGap = log?.maxGap ?? 10) {+ if (!log) return null;+ if (!Number.isFinite(maxGap) || maxGap < .1 || maxGap > 120) throw new Error('Choose a continuity limit between 0.1 and 120 seconds.');+ const p = plan.project, records = log.records, paths = []; let path = [], measuredDistance = 0, discontinuities = 0, outsideSegments = 0;+ const compared = log.comparisonSortie ? plan.sorties.filter(s => s.id === log.comparisonSortie) : plan.sorties;+ if (!compared.length) throw new Error('The recorded flight refers to a sortie this revision no longer has. Choose the comparison again.');+ const segments = compared.flatMap(s => s.path.slice(1).map((b,i) => [s.path[i],b]));+ function pointToSegment(p,a,b) { const dx=b[0]-a[0],dy=b[1]-a[1],square=dx*dx+dy*dy,t=square ? Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/square)) : 0; return distance(p,[a[0]+t*dx,a[1]+t*dy]); }+ const deviations = records.map(row => Math.min(...segments.map(([a,b]) => pointToSegment(row.point,a,b)))).sort((a,b) => a-b);+ let outsideSamples = 0, captureEvents = 0, unmodeledCaptures = 0, unknownCaptureSamples = 0; const modeled = [];+ for (let i = 0; i < records.length; i++) {+ const row = records[i], previous = records[i - 1];+ if (!pointIn(plan.region, row.point)) outsideSamples++;+ if (previous && (row.breakBefore || row.time - previous.time > maxGap)) { if (path.length) paths.push(path); path = []; discontinuities++; }+ else if (previous) { measuredDistance += distance(previous.point, row.point); if (!segmentWithin(plan.region, previous.point, row.point)) outsideSegments++; }+ path.push(row.point);+ if (row.capture === null) unknownCaptureSamples++;+ if (row.capture === true) {+ captureEvents++;+ if (!(row.altitude > 0) || row.heading === null) { unmodeledCaptures++; continue; }+ const camera = cameraGeometry(p, row.altitude);+ modeled.push(footprint(row.point, 90 - row.heading, camera.width, camera.along));+ }+ }+ if (path.length) paths.push(path);+ const covered = modeled.length ? intersection(plan.target, union(modeled)) : [];+ const batteries = records.filter(r => r.battery !== null);+ return { paths, measuredDistance, elapsedSeconds: records.at(-1).time - records[0].time, outsideSamples, outsideSegments, discontinuities, missingCoordinates: log.missingCoordinates ?? 0, captureEvents, unmodeledCaptures, unknownCaptureSamples, modeledCaptures: modeled.length, covered, coverage: modeled.length ? Math.min(1, regionArea(covered) / plan.area) : null, startBattery: batteries[0]?.battery ?? null, endBattery: batteries.at(-1)?.battery ?? null, maxGap, comparisonSortie: log.comparisonSortie ?? null, deviationP95: deviations[Math.min(deviations.length-1,Math.floor(deviations.length*.95))], deviationMax: deviations.at(-1),+ interpretation: 'Recorded event footprints are estimates from logged position, altitude and heading plus the current camera and level-ground/nadir assumptions. They do not establish that images exist, are sharp or form a usable map. Track gaps are not connected.' };+}diff --git a/store/agents/drone-pilot/template/studio/project.mjs b/store/agents/drone-pilot/template/studio/project.mjsnew file mode 100644index 000000000..557d08bfa--- /dev/null+++ b/store/agents/drone-pilot/template/studio/project.mjs@@ -0,0 +1,120 @@+import { validateRing, lonLat, toLonLat, flightRegion, difference, union, regionArea, pointIn, transects, navigatorFor, distance, length, intersection, orient } from './geo.mjs';++export const ASSUMPTIONS = 'Level ground at takeoff elevation; a nadir camera aligned with each survey run. Geometry and nominal time only: terrain, obstacles, airspace, wind, positioning error and aircraft dynamics are not verified.';+export const clone = value => JSON.parse(JSON.stringify(value));+const text = (value, label, max = 120) => { if (typeof value !== 'string' || !value.trim() || value.length > max) throw new Error(label + ' must be a nonempty text of at most ' + max + ' characters.'); return value; };+const number = (value, label, min, max) => { if (!Number.isFinite(value) || value < min || value > max) throw new Error(`${label} must be between ${min} and ${max}.`); return value; };+function coordinate(point, label) { if (!Array.isArray(point) || point.length !== 2 || !point.every(Number.isFinite) || Math.hypot(...point) > 5000) throw new Error(label + ' needs an east/north coordinate within 5 km.'); return [...point]; }+export function validateProject(input) {+ if (!input || new TextEncoder().encode(JSON.stringify(input)).length > 8000000 || input.schema !== 'vector/2') throw new Error('Open a Vector 2 project smaller than 8 MB.');+ const p = clone(input); text(p.id, 'Project ID'); text(p.title, 'Title'); text(p.brief, 'Brief', 4000); p.origin = lonLat(p.origin); p.home = coordinate(p.home, 'Takeoff');+ if (!Array.isArray(p.areas) || !p.areas.length || p.areas.length > 32) throw new Error('Use 1–32 named boundaries and exclusions.');+ const ids = new Set(); let corners = 0;+ for (const area of p.areas) {+ text(area.id, 'Area ID'); if (ids.has(area.id)) throw new Error('Area IDs must be unique.'); ids.add(area.id); text(area.name, 'Area name');+ if (!['boundary', 'exclusion'].includes(area.kind) || typeof area.locked !== 'boolean') throw new Error('Each area needs a boundary/exclusion kind and a lock state.');+ area.ring = validateRing(area.ring, area.name); corners += area.ring.length;+ }+ if (corners > 200 || !p.areas.some(a => a.kind === 'boundary')) throw new Error('Use at least one boundary and at most 200 total vertices.');+ const longitudes=[p.home,...p.areas.flatMap(a=>a.ring)].map(point=>toLonLat(p.origin,point)[0]);+ if(Math.max(...longitudes)-Math.min(...longitudes)>180)throw new Error('Split a site crossing the 180° meridian before planning; this exporter does not cut antimeridian polygons.');+ const c = p.camera, s = p.settings;+ if (!c || !s) throw new Error('Camera and planning settings are required.'); text(c.name, 'Camera name');+ for (const field of ['sensorWidth', 'sensorHeight', 'focalLength']) number(c[field], 'Camera ' + field + ' (mm)', 1, 100);+ for (const field of ['imageWidth', 'imageHeight']) if (!Number.isInteger(number(c[field], field + ' (pixels)', 100, 30000))) throw new Error('Image dimensions must be whole pixels.');+ number(c.minInterval, 'Minimum capture interval (s)', .05, 60);+ for (const [field, min, max] of [['height', 5, 500], ['speed', .2, 30], ['angle', 0, 179.9], ['frontOverlap', 0, .95], ['sideOverlap', 0, .95], ['margin', 0, 100], ['usableMinutes', 1, 120], ['reservePercent', 0, 80], ['climbSpeed', .2, 10], ['descentSpeed', .2, 10], ['turnSeconds', 0, 60]]) number(s[field], field, min, max);+ if (p.log != null) {+ text(p.log.name, 'Flight file name', 240); text(p.log.sha256, 'Flight source hash', 64);+ if (!/^[a-f0-9]{64}$/.test(p.log.sha256) || !p.log.mapping || !Array.isArray(p.log.records) || p.log.records.length < 2 || p.log.records.length > 12000) throw new Error('Flight records or provenance are invalid.');+ if (typeof p.log.raw !== 'string' || new TextEncoder().encode(p.log.raw).length > 3000000) throw new Error('Keep the original UTF-8 CSV, up to 3 MB, with its recorded flight.');+ if (p.log.maxGap != null) number(p.log.maxGap, 'Track continuity limit (seconds)', .1, 120);+ if (p.log.comparisonSortie != null && (!Number.isInteger(p.log.comparisonSortie) || p.log.comparisonSortie < 1 || p.log.comparisonSortie > 80)) throw new Error('Choose a valid comparison sortie.');+ let previous = -1;+ for (const row of p.log.records) {+ number(row.time, 'Flight elapsed seconds', 0, 172800); if (row.time <= previous) throw new Error('Flight timestamps must be strictly increasing.'); previous = row.time;+ row.point = coordinate(row.point, 'Flight record');+ if (row.altitude !== null) number(row.altitude, 'Flight altitude (m)', -1000, 10000);+ if (row.battery !== null) number(row.battery, 'Recorded battery (%)', 0, 100);+ if (row.heading !== null) number(row.heading, 'Recorded heading (degrees)', 0, 360);+ if (![null, true, false].includes(row.capture)) throw new Error('Capture events must be true, false or unknown.');+ if (typeof row.breakBefore !== 'boolean' || !Number.isInteger(row.sourceRow) || row.sourceRow < 2) throw new Error('Keep flight row provenance and track breaks.');+ }+ if (p.log.records.filter(r => r.capture).length > 3000) throw new Error('Use at most 3,000 recorded capture events.');+ }+ return p;+}+export function footprint(point, heading, width, height) {+ const a = heading * Math.PI / 180, u = [Math.cos(a), Math.sin(a)], v = [-u[1], u[0]];+ return orient([[-1,-1],[1,-1],[1,1],[-1,1]].map(([x,y]) => point.map((n,i) => n + u[i] * x * height / 2 + v[i] * y * width / 2)));+}+export function cameraGeometry(p, height = p.settings.height) {+ const c = p.camera, width = height * c.sensorWidth / c.focalLength, along = height * c.sensorHeight / c.focalLength;+ return { width, along, gsdX: width / c.imageWidth * 100, gsdY: along / c.imageHeight * 100, lineSpacing: width * (1 - p.settings.sideOverlap), photoSpacing: along * (1 - p.settings.frontOverlap) };+}+export function planProject(input, { coverage = true } = {}) {+ const p = validateProject(input), s = p.settings, camera = cameraGeometry(p);+ const boundaries = p.areas.filter(a => a.kind === 'boundary').map(a => a.ring), exclusions = p.areas.filter(a => a.kind === 'exclusion').map(a => a.ring);+ const target = difference(union(boundaries), union(exclusions)), region = flightRegion(boundaries, exclusions, s.margin), area = regionArea(target);+ if (area < 1 || !region.length) throw new Error('The boundary and margin leave no survey area.');+ if (!pointIn(region, p.home)) throw new Error('Move takeoff inside the inset boundary and outside expanded exclusions.');+ const navigate = navigatorFor(region), spans = transects(region, camera.lineSpacing, s.angle), runs = [], photos = [];+ if (!spans.length) throw new Error('No survey runs fit inside the flight area.');+ for (const span of spans) {+ const count = Math.max(1, Math.ceil(span.length / camera.photoSpacing)), spacing = span.length / count;+ if (photos.length + count > 3000) throw new Error('This plan exceeds 3,000 photos. Split the site or revise capture requirements.');+ if (count > 1 && spacing / s.speed + 1e-8 < p.camera.minInterval) throw new Error(`The camera cannot capture this fast. Reduce speed to at most ${(spacing / p.camera.minInterval).toFixed(2)} m/s, raise height, or change capture requirements.`);+ const heading = Math.atan2(span.b[1] - span.a[1], span.b[0] - span.a[0]) * 180 / Math.PI;+ const shots = Array.from({ length: count }, (_, i) => ({ id: photos.length + i + 1, point: span.a.map((n,j) => n + (span.b[j] - n) * (i + .5) / count), heading, run: runs.length + 1 }));+ photos.push(...shots); runs.push({ id: runs.length + 1, row: span.row, photos: shots, spacing, heading });+ }+ const budget = s.usableMinutes * 60 * (1 - s.reservePercent / 100), overhead = s.height / s.climbSpeed + s.height / s.descentSpeed;+ if (overhead >= budget) throw new Error('Climb and descent consume the whole time budget. Revise the plan.');+ const sorties = []; let sortie = null;+ const homeRoutes = new Map();+ function homeRoute(shot) { if (!homeRoutes.has(shot.id)) { const route = navigate(shot.point, p.home); if (!route) throw new Error(`Photo ${shot.id} is in an area disconnected from takeoff. Split the site or move takeoff.`); homeRoutes.set(shot.id, route); } return homeRoutes.get(shot.id); }+ function open() { sortie = { id: sorties.length + 1, path: [[...p.home]], legs: [], photos: [], seconds: s.height / s.climbSpeed, distance: 0, lastCapture: -Infinity }; }+ function addLeg(path, kind, seconds = length(path) / s.speed) {+ sortie.legs.push({ kind, points: path.map(p => [...p]), start: sortie.seconds, seconds }); sortie.path.push(...path.slice(1)); sortie.distance += length(path); sortie.seconds += seconds;+ }+ function finish() {+ if (!sortie?.photos.length) return;+ addLeg(homeRoute(sortie.photos.at(-1)), 'return'); sortie.seconds += s.height / s.descentSpeed;+ sortie.remainingSeconds = budget - sortie.seconds; delete sortie.lastCapture; sorties.push(sortie); sortie = null;+ if (sorties.length > 80) throw new Error('This plan needs more than 80 sorties. Split the job or revise the time budget.');+ }+ open();+ for (const run of runs) {+ let at = 0;+ while (at < run.photos.length) {+ const first = run.photos[at], from = sortie.path.at(-1), transit = navigate(from, first.point);+ if (!transit) throw new Error(`Survey run ${run.id} is disconnected from takeoff. Split the site.`);+ const arrive = sortie.seconds + length(transit) / s.speed;+ const settle = Math.max(s.turnSeconds, p.camera.minInterval - (arrive - sortie.lastCapture), 0);+ let end = at - 1;+ for (let i = at; i < run.photos.length; i++) {+ const shot = run.photos[i], duration = arrive + settle + distance(first.point, shot.point) / s.speed + length(homeRoute(shot)) / s.speed + s.height / s.descentSpeed;+ if (duration <= budget + 1e-7) end = i; else break;+ }+ if (end < at) {+ if (!sortie.photos.length) throw new Error(`Photo ${first.id} cannot fit a return trip within the time budget. Move takeoff, increase usable time, or split the site.`);+ finish(); open(); continue;+ }+ addLeg(transit, 'transit'); addLeg([first.point], 'settle', settle);+ const selected = run.photos.slice(at, end + 1), started = sortie.seconds;+ for (const photo of selected) { photo.sortie = sortie.id; photo.time = started + distance(first.point, photo.point) / s.speed; sortie.photos.push(photo); }+ addLeg(selected.map(photo => photo.point), 'survey'); sortie.lastCapture = sortie.photos.at(-1).time;+ at = end + 1; if (at < run.photos.length) { finish(); open(); }+ }+ }+ finish();+ const footprints = coverage ? union(photos.map(photo => footprint(photo.point, photo.heading, camera.width, camera.along))) : [];+ const covered = coverage ? intersection(target, footprints) : [], gaps = coverage ? difference(target, footprints) : [];+ return { project: p, assumptions: ASSUMPTIONS, target, region, area, camera, runs, photos, sorties, covered, gaps, coverage: coverage ? Math.min(1, regionArea(covered) / area) : null, totalDistance: sorties.reduce((n,s) => n + s.distance,0), totalSeconds: sorties.reduce((n,s) => n + s.seconds,0), budgetSeconds: budget };+}+export function history(initial) {+ let states = [clone(initial)], at = 0;+ return { get value() { return clone(states[at]); }, get canUndo() { return at > 0; }, get canRedo() { return at < states.length - 1; },+ push(next) { const checked = validateProject(next); states = [...states.slice(0, at + 1), checked].slice(-40); at = states.length - 1; return this.value; },+ undo() { if (at > 0) at--; return this.value; }, redo() { if (at < states.length - 1) at++; return this.value; } };+}diff --git a/store/agents/drone-pilot/template/studio/shell.html b/store/agents/drone-pilot/template/studio/shell.htmlnew file mode 100644index 000000000..268151f5a--- /dev/null+++ b/store/agents/drone-pilot/template/studio/shell.html@@ -0,0 +1,16 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vector — Field Studio</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head><body>+<header><div class="identity"><span class="mark"><!-- VECTOR_ICON --></span><div>VECTOR<small>FIELD STUDIO</small></div></div><button id="project-details" class="project-heading"><strong id="project-title"></strong><span id="save-state">Opening project</span></button><nav><button id="open-project">Open project</button><button id="save-project">Save file</button><button id="save-source" hidden>Save to workspace</button><button id="deliver" class="primary">Export field kit ↗</button></nav></header>+<div id="source-notice" class="notice" hidden><span></span><button id="draft-keep">Download my draft</button><button id="source-load">Use source version</button></div>+<section id="metrics" class="metrics"></section><div id="plan-error" class="plan-error" role="alert" hidden></div>+<main><aside class="controls"><div class="tabs"><button id="plan-tab" class="active">Survey plan</button><button id="evidence-tab">Flight evidence</button></div><div id="settings-panel"></div><div id="evidence-panel" hidden></div></aside>+<section class="stage"><div class="map-toolbar"><div class="segmented"><button data-tool="select" class="active">↖ Edit</button><button data-tool="boundary">+ Boundary</button><button data-tool="exclusion">⊘ Exclusion</button><button data-tool="home">⌖ Takeoff</button></div><button id="import-geo">Import GeoJSON</button></div><div class="map-wrap"><svg id="map" aria-label="Editable georeferenced site map" role="img" tabindex="0"></svg><div class="map-heading"><span class="eyebrow">SITE OVERVIEW</span><h1 id="map-title"></h1><p id="map-subtitle"></p></div><div class="north">N<span>↑</span></div><div class="map-legend"><span><i class="boundary-key"></i>Site</span><span><i class="route-key"></i>Planned route</span><span><i class="exclude-key"></i>Exclusion</span><span id="log-legend" hidden><i class="log-key"></i>Recorded track</span></div><div class="map-actions"><button id="undo" title="Undo">↶</button><button id="redo" title="Redo">↷</button><button id="zoom-in" title="Zoom in">+</button><button id="zoom-out" title="Zoom out">−</button><button id="frame-site">Fit site</button></div><div id="draw-help" hidden><span>Click to add corners. Double-click or press Enter to finish.</span><button id="finish-draw">Finish polygon</button><button id="cancel-draw">Cancel</button></div><div class="map-caption"><span id="map-origin"></span><span id="scale"></span></div></div><div class="assumptions"><span>MODEL</span><p>Level ground · nadir camera · nominal timing. <button id="model-details">View assumptions</button></p></div></section>+<aside class="details"><section><div class="section-title">SITE LAYERS <span id="area-count"></span></div><div id="area-list"></div><div id="area-editor"></div></section><section><div class="section-title">SORTIES <button id="show-all">Show all</button></div><div id="sortie-list"></div></section><section class="coverage"><div class="section-title">IMAGE FOOTPRINTS</div><label class="check"><input id="show-coverage" type="checkbox"> Show nominal coverage</label><label class="check"><input id="show-gaps" type="checkbox" checked> Show coverage gaps</label><p>Coverage is a geometric estimate. It does not establish image quality or mapping accuracy.</p></section></aside></main>+<footer><span id="status" role="status">Ready to plan your site</span><span>Local files · works offline</span></footer>+<dialog id="project-dialog"><h2>Project & map origin</h2><label>Project title<input id="title-input" maxlength="120"></label><label>Brief<textarea id="brief-input" rows="4" maxlength="4000"></textarea></label><div class="two"><label>Origin longitude<input id="origin-lon" type="number" step="any"></label><label>Origin latitude<input id="origin-lat" type="number" step="any"></label></div><p>Coordinates are WGS 84. Changing the origin relocates all local geometry; vertices remain in east/north meters. A recorded log must be removed before relocation.</p><div class="dialog-actions"><button data-close>Cancel</button><button id="apply-project" class="primary">Apply</button></div></dialog>+<dialog id="open-dialog"><h2>Open a project</h2><p>Open an editable .vector.json file. The existing source changes only when you save to the workspace.</p><button id="choose-project">Choose file…</button><section id="native-open"><label>Or paste a project path in your home folder<input id="project-path" placeholder="~/Downloads/my-site.vector.json"></label><button id="open-path">Open this project</button><div id="recent-projects"></div></section><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="geo-dialog"><h2>Bring your site</h2><p>Import WGS 84 polygon GeoJSON. Interior rings become exclusions; a boundary/exclusion kind property is retained. You can edit every vertex after import.</p><label>Import mode<select id="geo-mode"><option value="replace">Replace site and use file coordinates</option><option value="add">Add to this site at its current origin</option></select></label><label>Default polygon layer<select id="geo-kind"><option value="boundary">Site boundaries</option><option value="exclusion">Exclusions</option></select></label><p>Replace starts a new site draft and removes any recorded log. Undo restores the prior project.</p><button id="choose-geo" class="primary">Choose GeoJSON…</button><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="log-dialog" class="wide-dialog"><h2>Read a recorded flight</h2><p id="log-name"></p><div id="log-mapping" class="two"></div><p>Heading is degrees clockwise from north. Capture events must be 1/0, true/false or yes/no; blank means unknown. Battery is a percentage. No photograph is inferred from a track sample.</p><div class="dialog-actions"><button data-close>Cancel</button><button id="apply-log" class="primary">Import recorded flight</button></div></dialog>+<dialog id="export-dialog"><h2>Take the field kit with you</h2><p id="export-summary"></p><div class="export-options"><button id="export-geo"><strong>GIS layers · GeoJSON</strong><span>Site, exclusions, routes, captures and coverage</span></button><button id="export-kml"><strong>Map overlay · KML</strong><span>Ground-clamped route and site geometry</span></button><button id="export-report"><strong>Survey report · HTML / PDF</strong><span>Calculations, assumptions and recorded evidence</span></button><button id="export-kit" class="primary"><strong>Complete editable kit · ZIP</strong><span>Planner, project, GIS, CSV, report and original log</span></button></div><p>Files support planning, review and GIS workflows. They are not an aircraft mission. No vehicle connection or upload is included.</p><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<dialog id="model-dialog"><h2>What the model measures</h2><p>Vector computes local geometry within 5 km of a WGS 84 origin. Boundary insets and exclusion buffers constrain connected horizontal routes. Camera geometry determines ideal footprints and regular-run overlap.</p><p>Height is above takeoff. The ground is assumed level with takeoff and the camera points straight down, aligned with each run. No terrain model, obstacle data, airspace check, wind, navigation error or aircraft dynamics are included.</p><p>Time includes distance at the configured speed, climb and descent rates, a fixed allowance per capture run and a connected return to takeoff. The usable duration and reserve are inputs, not a validated battery prediction.</p><p>Recorded evidence uses only supplied samples. Gaps remain gaps. Footprints require actual event flags, height and heading; they still do not prove that an image exists or is suitable for mapping.</p><div class="dialog-actions"><button data-close>Close</button></div></dialog>+<input id="project-file" type="file" accept=".json,.vector.json" hidden><input id="geo-file" type="file" accept=".json,.geojson" hidden><input id="log-file" type="file" accept=".csv,text/csv" hidden>+<script id="vector-data" type="application/json">VECTOR_DATA</script><script>/* VECTOR_APP */</script></body></html>diff --git a/store/agents/drone-pilot/template/studio/style.css b/store/agents/drone-pilot/template/studio/style.cssnew file mode 100644index 000000000..523041f42--- /dev/null+++ b/store/agents/drone-pilot/template/studio/style.css@@ -0,0 +1 @@+:root{color-scheme:light;--paper:#f9faf6;--ink:#273c31;--muted:#758074;--line:#dde2d7;--orange:#c65a32;--pale:#eef1e8;--teal:#267d81;font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink)}button,input,select,textarea{font:inherit}button{cursor:pointer;background:transparent;border:1px solid var(--line);border-radius:7px;padding:8px 12px;color:inherit;white-space:nowrap}button:hover{background:#edf0e7;border-color:#c4cdbd}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--teal);outline-offset:2px}button:disabled{opacity:.42;cursor:default}.primary{background:var(--ink);border-color:var(--ink);color:white}.primary:hover{background:#395844;color:white}header{display:flex;align-items:center;gap:30px;min-height:83px;padding:17px 25px;border-bottom:1px solid var(--line)}.identity{display:flex;gap:10px;align-items:center;min-width:176px;font-size:14px;font-weight:750;letter-spacing:2px}.identity small{display:block;font-size:8px;letter-spacing:2.2px;color:var(--muted);font-weight:550}.mark svg{width:38px;height:38px}.project-heading{border:0;text-align:left;padding:0;white-space:normal}.project-heading strong{display:block;font-size:17px;font-weight:650}.project-heading span{font-size:11px;color:var(--muted)}header nav{margin-left:auto;display:flex;gap:8px}.metrics{display:flex;align-items:center;min-height:92px;border-bottom:1px solid var(--line);padding:16px 25px;gap:0}.metric{flex:1;border-right:1px solid var(--line);padding:0 25px}.metric:first-child{padding-left:0}.metric:last-child{border:0}.metric small{font-size:9px;letter-spacing:1.2px;text-transform:uppercase;color:var(--muted);display:block}.metric b{font-size:25px;letter-spacing:-.6px;font-weight:550}.metric em{font-style:normal;font-size:11px;font-weight:400;margin-left:5px;color:var(--muted)}main{display:grid;grid-template-columns:280px minmax(380px,1fr) 258px;min-height:650px;height:calc(100vh - 211px)}aside{overflow:auto;scrollbar-width:thin}.controls{border-right:1px solid var(--line);padding:20px}.details{border-left:1px solid var(--line);padding:20px 17px}.tabs{display:flex;gap:14px;border-bottom:1px solid var(--line);margin-bottom:21px}.tabs button{border:0;border-radius:0;padding:0 0 12px;font-weight:600;font-size:12px}.tabs .active{border-bottom:2px solid var(--orange);color:var(--orange)}.section-title,.eyebrow{font-size:9px;letter-spacing:1.3px;color:var(--muted);font-weight:650}.section-title{display:flex;align-items:center;justify-content:space-between;margin:0 0 13px}.section-title button{font-size:10px;padding:3px 6px}.section-title span{letter-spacing:0}.controls section+section,.details section+section{border-top:1px solid var(--line);margin-top:22px;padding-top:20px}label{display:block;font-size:11px;color:#5d6b5e;margin:11px 0}input:not([type=checkbox]),select,textarea{display:block;width:100%;border:1px solid var(--line);border-radius:5px;background:#fffefa;color:var(--ink);padding:8px;margin-top:5px;min-width:0}input[type=number]{font-variant-numeric:tabular-nums}textarea{resize:vertical}.two{display:grid;grid-template-columns:1fr 1fr;gap:0 12px}.two label{min-width:0}.controls p,.details p{font-size:11px;line-height:1.65;color:var(--muted)}details summary{cursor:pointer;font-size:11px;color:var(--muted);margin:15px 0}.hint{background:var(--pale);padding:12px;border-radius:6px;font-size:11px}.stage{min-width:0;display:flex;flex-direction:column;background:#f0f2e9}.map-toolbar{display:flex;align-items:center;justify-content:space-between;padding:12px 15px;gap:8px;background:var(--paper);border-bottom:1px solid var(--line)}.map-toolbar button{font-size:10px;padding:7px 9px}.segmented{display:flex;border:1px solid var(--line);border-radius:6px;padding:2px;gap:1px}.segmented button{border:0}.segmented .active{background:var(--pale);color:var(--ink)}.map-wrap{position:relative;flex:1;min-height:470px;overflow:hidden}#map{width:100%;height:100%;position:absolute;inset:0;touch-action:none}#map .area{cursor:pointer;vector-effect:non-scaling-stroke}#map .handle{cursor:move;vector-effect:non-scaling-stroke}#map [data-home]{cursor:move}.map-heading{position:absolute;top:23px;left:25px;pointer-events:none;max-width:70%}.map-heading h1{font-family:Georgia,"Times New Roman",serif;font-size:29px;font-weight:400;letter-spacing:-.8px;margin:5px 0 3px}.map-heading p{font-size:10px;color:var(--muted);margin:0}.north{position:absolute;right:22px;top:23px;display:flex;flex-direction:column;text-align:center;font-size:9px;color:#7c8879}.north span{font-size:31px;line-height:1}.map-legend{position:absolute;bottom:61px;left:20px;display:flex;gap:12px;flex-wrap:wrap;font-size:9px;color:var(--muted);pointer-events:none}.map-legend span{display:flex;align-items:center;gap:5px}.map-legend i{width:8px;height:8px;display:inline-block;border-radius:2px}.boundary-key{background:#86a77d}.route-key{background:var(--orange)}.exclude-key{background:#cc8b7c}.log-key{background:var(--teal)}.map-actions{position:absolute;bottom:20px;right:17px;display:flex;background:#fafbf5ee;border:1px solid var(--line);border-radius:6px}.map-actions button{border:0;font-size:11px;padding:7px 10px}.map-caption{position:absolute;bottom:23px;left:22px;font-size:9px;color:#7b8575;display:flex;gap:12px;flex-wrap:wrap;max-width:48%}.assumptions{display:flex;align-items:center;gap:12px;padding:9px 17px;background:var(--paper);border-top:1px solid var(--line);font-size:10px;color:var(--muted)}.assumptions span{font-size:8px;letter-spacing:1px;background:var(--pale);padding:3px 5px;border-radius:3px}.assumptions p{margin:0}.assumptions button{font-size:10px;border:0;padding:0;text-decoration:underline;color:#597256}.area-row{width:100%;display:flex;align-items:center;text-align:left;gap:8px;padding:10px 8px;border:1px solid transparent;font-size:11px;margin:4px 0;white-space:normal}.area-row.active{background:#edf1e7;border-color:#d7e0ce}.area-row i{width:8px;height:8px;border-radius:2px;flex-shrink:0}.area-row span{flex:1}.area-row small{font-size:10px;color:var(--muted)}#area-editor{padding:3px 8px}#area-editor textarea{font:10px/1.7 monospace}.row-actions{display:flex;gap:6px}.row-actions button{font-size:10px;padding:5px 8px}.sortie{display:block;width:100%;text-align:left;padding:12px 10px;margin-bottom:7px;border-radius:6px}.sortie .row{display:flex;justify-content:space-between;gap:8px;font-size:11px}.sortie .row b{font-weight:650}.sortie small{display:block;font-size:9px;color:var(--muted);margin-top:4px}.sortie .bar{height:3px;background:#e9ede2;margin-top:9px;border-radius:3px}.sortie .bar i{display:block;height:100%;background:#b3bf99;border-radius:3px}.sortie.active{background:#edf1e7;border-color:#b9cba5}.check{display:flex;gap:7px;align-items:center;font-size:11px}.check input{accent-color:var(--ink)}.evidence-metrics{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:17px 0}.evidence-metrics div{background:var(--pale);padding:10px;border-radius:5px;font-size:9px;color:var(--muted)}.evidence-metrics b{display:block;color:var(--ink);font-size:21px;font-weight:550}.notice,.plan-error{padding:12px 25px;background:#f7e8cf;color:#765222;display:flex;gap:12px;align-items:center}.notice span{flex:1}.plan-error{border-bottom:1px solid #e5c79f;font-size:12px}.notice button{font-size:11px;border-color:#d9bd8d}#draw-help{position:absolute;top:115px;left:20px;right:20px;background:#fffefa;padding:12px;border:1px solid #d7dfca;box-shadow:0 5px 20px #24302012;border-radius:7px;font-size:11px;display:flex;align-items:center;gap:7px}#draw-help span{flex:1}#draw-help button{font-size:10px;padding:6px}footer{height:36px;border-top:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;padding:0 22px;font-size:10px;color:var(--muted)}footer #status{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:80%}dialog{background:var(--paper);color:var(--ink);border:1px solid var(--line);border-radius:13px;padding:30px;max-width:min(94vw,590px);width:590px;max-height:88vh;box-shadow:0 24px 100px #19322033}dialog::backdrop{background:#15251aaa;backdrop-filter:blur(3px)}dialog h2{font:29px Georgia,serif;margin:0 0 15px;letter-spacing:-.5px}dialog p{font-size:12px;color:var(--muted)}dialog label{font-size:12px}dialog .dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:22px}.dialog-error{background:#f5e2d7;color:#92492e;padding:12px;border-radius:5px;white-space:normal}.export-options{display:grid;gap:10px;margin:22px 0}.export-options button{text-align:left;padding:15px;white-space:normal}.export-options strong{display:block;font-size:13px}.export-options span{display:block;font-size:11px;opacity:.7;margin-top:3px}.wide-dialog{width:670px;max-width:min(94vw,670px)}#native-open{margin-top:20px}#recent-projects button{display:block;width:100%;text-align:left;margin-top:7px;white-space:normal;font-size:11px}[hidden]{display:none!important}@media(min-width:1550px){main{grid-template-columns:306px minmax(380px,1fr) 280px}.controls,.details{padding:24px}.metric b{font-size:29px}}@media(max-width:1190px){main{grid-template-columns:258px minmax(380px,1fr)}.details{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;border-left:0;border-top:1px solid var(--line)}.details section+section{margin:0;padding:0 0 0 20px;border-top:0;border-left:1px solid var(--line)}main{height:auto}.stage{min-height:650px}.controls{max-height:780px}.metric{padding:0 14px}.metric b{font-size:22px}header{gap:20px}.identity{min-width:130px}header nav button{font-size:11px}}@media(max-width:740px){header{padding:12px 14px;gap:12px;flex-wrap:wrap}.identity{min-width:auto}.identity small{display:none}.mark svg{width:29px;height:29px}.project-heading{margin-left:auto}.project-heading strong{font-size:14px}header nav{width:100%;display:grid;grid-template-columns:1fr 1fr;gap:7px}header nav button{min-width:0}.metrics{flex-wrap:wrap;padding:10px 14px;gap:12px}.metric{flex:0 0 calc(33.33% - 12px);padding:0;border:0}.metric b{font-size:22px}.metric small{font-size:8px}.metric em{font-size:9px}main{display:flex;flex-direction:column}.stage{order:0;min-height:550px}.controls{order:1;border:0;border-top:1px solid var(--line);max-height:none;padding:20px}.details{order:2;display:block;padding:20px}.details section+section{border-left:0;border-top:1px solid var(--line);padding:20px 0 0;margin-top:20px}.map-toolbar{padding:9px 7px;gap:4px}.map-toolbar button{padding:6px;font-size:9px}.map-heading h1{font-size:25px}.map-heading{left:18px}.map-caption{font-size:8px;max-width:45%;gap:3px}.map-actions button{padding:7px}.map-legend{gap:8px;font-size:8px;left:14px}.assumptions{font-size:9px}.assumptions button{font-size:9px}footer{height:auto;min-height:36px;padding:8px 14px}footer>span:last-child{display:none}footer #status{max-width:100%}#draw-help{flex-wrap:wrap;top:102px}#draw-help span{flex-basis:100%}.notice{flex-wrap:wrap;padding:12px}.notice span{flex-basis:100%}}diff --git a/store/agents/drone-pilot/template/studio/vendor/LICENSE-BOOST.txt b/store/agents/drone-pilot/template/studio/vendor/LICENSE-BOOST.txtnew file mode 100644index 000000000..36b7cd93c--- /dev/null+++ b/store/agents/drone-pilot/template/studio/vendor/LICENSE-BOOST.txt@@ -0,0 +1,23 @@+Boost Software License - Version 1.0 - August 17th, 2003++Permission is hereby granted, free of charge, to any person or organization+obtaining a copy of the software and accompanying documentation covered by+this license (the "Software") to use, reproduce, display, distribute,+execute, and transmit the Software, and to prepare derivative works of the+Software, and to permit third-parties to whom the Software is furnished to+do so, all subject to the following:++The copyright notices in the Software and this entire statement, including+the above license grant, this restriction and the following disclaimer,+must be included in all copies of the Software, in whole or in part, and+all derivative works of the Software, unless such copies or derivative+works are solely in the form of machine-executable object code generated by+a source language processor.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/store/agents/drone-pilot/template/studio/vendor/LICENSE-JSBN.txt b/store/agents/drone-pilot/template/studio/vendor/LICENSE-JSBN.txtnew file mode 100644index 000000000..24502a9cf--- /dev/null+++ b/store/agents/drone-pilot/template/studio/vendor/LICENSE-JSBN.txt@@ -0,0 +1,40 @@+Licensing+---------++This software is covered under the following copyright:++/*+ * Copyright (c) 2003-2005 Tom Wu+ * All Rights Reserved.+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files (the+ * "Software"), to deal in the Software without restriction, including+ * without limitation the rights to use, copy, modify, merge, publish,+ * distribute, sublicense, and/or sell copies of the Software, and to+ * permit persons to whom the Software is furnished to do so, subject to+ * the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY+ * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.+ *+ * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,+ * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER+ * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF+ * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT+ * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.+ *+ * In addition, the following condition applies:+ *+ * All redistributions must retain an intact copy of this copyright notice+ * and disclaimer.+ */++Address all questions regarding this license to:++ Tom Wudiff --git a/store/agents/drone-pilot/template/studio/vendor/clipper.cjs b/store/agents/drone-pilot/template/studio/vendor/clipper.cjsnew file mode 100644index 000000000..7e9453dec--- /dev/null+++ b/store/agents/drone-pilot/template/studio/vendor/clipper.cjs@@ -0,0 +1,7629 @@+/*******************************************************************************+ * *+ * Author : Angus Johnson *+ * Version : 6.4.2 *+ * Date : 27 February 2017 *+ * Website : http://www.angusj.com *+ * Copyright : Angus Johnson 2010-2017 *+ * *+ * License: *+ * Use, modification & distribution is subject to Boost Software License Ver 1. *+ * http://www.boost.org/LICENSE_1_0.txt *+ * *+ * Attributions: *+ * The code in this library is an extension of Bala Vatti's clipping algorithm: *+ * "A generic solution to polygon clipping" *+ * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *+ * http://portal.acm.org/citation.cfm?id=129906 *+ * *+ * Computer graphics and geometric modeling: implementation and algorithms *+ * By Max K. Agoston *+ * Springer; 1 edition (January 4, 2005) *+ * http://books.google.com/books?q=vatti+clipping+agoston *+ * *+ * See also: *+ * "Polygon Offsetting by Computing Winding Numbers" *+ * Paper no. DETC2005-85513 pp. 565-575 *+ * ASME 2005 International Design Engineering Technical Conferences *+ * and Computers and Information in Engineering Conference (IDETC/CIE2005) *+ * September 24-28, 2005 , Long Beach, California, USA *+ * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *+ * *+ *******************************************************************************/+/*******************************************************************************+ * *+ * Author : Timo *+ * Version : 6.4.2.2 *+ * Date : 8 September 2017 *+ * *+ * This is a translation of the C# Clipper library to Javascript. *+ * Int128 struct of C# is implemented using JSBN of Tom Wu. *+ * Because Javascript lacks support for 64-bit integers, the space *+ * is a little more restricted than in C# version. *+ * *+ * C# version has support for coordinate space: *+ * +-4611686018427387903 ( sqrt(2^127 -1)/2 ) *+ * while Javascript version has support for space: *+ * +-4503599627370495 ( sqrt(2^106 -1)/2 ) *+ * *+ * Tom Wu's JSBN proved to be the fastest big integer library: *+ * http://jsperf.com/big-integer-library-test *+ * *+ * This class can be made simpler when (if ever) 64-bit integer support comes *+ * or floating point Clipper is released. *+ * *+ *******************************************************************************/+/*******************************************************************************+ * *+ * Basic JavaScript BN library - subset useful for RSA encryption. *+ * http://www-cs-students.stanford.edu/~tjw/jsbn/ *+ * Copyright (c) 2005 Tom Wu *+ * All Rights Reserved. *+ * See "LICENSE" for details: *+ * http://www-cs-students.stanford.edu/~tjw/jsbn/LICENSE *+ * *+ *******************************************************************************/+(function ()+{+ "use strict";+ var ClipperLib = {};+ ClipperLib.version = '6.4.2.2';++ //UseLines: Enables open path clipping. Adds a very minor cost to performance.+ ClipperLib.use_lines = true;++ //ClipperLib.use_xyz: adds a Z member to IntPoint. Adds a minor cost to performance.+ ClipperLib.use_xyz = false;++ var isNode = false;+ if (typeof module !== 'undefined' && module.exports)+ {+ module.exports = ClipperLib;+ isNode = true;+ }+ else+ {+ if (typeof define === 'function' && define.amd) {+ define(ClipperLib);+ }+ if (typeof (document) !== "undefined") window.ClipperLib = ClipperLib;+ else self['ClipperLib'] = ClipperLib;+ }+ var navigator_appName;+ if (!isNode)+ {+ var nav = navigator.userAgent.toString().toLowerCase();+ navigator_appName = navigator.appName;+ }+ else+ {+ var nav = "chrome"; // Node.js uses Chrome's V8 engine+ navigator_appName = "Netscape"; // Firefox, Chrome and Safari returns "Netscape", so Node.js should also+ }+ // Browser test to speedup performance critical functions+ var browser = {};++ if (nav.indexOf("chrome") != -1 && nav.indexOf("chromium") == -1) browser.chrome = 1;+ else browser.chrome = 0;+ if (nav.indexOf("chromium") != -1) browser.chromium = 1;+ else browser.chromium = 0;+ if (nav.indexOf("safari") != -1 && nav.indexOf("chrome") == -1 && nav.indexOf("chromium") == -1) browser.safari = 1;+ else browser.safari = 0;+ if (nav.indexOf("firefox") != -1) browser.firefox = 1;+ else browser.firefox = 0;+ if (nav.indexOf("firefox/17") != -1) browser.firefox17 = 1;+ else browser.firefox17 = 0;+ if (nav.indexOf("firefox/15") != -1) browser.firefox15 = 1;+ else browser.firefox15 = 0;+ if (nav.indexOf("firefox/3") != -1) browser.firefox3 = 1;+ else browser.firefox3 = 0;+ if (nav.indexOf("opera") != -1) browser.opera = 1;+ else browser.opera = 0;+ if (nav.indexOf("msie 10") != -1) browser.msie10 = 1;+ else browser.msie10 = 0;+ if (nav.indexOf("msie 9") != -1) browser.msie9 = 1;+ else browser.msie9 = 0;+ if (nav.indexOf("msie 8") != -1) browser.msie8 = 1;+ else browser.msie8 = 0;+ if (nav.indexOf("msie 7") != -1) browser.msie7 = 1;+ else browser.msie7 = 0;+ if (nav.indexOf("msie ") != -1) browser.msie = 1;+ else browser.msie = 0;+ ClipperLib.biginteger_used = null;++ // Copyright (c) 2005 Tom Wu+ // All Rights Reserved.+ // See "LICENSE" for details.+ // Basic JavaScript BN library - subset useful for RSA encryption.+ // Bits per digit+ var dbits;+ // JavaScript engine analysis+ var canary = 0xdeadbeefcafe;+ var j_lm = ((canary & 0xffffff) == 0xefcafe);+ // (public) Constructor+ /**+ * @constructor+ */+ function BigInteger(a, b, c)+ {+ // This test variable can be removed,+ // but at least for performance tests it is useful piece of knowledge+ // This is the only ClipperLib related variable in BigInteger library+ ClipperLib.biginteger_used = 1;+ if (a != null)+ if ("number" == typeof a && "undefined" == typeof (b)) this.fromInt(a); // faster conversion+ else if ("number" == typeof a) this.fromNumber(a, b, c);+ else if (b == null && "string" != typeof a) this.fromString(a, 256);+ else this.fromString(a, b);+ }+ // return new, unset BigInteger+ function nbi()+ {+ return new BigInteger(null, undefined, undefined);+ }+ // am: Compute w_j += (x*this_i), propagate carries,+ // c is initial carry, returns final carry.+ // c < 3*dvalue, x < 2*dvalue, this_i < dvalue+ // We need to select the fastest one that works in this environment.+ // am1: use a single mult and divide to get the high bits,+ // max digit bits should be 26 because+ // max internal value = 2*dvalue^2-2*dvalue (< 2^53)+ function am1(i, x, w, j, c, n)+ {+ while (--n >= 0)+ {+ var v = x * this[i++] + w[j] + c;+ c = Math.floor(v / 0x4000000);+ w[j++] = v & 0x3ffffff;+ }+ return c;+ }+ // am2 avoids a big mult-and-extract completely.+ // Max digit bits should be <= 30 because we do bitwise ops+ // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)+ function am2(i, x, w, j, c, n)+ {+ var xl = x & 0x7fff,+ xh = x >> 15;+ while (--n >= 0)+ {+ var l = this[i] & 0x7fff;+ var h = this[i++] >> 15;+ var m = xh * l + h * xl;+ l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);+ c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);+ w[j++] = l & 0x3fffffff;+ }+ return c;+ }+ // Alternately, set max digit bits to 28 since some+ // browsers slow down when dealing with 32-bit numbers.+ function am3(i, x, w, j, c, n)+ {+ var xl = x & 0x3fff,+ xh = x >> 14;+ while (--n >= 0)+ {+ var l = this[i] & 0x3fff;+ var h = this[i++] >> 14;+ var m = xh * l + h * xl;+ l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;+ c = (l >> 28) + (m >> 14) + xh * h;+ w[j++] = l & 0xfffffff;+ }+ return c;+ }+ if (j_lm && (navigator_appName == "Microsoft Internet Explorer"))+ {+ BigInteger.prototype.am = am2;+ dbits = 30;+ }+ else if (j_lm && (navigator_appName != "Netscape"))+ {+ BigInteger.prototype.am = am1;+ dbits = 26;+ }+ else+ { // Mozilla/Netscape seems to prefer am3+ BigInteger.prototype.am = am3;+ dbits = 28;+ }+ BigInteger.prototype.DB = dbits;+ BigInteger.prototype.DM = ((1 << dbits) - 1);+ BigInteger.prototype.DV = (1 << dbits);+ var BI_FP = 52;+ BigInteger.prototype.FV = Math.pow(2, BI_FP);+ BigInteger.prototype.F1 = BI_FP - dbits;+ BigInteger.prototype.F2 = 2 * dbits - BI_FP;+ // Digit conversions+ var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";+ var BI_RC = new Array();+ var rr, vv;+ rr = "0".charCodeAt(0);+ for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;+ rr = "a".charCodeAt(0);+ for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;+ rr = "A".charCodeAt(0);+ for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;++ function int2char(n)+ {+ return BI_RM.charAt(n);+ }++ function intAt(s, i)+ {+ var c = BI_RC[s.charCodeAt(i)];+ return (c == null) ? -1 : c;+ }+ // (protected) copy this to r+ function bnpCopyTo(r)+ {+ for (var i = this.t - 1; i >= 0; --i) r[i] = this[i];+ r.t = this.t;+ r.s = this.s;+ }+ // (protected) set from integer value x, -DV <= x < DV+ function bnpFromInt(x)+ {+ this.t = 1;+ this.s = (x < 0) ? -1 : 0;+ if (x > 0) this[0] = x;+ else if (x < -1) this[0] = x + this.DV;+ else this.t = 0;+ }+ // return bigint initialized to value+ function nbv(i)+ {+ var r = nbi();+ r.fromInt(i);+ return r;+ }+ // (protected) set from string and radix+ function bnpFromString(s, b)+ {+ var k;+ if (b == 16) k = 4;+ else if (b == 8) k = 3;+ else if (b == 256) k = 8; // byte array+ else if (b == 2) k = 1;+ else if (b == 32) k = 5;+ else if (b == 4) k = 2;+ else+ {+ this.fromRadix(s, b);+ return;+ }+ this.t = 0;+ this.s = 0;+ var i = s.length,+ mi = false,+ sh = 0;+ while (--i >= 0)+ {+ var x = (k == 8) ? s[i] & 0xff : intAt(s, i);+ if (x < 0)+ {+ if (s.charAt(i) == "-") mi = true;+ continue;+ }+ mi = false;+ if (sh == 0)+ this[this.t++] = x;+ else if (sh + k > this.DB)+ {+ this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;+ this[this.t++] = (x >> (this.DB - sh));+ }+ else+ this[this.t - 1] |= x << sh;+ sh += k;+ if (sh >= this.DB) sh -= this.DB;+ }+ if (k == 8 && (s[0] & 0x80) != 0)+ {+ this.s = -1;+ if (sh > 0) this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;+ }+ this.clamp();+ if (mi) BigInteger.ZERO.subTo(this, this);+ }+ // (protected) clamp off excess high words+ function bnpClamp()+ {+ var c = this.s & this.DM;+ while (this.t > 0 && this[this.t - 1] == c) --this.t;+ }+ // (public) return string representation in given radix+ function bnToString(b)+ {+ if (this.s < 0) return "-" + this.negate().toString(b);+ var k;+ if (b == 16) k = 4;+ else if (b == 8) k = 3;+ else if (b == 2) k = 1;+ else if (b == 32) k = 5;+ else if (b == 4) k = 2;+ else return this.toRadix(b);+ var km = (1 << k) - 1,+ d, m = false,+ r = "",+ i = this.t;+ var p = this.DB - (i * this.DB) % k;+ if (i-- > 0)+ {+ if (p < this.DB && (d = this[i] >> p) > 0)+ {+ m = true;+ r = int2char(d);+ }+ while (i >= 0)+ {+ if (p < k)+ {+ d = (this[i] & ((1 << p) - 1)) << (k - p);+ d |= this[--i] >> (p += this.DB - k);+ }+ else+ {+ d = (this[i] >> (p -= k)) & km;+ if (p <= 0)+ {+ p += this.DB;+ --i;+ }+ }+ if (d > 0) m = true;+ if (m) r += int2char(d);+ }+ }+ return m ? r : "0";+ }+ // (public) -this+ function bnNegate()+ {+ var r = nbi();+ BigInteger.ZERO.subTo(this, r);+ return r;+ }+ // (public) |this|+ function bnAbs()+ {+ return (this.s < 0) ? this.negate() : this;+ }+ // (public) return + if this > a, - if this < a, 0 if equal+ function bnCompareTo(a)+ {+ var r = this.s - a.s;+ if (r != 0) return r;+ var i = this.t;+ r = i - a.t;+ if (r != 0) return (this.s < 0) ? -r : r;+ while (--i >= 0)+ if ((r = this[i] - a[i]) != 0) return r;+ return 0;+ }+ // returns bit length of the integer x+ function nbits(x)+ {+ var r = 1,+ t;+ if ((t = x >>> 16) != 0)+ {+ x = t;+ r += 16;+ }+ if ((t = x >> 8) != 0)+ {+ x = t;+ r += 8;+ }+ if ((t = x >> 4) != 0)+ {+ x = t;+ r += 4;+ }+ if ((t = x >> 2) != 0)+ {+ x = t;+ r += 2;+ }+ if ((t = x >> 1) != 0)+ {+ x = t;+ r += 1;+ }+ return r;+ }+ // (public) return the number of bits in "this"+ function bnBitLength()+ {+ if (this.t <= 0) return 0;+ return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));+ }+ // (protected) r = this << n*DB+ function bnpDLShiftTo(n, r)+ {+ var i;+ for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i];+ for (i = n - 1; i >= 0; --i) r[i] = 0;+ r.t = this.t + n;+ r.s = this.s;+ }+ // (protected) r = this >> n*DB+ function bnpDRShiftTo(n, r)+ {+ for (var i = n; i < this.t; ++i) r[i - n] = this[i];+ r.t = Math.max(this.t - n, 0);+ r.s = this.s;+ }+ // (protected) r = this << n+ function bnpLShiftTo(n, r)+ {+ var bs = n % this.DB;+ var cbs = this.DB - bs;+ var bm = (1 << cbs) - 1;+ var ds = Math.floor(n / this.DB),+ c = (this.s << bs) & this.DM,+ i;+ for (i = this.t - 1; i >= 0; --i)+ {+ r[i + ds + 1] = (this[i] >> cbs) | c;+ c = (this[i] & bm) << bs;+ }+ for (i = ds - 1; i >= 0; --i) r[i] = 0;+ r[ds] = c;+ r.t = this.t + ds + 1;+ r.s = this.s;+ r.clamp();+ }+ // (protected) r = this >> n+ function bnpRShiftTo(n, r)+ {+ r.s = this.s;+ var ds = Math.floor(n / this.DB);+ if (ds >= this.t)+ {+ r.t = 0;+ return;+ }+ var bs = n % this.DB;+ var cbs = this.DB - bs;+ var bm = (1 << bs) - 1;+ r[0] = this[ds] >> bs;+ for (var i = ds + 1; i < this.t; ++i)+ {+ r[i - ds - 1] |= (this[i] & bm) << cbs;+ r[i - ds] = this[i] >> bs;+ }+ if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;+ r.t = this.t - ds;+ r.clamp();+ }+ // (protected) r = this - a+ function bnpSubTo(a, r)+ {+ var i = 0,+ c = 0,+ m = Math.min(a.t, this.t);+ while (i < m)+ {+ c += this[i] - a[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ if (a.t < this.t)+ {+ c -= a.s;+ while (i < this.t)+ {+ c += this[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ c += this.s;+ }+ else+ {+ c += this.s;+ while (i < a.t)+ {+ c -= a[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ c -= a.s;+ }+ r.s = (c < 0) ? -1 : 0;+ if (c < -1) r[i++] = this.DV + c;+ else if (c > 0) r[i++] = c;+ r.t = i;+ r.clamp();+ }+ // (protected) r = this * a, r != this,a (HAC 14.12)+ // "this" should be the larger one if appropriate.+ function bnpMultiplyTo(a, r)+ {+ var x = this.abs(),+ y = a.abs();+ var i = x.t;+ r.t = i + y.t;+ while (--i >= 0) r[i] = 0;+ for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);+ r.s = 0;+ r.clamp();+ if (this.s != a.s) BigInteger.ZERO.subTo(r, r);+ }+ // (protected) r = this^2, r != this (HAC 14.16)+ function bnpSquareTo(r)+ {+ var x = this.abs();+ var i = r.t = 2 * x.t;+ while (--i >= 0) r[i] = 0;+ for (i = 0; i < x.t - 1; ++i)+ {+ var c = x.am(i, x[i], r, 2 * i, 0, 1);+ if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV)+ {+ r[i + x.t] -= x.DV;+ r[i + x.t + 1] = 1;+ }+ }+ if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);+ r.s = 0;+ r.clamp();+ }+ // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)+ // r != q, this != m. q or r may be null.+ function bnpDivRemTo(m, q, r)+ {+ var pm = m.abs();+ if (pm.t <= 0) return;+ var pt = this.abs();+ if (pt.t < pm.t)+ {+ if (q != null) q.fromInt(0);+ if (r != null) this.copyTo(r);+ return;+ }+ if (r == null) r = nbi();+ var y = nbi(),+ ts = this.s,+ ms = m.s;+ var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus+ if (nsh > 0)+ {+ pm.lShiftTo(nsh, y);+ pt.lShiftTo(nsh, r);+ }+ else+ {+ pm.copyTo(y);+ pt.copyTo(r);+ }+ var ys = y.t;+ var y0 = y[ys - 1];+ if (y0 == 0) return;+ var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);+ var d1 = this.FV / yt,+ d2 = (1 << this.F1) / yt,+ e = 1 << this.F2;+ var i = r.t,+ j = i - ys,+ t = (q == null) ? nbi() : q;+ y.dlShiftTo(j, t);+ if (r.compareTo(t) >= 0)+ {+ r[r.t++] = 1;+ r.subTo(t, r);+ }+ BigInteger.ONE.dlShiftTo(ys, t);+ t.subTo(y, y); // "negative" y so we can replace sub with am later+ while (y.t < ys) y[y.t++] = 0;+ while (--j >= 0)+ {+ // Estimate quotient digit+ var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);+ if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd)+ { // Try it out+ y.dlShiftTo(j, t);+ r.subTo(t, r);+ while (r[i] < --qd) r.subTo(t, r);+ }+ }+ if (q != null)+ {+ r.drShiftTo(ys, q);+ if (ts != ms) BigInteger.ZERO.subTo(q, q);+ }+ r.t = ys;+ r.clamp();+ if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder+ if (ts < 0) BigInteger.ZERO.subTo(r, r);+ }+ // (public) this mod a+ function bnMod(a)+ {+ var r = nbi();+ this.abs().divRemTo(a, null, r);+ if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);+ return r;+ }+ // Modular reduction using "classic" algorithm+ /**+ * @constructor+ */+ function Classic(m)+ {+ this.m = m;+ }++ function cConvert(x)+ {+ if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);+ else return x;+ }++ function cRevert(x)+ {+ return x;+ }++ function cReduce(x)+ {+ x.divRemTo(this.m, null, x);+ }++ function cMulTo(x, y, r)+ {+ x.multiplyTo(y, r);+ this.reduce(r);+ }++ function cSqrTo(x, r)+ {+ x.squareTo(r);+ this.reduce(r);+ }+ Classic.prototype.convert = cConvert;+ Classic.prototype.revert = cRevert;+ Classic.prototype.reduce = cReduce;+ Classic.prototype.mulTo = cMulTo;+ Classic.prototype.sqrTo = cSqrTo;+ // (protected) return "-1/this % 2^DB"; useful for Mont. reduction+ // justification:+ // xy == 1 (mod m)+ // xy = 1+km+ // xy(2-xy) = (1+km)(1-km)+ // x[y(2-xy)] = 1-k^2m^2+ // x[y(2-xy)] == 1 (mod m^2)+ // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2+ // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.+ // JS multiply "overflows" differently from C/C++, so care is needed here.+ function bnpInvDigit()+ {+ if (this.t < 1) return 0;+ var x = this[0];+ if ((x & 1) == 0) return 0;+ var y = x & 3; // y == 1/x mod 2^2+ y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4+ y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8+ y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16+ // last step - calculate inverse mod DV directly;+ // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints+ y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits+ // we really want the negative inverse, and -DV < y < DV+ return (y > 0) ? this.DV - y : -y;+ }+ // Montgomery reduction+ /**+ * @constructor+ */+ function Montgomery(m)+ {+ this.m = m;+ this.mp = m.invDigit();+ this.mpl = this.mp & 0x7fff;+ this.mph = this.mp >> 15;+ this.um = (1 << (m.DB - 15)) - 1;+ this.mt2 = 2 * m.t;+ }+ // xR mod m+ function montConvert(x)+ {+ var r = nbi();+ x.abs().dlShiftTo(this.m.t, r);+ r.divRemTo(this.m, null, r);+ if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);+ return r;+ }+ // x/R mod m+ function montRevert(x)+ {+ var r = nbi();+ x.copyTo(r);+ this.reduce(r);+ return r;+ }+ // x = x/R mod m (HAC 14.32)+ function montReduce(x)+ {+ while (x.t <= this.mt2) // pad x so am has enough room later+ x[x.t++] = 0;+ for (var i = 0; i < this.m.t; ++i)+ {+ // faster way of calculating u0 = x[i]*mp mod DV+ var j = x[i] & 0x7fff;+ var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;+ // use am to combine the multiply-shift-add into one call+ j = i + this.m.t;+ x[j] += this.m.am(0, u0, x, i, 0, this.m.t);+ // propagate carry+ while (x[j] >= x.DV)+ {+ x[j] -= x.DV;+ x[++j]++;+ }+ }+ x.clamp();+ x.drShiftTo(this.m.t, x);+ if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);+ }+ // r = "x^2/R mod m"; x != r+ function montSqrTo(x, r)+ {+ x.squareTo(r);+ this.reduce(r);+ }+ // r = "xy/R mod m"; x,y != r+ function montMulTo(x, y, r)+ {+ x.multiplyTo(y, r);+ this.reduce(r);+ }+ Montgomery.prototype.convert = montConvert;+ Montgomery.prototype.revert = montRevert;+ Montgomery.prototype.reduce = montReduce;+ Montgomery.prototype.mulTo = montMulTo;+ Montgomery.prototype.sqrTo = montSqrTo;+ // (protected) true iff this is even+ function bnpIsEven()+ {+ return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;+ }+ // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)+ function bnpExp(e, z)+ {+ if (e > 0xffffffff || e < 1) return BigInteger.ONE;+ var r = nbi(),+ r2 = nbi(),+ g = z.convert(this),+ i = nbits(e) - 1;+ g.copyTo(r);+ while (--i >= 0)+ {+ z.sqrTo(r, r2);+ if ((e & (1 << i)) > 0) z.mulTo(r2, g, r);+ else+ {+ var t = r;+ r = r2;+ r2 = t;+ }+ }+ return z.revert(r);+ }+ // (public) this^e % m, 0 <= e < 2^32+ function bnModPowInt(e, m)+ {+ var z;+ if (e < 256 || m.isEven()) z = new Classic(m);+ else z = new Montgomery(m);+ return this.exp(e, z);+ }+ // protected+ BigInteger.prototype.copyTo = bnpCopyTo;+ BigInteger.prototype.fromInt = bnpFromInt;+ BigInteger.prototype.fromString = bnpFromString;+ BigInteger.prototype.clamp = bnpClamp;+ BigInteger.prototype.dlShiftTo = bnpDLShiftTo;+ BigInteger.prototype.drShiftTo = bnpDRShiftTo;+ BigInteger.prototype.lShiftTo = bnpLShiftTo;+ BigInteger.prototype.rShiftTo = bnpRShiftTo;+ BigInteger.prototype.subTo = bnpSubTo;+ BigInteger.prototype.multiplyTo = bnpMultiplyTo;+ BigInteger.prototype.squareTo = bnpSquareTo;+ BigInteger.prototype.divRemTo = bnpDivRemTo;+ BigInteger.prototype.invDigit = bnpInvDigit;+ BigInteger.prototype.isEven = bnpIsEven;+ BigInteger.prototype.exp = bnpExp;+ // public+ BigInteger.prototype.toString = bnToString;+ BigInteger.prototype.negate = bnNegate;+ BigInteger.prototype.abs = bnAbs;+ BigInteger.prototype.compareTo = bnCompareTo;+ BigInteger.prototype.bitLength = bnBitLength;+ BigInteger.prototype.mod = bnMod;+ BigInteger.prototype.modPowInt = bnModPowInt;+ // "constants"+ BigInteger.ZERO = nbv(0);+ BigInteger.ONE = nbv(1);+ // Copyright (c) 2005-2009 Tom Wu+ // All Rights Reserved.+ // See "LICENSE" for details.+ // Extended JavaScript BN functions, required for RSA private ops.+ // Version 1.1: new BigInteger("0", 10) returns "proper" zero+ // Version 1.2: square() API, isProbablePrime fix+ // (public)+ function bnClone()+ {+ var r = nbi();+ this.copyTo(r);+ return r;+ }+ // (public) return value as integer+ function bnIntValue()+ {+ if (this.s < 0)+ {+ if (this.t == 1) return this[0] - this.DV;+ else if (this.t == 0) return -1;+ }+ else if (this.t == 1) return this[0];+ else if (this.t == 0) return 0;+ // assumes 16 < DB < 32+ return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];+ }+ // (public) return value as byte+ function bnByteValue()+ {+ return (this.t == 0) ? this.s : (this[0] << 24) >> 24;+ }+ // (public) return value as short (assumes DB>=16)+ function bnShortValue()+ {+ return (this.t == 0) ? this.s : (this[0] << 16) >> 16;+ }+ // (protected) return x s.t. r^x < DV+ function bnpChunkSize(r)+ {+ return Math.floor(Math.LN2 * this.DB / Math.log(r));+ }+ // (public) 0 if this == 0, 1 if this > 0+ function bnSigNum()+ {+ if (this.s < 0) return -1;+ else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;+ else return 1;+ }+ // (protected) convert to radix string+ function bnpToRadix(b)+ {+ if (b == null) b = 10;+ if (this.signum() == 0 || b < 2 || b > 36) return "0";+ var cs = this.chunkSize(b);+ var a = Math.pow(b, cs);+ var d = nbv(a),+ y = nbi(),+ z = nbi(),+ r = "";+ this.divRemTo(d, y, z);+ while (y.signum() > 0)+ {+ r = (a + z.intValue()).toString(b).substr(1) + r;+ y.divRemTo(d, y, z);+ }+ return z.intValue().toString(b) + r;+ }+ // (protected) convert from radix string+ function bnpFromRadix(s, b)+ {+ this.fromInt(0);+ if (b == null) b = 10;+ var cs = this.chunkSize(b);+ var d = Math.pow(b, cs),+ mi = false,+ j = 0,+ w = 0;+ for (var i = 0; i < s.length; ++i)+ {+ var x = intAt(s, i);+ if (x < 0)+ {+ if (s.charAt(i) == "-" && this.signum() == 0) mi = true;+ continue;+ }+ w = b * w + x;+ if (++j >= cs)+ {+ this.dMultiply(d);+ this.dAddOffset(w, 0);+ j = 0;+ w = 0;+ }+ }+ if (j > 0)+ {+ this.dMultiply(Math.pow(b, j));+ this.dAddOffset(w, 0);+ }+ if (mi) BigInteger.ZERO.subTo(this, this);+ }+ // (protected) alternate constructor+ function bnpFromNumber(a, b, c)+ {+ if ("number" == typeof b)+ {+ // new BigInteger(int,int,RNG)+ if (a < 2) this.fromInt(1);+ else+ {+ this.fromNumber(a, c);+ if (!this.testBit(a - 1)) // force MSB set+ this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);+ if (this.isEven()) this.dAddOffset(1, 0); // force odd+ while (!this.isProbablePrime(b))+ {+ this.dAddOffset(2, 0);+ if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);+ }+ }+ }+ else+ {+ // new BigInteger(int,RNG)+ var x = new Array(),+ t = a & 7;+ x.length = (a >> 3) + 1;+ b.nextBytes(x);+ if (t > 0) x[0] &= ((1 << t) - 1);+ else x[0] = 0;+ this.fromString(x, 256);+ }+ }+ // (public) convert to bigendian byte array+ function bnToByteArray()+ {+ var i = this.t,+ r = new Array();+ r[0] = this.s;+ var p = this.DB - (i * this.DB) % 8,+ d, k = 0;+ if (i-- > 0)+ {+ if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p)+ r[k++] = d | (this.s << (this.DB - p));+ while (i >= 0)+ {+ if (p < 8)+ {+ d = (this[i] & ((1 << p) - 1)) << (8 - p);+ d |= this[--i] >> (p += this.DB - 8);+ }+ else+ {+ d = (this[i] >> (p -= 8)) & 0xff;+ if (p <= 0)+ {+ p += this.DB;+ --i;+ }+ }+ if ((d & 0x80) != 0) d |= -256;+ if (k == 0 && (this.s & 0x80) != (d & 0x80)) ++k;+ if (k > 0 || d != this.s) r[k++] = d;+ }+ }+ return r;+ }++ function bnEquals(a)+ {+ return (this.compareTo(a) == 0);+ }++ function bnMin(a)+ {+ return (this.compareTo(a) < 0) ? this : a;+ }++ function bnMax(a)+ {+ return (this.compareTo(a) > 0) ? this : a;+ }+ // (protected) r = this op a (bitwise)+ function bnpBitwiseTo(a, op, r)+ {+ var i, f, m = Math.min(a.t, this.t);+ for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]);+ if (a.t < this.t)+ {+ f = a.s & this.DM;+ for (i = m; i < this.t; ++i) r[i] = op(this[i], f);+ r.t = this.t;+ }+ else+ {+ f = this.s & this.DM;+ for (i = m; i < a.t; ++i) r[i] = op(f, a[i]);+ r.t = a.t;+ }+ r.s = op(this.s, a.s);+ r.clamp();+ }+ // (public) this & a+ function op_and(x, y)+ {+ return x & y;+ }++ function bnAnd(a)+ {+ var r = nbi();+ this.bitwiseTo(a, op_and, r);+ return r;+ }+ // (public) this | a+ function op_or(x, y)+ {+ return x | y;+ }++ function bnOr(a)+ {+ var r = nbi();+ this.bitwiseTo(a, op_or, r);+ return r;+ }+ // (public) this ^ a+ function op_xor(x, y)+ {+ return x ^ y;+ }++ function bnXor(a)+ {+ var r = nbi();+ this.bitwiseTo(a, op_xor, r);+ return r;+ }+ // (public) this & ~a+ function op_andnot(x, y)+ {+ return x & ~y;+ }++ function bnAndNot(a)+ {+ var r = nbi();+ this.bitwiseTo(a, op_andnot, r);+ return r;+ }+ // (public) ~this+ function bnNot()+ {+ var r = nbi();+ for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i];+ r.t = this.t;+ r.s = ~this.s;+ return r;+ }+ // (public) this << n+ function bnShiftLeft(n)+ {+ var r = nbi();+ if (n < 0) this.rShiftTo(-n, r);+ else this.lShiftTo(n, r);+ return r;+ }+ // (public) this >> n+ function bnShiftRight(n)+ {+ var r = nbi();+ if (n < 0) this.lShiftTo(-n, r);+ else this.rShiftTo(n, r);+ return r;+ }+ // return index of lowest 1-bit in x, x < 2^31+ function lbit(x)+ {+ if (x == 0) return -1;+ var r = 0;+ if ((x & 0xffff) == 0)+ {+ x >>= 16;+ r += 16;+ }+ if ((x & 0xff) == 0)+ {+ x >>= 8;+ r += 8;+ }+ if ((x & 0xf) == 0)+ {+ x >>= 4;+ r += 4;+ }+ if ((x & 3) == 0)+ {+ x >>= 2;+ r += 2;+ }+ if ((x & 1) == 0) ++r;+ return r;+ }+ // (public) returns index of lowest 1-bit (or -1 if none)+ function bnGetLowestSetBit()+ {+ for (var i = 0; i < this.t; ++i)+ if (this[i] != 0) return i * this.DB + lbit(this[i]);+ if (this.s < 0) return this.t * this.DB;+ return -1;+ }+ // return number of 1 bits in x+ function cbit(x)+ {+ var r = 0;+ while (x != 0)+ {+ x &= x - 1;+ ++r;+ }+ return r;+ }+ // (public) return number of set bits+ function bnBitCount()+ {+ var r = 0,+ x = this.s & this.DM;+ for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x);+ return r;+ }+ // (public) true iff nth bit is set+ function bnTestBit(n)+ {+ var j = Math.floor(n / this.DB);+ if (j >= this.t) return (this.s != 0);+ return ((this[j] & (1 << (n % this.DB))) != 0);+ }+ // (protected) this op (1<<n)+ function bnpChangeBit(n, op)+ {+ var r = BigInteger.ONE.shiftLeft(n);+ this.bitwiseTo(r, op, r);+ return r;+ }+ // (public) this | (1<<n)+ function bnSetBit(n)+ {+ return this.changeBit(n, op_or);+ }+ // (public) this & ~(1<<n)+ function bnClearBit(n)+ {+ return this.changeBit(n, op_andnot);+ }+ // (public) this ^ (1<<n)+ function bnFlipBit(n)+ {+ return this.changeBit(n, op_xor);+ }+ // (protected) r = this + a+ function bnpAddTo(a, r)+ {+ var i = 0,+ c = 0,+ m = Math.min(a.t, this.t);+ while (i < m)+ {+ c += this[i] + a[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ if (a.t < this.t)+ {+ c += a.s;+ while (i < this.t)+ {+ c += this[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ c += this.s;+ }+ else+ {+ c += this.s;+ while (i < a.t)+ {+ c += a[i];+ r[i++] = c & this.DM;+ c >>= this.DB;+ }+ c += a.s;+ }+ r.s = (c < 0) ? -1 : 0;+ if (c > 0) r[i++] = c;+ else if (c < -1) r[i++] = this.DV + c;+ r.t = i;+ r.clamp();+ }+ // (public) this + a+ function bnAdd(a)+ {+ var r = nbi();+ this.addTo(a, r);+ return r;+ }+ // (public) this - a+ function bnSubtract(a)+ {+ var r = nbi();+ this.subTo(a, r);+ return r;+ }+ // (public) this * a+ function bnMultiply(a)+ {+ var r = nbi();+ this.multiplyTo(a, r);+ return r;+ }+ // (public) this^2+ function bnSquare()+ {+ var r = nbi();+ this.squareTo(r);+ return r;+ }+ // (public) this / a+ function bnDivide(a)+ {+ var r = nbi();+ this.divRemTo(a, r, null);+ return r;+ }+ // (public) this % a+ function bnRemainder(a)+ {+ var r = nbi();+ this.divRemTo(a, null, r);+ return r;+ }+ // (public) [this/a,this%a]+ function bnDivideAndRemainder(a)+ {+ var q = nbi(),+ r = nbi();+ this.divRemTo(a, q, r);+ return new Array(q, r);+ }+ // (protected) this *= n, this >= 0, 1 < n < DV+ function bnpDMultiply(n)+ {+ this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);+ ++this.t;+ this.clamp();+ }+ // (protected) this += n << w words, this >= 0+ function bnpDAddOffset(n, w)+ {+ if (n == 0) return;+ while (this.t <= w) this[this.t++] = 0;+ this[w] += n;+ while (this[w] >= this.DV)+ {+ this[w] -= this.DV;+ if (++w >= this.t) this[this.t++] = 0;+ ++this[w];+ }+ }+ // A "null" reducer+ /**+ * @constructor+ */+ function NullExp()+ {}++ function nNop(x)+ {+ return x;+ }++ function nMulTo(x, y, r)+ {+ x.multiplyTo(y, r);+ }++ function nSqrTo(x, r)+ {+ x.squareTo(r);+ }+ NullExp.prototype.convert = nNop;+ NullExp.prototype.revert = nNop;+ NullExp.prototype.mulTo = nMulTo;+ NullExp.prototype.sqrTo = nSqrTo;+ // (public) this^e+ function bnPow(e)+ {+ return this.exp(e, new NullExp());+ }+ // (protected) r = lower n words of "this * a", a.t <= n+ // "this" should be the larger one if appropriate.+ function bnpMultiplyLowerTo(a, n, r)+ {+ var i = Math.min(this.t + a.t, n);+ r.s = 0; // assumes a,this >= 0+ r.t = i;+ while (i > 0) r[--i] = 0;+ var j;+ for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);+ for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i);+ r.clamp();+ }+ // (protected) r = "this * a" without lower n words, n > 0+ // "this" should be the larger one if appropriate.+ function bnpMultiplyUpperTo(a, n, r)+ {+ --n;+ var i = r.t = this.t + a.t - n;+ r.s = 0; // assumes a,this >= 0+ while (--i >= 0) r[i] = 0;+ for (i = Math.max(n - this.t, 0); i < a.t; ++i)+ r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);+ r.clamp();+ r.drShiftTo(1, r);+ }+ // Barrett modular reduction+ /**+ * @constructor+ */+ function Barrett(m)+ {+ // setup Barrett+ this.r2 = nbi();+ this.q3 = nbi();+ BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);+ this.mu = this.r2.divide(m);+ this.m = m;+ }++ function barrettConvert(x)+ {+ if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m);+ else if (x.compareTo(this.m) < 0) return x;+ else+ {+ var r = nbi();+ x.copyTo(r);+ this.reduce(r);+ return r;+ }+ }++ function barrettRevert(x)+ {+ return x;+ }+ // x = x mod m (HAC 14.42)+ function barrettReduce(x)+ {+ x.drShiftTo(this.m.t - 1, this.r2);+ if (x.t > this.m.t + 1)+ {+ x.t = this.m.t + 1;+ x.clamp();+ }+ this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);+ this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);+ while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1);+ x.subTo(this.r2, x);+ while (x.compareTo(this.m) >= 0) x.subTo(this.m, x);+ }+ // r = x^2 mod m; x != r+ function barrettSqrTo(x, r)+ {+ x.squareTo(r);+ this.reduce(r);+ }+ // r = x*y mod m; x,y != r+ function barrettMulTo(x, y, r)+ {+ x.multiplyTo(y, r);+ this.reduce(r);+ }+ Barrett.prototype.convert = barrettConvert;+ Barrett.prototype.revert = barrettRevert;+ Barrett.prototype.reduce = barrettReduce;+ Barrett.prototype.mulTo = barrettMulTo;+ Barrett.prototype.sqrTo = barrettSqrTo;+ // (public) this^e % m (HAC 14.85)+ function bnModPow(e, m)+ {+ var i = e.bitLength(),+ k, r = nbv(1),+ z;+ if (i <= 0) return r;+ else if (i < 18) k = 1;+ else if (i < 48) k = 3;+ else if (i < 144) k = 4;+ else if (i < 768) k = 5;+ else k = 6;+ if (i < 8)+ z = new Classic(m);+ else if (m.isEven())+ z = new Barrett(m);+ else+ z = new Montgomery(m);+ // precomputation+ var g = new Array(),+ n = 3,+ k1 = k - 1,+ km = (1 << k) - 1;+ g[1] = z.convert(this);+ if (k > 1)+ {+ var g2 = nbi();+ z.sqrTo(g[1], g2);+ while (n <= km)+ {+ g[n] = nbi();+ z.mulTo(g2, g[n - 2], g[n]);+ n += 2;+ }+ }+ var j = e.t - 1,+ w, is1 = true,+ r2 = nbi(),+ t;+ i = nbits(e[j]) - 1;+ while (j >= 0)+ {+ if (i >= k1) w = (e[j] >> (i - k1)) & km;+ else+ {+ w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);+ if (j > 0) w |= e[j - 1] >> (this.DB + i - k1);+ }+ n = k;+ while ((w & 1) == 0)+ {+ w >>= 1;+ --n;+ }+ if ((i -= n) < 0)+ {+ i += this.DB;+ --j;+ }+ if (is1)+ { // ret == 1, don't bother squaring or multiplying it+ g[w].copyTo(r);+ is1 = false;+ }+ else+ {+ while (n > 1)+ {+ z.sqrTo(r, r2);+ z.sqrTo(r2, r);+ n -= 2;+ }+ if (n > 0) z.sqrTo(r, r2);+ else+ {+ t = r;+ r = r2;+ r2 = t;+ }+ z.mulTo(r2, g[w], r);+ }+ while (j >= 0 && (e[j] & (1 << i)) == 0)+ {+ z.sqrTo(r, r2);+ t = r;+ r = r2;+ r2 = t;+ if (--i < 0)+ {+ i = this.DB - 1;+ --j;+ }+ }+ }+ return z.revert(r);+ }+ // (public) gcd(this,a) (HAC 14.54)+ function bnGCD(a)+ {+ var x = (this.s < 0) ? this.negate() : this.clone();+ var y = (a.s < 0) ? a.negate() : a.clone();+ if (x.compareTo(y) < 0)+ {+ var t = x;+ x = y;+ y = t;+ }+ var i = x.getLowestSetBit(),+ g = y.getLowestSetBit();+ if (g < 0) return x;+ if (i < g) g = i;+ if (g > 0)+ {+ x.rShiftTo(g, x);+ y.rShiftTo(g, y);+ }+ while (x.signum() > 0)+ {+ if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x);+ if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y);+ if (x.compareTo(y) >= 0)+ {+ x.subTo(y, x);+ x.rShiftTo(1, x);+ }+ else+ {+ y.subTo(x, y);+ y.rShiftTo(1, y);+ }+ }+ if (g > 0) y.lShiftTo(g, y);+ return y;+ }+ // (protected) this % n, n < 2^26+ function bnpModInt(n)+ {+ if (n <= 0) return 0;+ var d = this.DV % n,+ r = (this.s < 0) ? n - 1 : 0;+ if (this.t > 0)+ if (d == 0) r = this[0] % n;+ else+ for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n;+ return r;+ }+ // (public) 1/this % m (HAC 14.61)+ function bnModInverse(m)+ {+ var ac = m.isEven();+ if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;+ var u = m.clone(),+ v = this.clone();+ var a = nbv(1),+ b = nbv(0),+ c = nbv(0),+ d = nbv(1);+ while (u.signum() != 0)+ {+ while (u.isEven())+ {+ u.rShiftTo(1, u);+ if (ac)+ {+ if (!a.isEven() || !b.isEven())+ {+ a.addTo(this, a);+ b.subTo(m, b);+ }+ a.rShiftTo(1, a);+ }+ else if (!b.isEven()) b.subTo(m, b);+ b.rShiftTo(1, b);+ }+ while (v.isEven())+ {+ v.rShiftTo(1, v);+ if (ac)+ {+ if (!c.isEven() || !d.isEven())+ {+ c.addTo(this, c);+ d.subTo(m, d);+ }+ c.rShiftTo(1, c);+ }+ else if (!d.isEven()) d.subTo(m, d);+ d.rShiftTo(1, d);+ }+ if (u.compareTo(v) >= 0)+ {+ u.subTo(v, u);+ if (ac) a.subTo(c, a);+ b.subTo(d, b);+ }+ else+ {+ v.subTo(u, v);+ if (ac) c.subTo(a, c);+ d.subTo(b, d);+ }+ }+ if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;+ if (d.compareTo(m) >= 0) return d.subtract(m);+ if (d.signum() < 0) d.addTo(m, d);+ else return d;+ if (d.signum() < 0) return d.add(m);+ else return d;+ }+ var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];+ var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];+ // (public) test primality with certainty >= 1-.5^t+ function bnIsProbablePrime(t)+ {+ var i, x = this.abs();+ if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1])+ {+ for (i = 0; i < lowprimes.length; ++i)+ if (x[0] == lowprimes[i]) return true;+ return false;+ }+ if (x.isEven()) return false;+ i = 1;+ while (i < lowprimes.length)+ {+ var m = lowprimes[i],+ j = i + 1;+ while (j < lowprimes.length && m < lplim) m *= lowprimes[j++];+ m = x.modInt(m);+ while (i < j)+ if (m % lowprimes[i++] == 0) return false;+ }+ return x.millerRabin(t);+ }+ // (protected) true if probably prime (HAC 4.24, Miller-Rabin)+ function bnpMillerRabin(t)+ {+ var n1 = this.subtract(BigInteger.ONE);+ var k = n1.getLowestSetBit();+ if (k <= 0) return false;+ var r = n1.shiftRight(k);+ t = (t + 1) >> 1;+ if (t > lowprimes.length) t = lowprimes.length;+ var a = nbi();+ for (var i = 0; i < t; ++i)+ {+ //Pick bases at random, instead of starting at 2+ a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);+ var y = a.modPow(r, this);+ if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0)+ {+ var j = 1;+ while (j++ < k && y.compareTo(n1) != 0)+ {+ y = y.modPowInt(2, this);+ if (y.compareTo(BigInteger.ONE) == 0) return false;+ }+ if (y.compareTo(n1) != 0) return false;+ }+ }+ return true;+ }+ // protected+ BigInteger.prototype.chunkSize = bnpChunkSize;+ BigInteger.prototype.toRadix = bnpToRadix;+ BigInteger.prototype.fromRadix = bnpFromRadix;+ BigInteger.prototype.fromNumber = bnpFromNumber;+ BigInteger.prototype.bitwiseTo = bnpBitwiseTo;+ BigInteger.prototype.changeBit = bnpChangeBit;+ BigInteger.prototype.addTo = bnpAddTo;+ BigInteger.prototype.dMultiply = bnpDMultiply;+ BigInteger.prototype.dAddOffset = bnpDAddOffset;+ BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;+ BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;+ BigInteger.prototype.modInt = bnpModInt;+ BigInteger.prototype.millerRabin = bnpMillerRabin;+ // public+ BigInteger.prototype.clone = bnClone;+ BigInteger.prototype.intValue = bnIntValue;+ BigInteger.prototype.byteValue = bnByteValue;+ BigInteger.prototype.shortValue = bnShortValue;+ BigInteger.prototype.signum = bnSigNum;+ BigInteger.prototype.toByteArray = bnToByteArray;+ BigInteger.prototype.equals = bnEquals;+ BigInteger.prototype.min = bnMin;+ BigInteger.prototype.max = bnMax;+ BigInteger.prototype.and = bnAnd;+ BigInteger.prototype.or = bnOr;+ BigInteger.prototype.xor = bnXor;+ BigInteger.prototype.andNot = bnAndNot;+ BigInteger.prototype.not = bnNot;+ BigInteger.prototype.shiftLeft = bnShiftLeft;+ BigInteger.prototype.shiftRight = bnShiftRight;+ BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;+ BigInteger.prototype.bitCount = bnBitCount;+ BigInteger.prototype.testBit = bnTestBit;+ BigInteger.prototype.setBit = bnSetBit;+ BigInteger.prototype.clearBit = bnClearBit;+ BigInteger.prototype.flipBit = bnFlipBit;+ BigInteger.prototype.add = bnAdd;+ BigInteger.prototype.subtract = bnSubtract;+ BigInteger.prototype.multiply = bnMultiply;+ BigInteger.prototype.divide = bnDivide;+ BigInteger.prototype.remainder = bnRemainder;+ BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;+ BigInteger.prototype.modPow = bnModPow;+ BigInteger.prototype.modInverse = bnModInverse;+ BigInteger.prototype.pow = bnPow;+ BigInteger.prototype.gcd = bnGCD;+ BigInteger.prototype.isProbablePrime = bnIsProbablePrime;+ // JSBN-specific extension+ BigInteger.prototype.square = bnSquare;+ var Int128 = BigInteger;+ // BigInteger interfaces not implemented in jsbn:+ // BigInteger(int signum, byte[] magnitude)+ // double doubleValue()+ // float floatValue()+ // int hashCode()+ // long longValue()+ // static BigInteger valueOf(long val)+ // Helper functions to make BigInteger functions callable with two parameters+ // as in original C# Clipper+ Int128.prototype.IsNegative = function ()+ {+ if (this.compareTo(Int128.ZERO) == -1) return true;+ else return false;+ };++ Int128.op_Equality = function (val1, val2)+ {+ if (val1.compareTo(val2) == 0) return true;+ else return false;+ };++ Int128.op_Inequality = function (val1, val2)+ {+ if (val1.compareTo(val2) != 0) return true;+ else return false;+ };++ Int128.op_GreaterThan = function (val1, val2)+ {+ if (val1.compareTo(val2) > 0) return true;+ else return false;+ };++ Int128.op_LessThan = function (val1, val2)+ {+ if (val1.compareTo(val2) < 0) return true;+ else return false;+ };++ Int128.op_Addition = function (lhs, rhs)+ {+ return new Int128(lhs, undefined, undefined).add(new Int128(rhs, undefined, undefined));+ };++ Int128.op_Subtraction = function (lhs, rhs)+ {+ return new Int128(lhs, undefined, undefined).subtract(new Int128(rhs, undefined, undefined));+ };++ Int128.Int128Mul = function (lhs, rhs)+ {+ return new Int128(lhs, undefined, undefined).multiply(new Int128(rhs, undefined, undefined));+ };++ Int128.op_Division = function (lhs, rhs)+ {+ return lhs.divide(rhs);+ };++ Int128.prototype.ToDouble = function ()+ {+ return parseFloat(this.toString()); // This could be something faster+ };++ // end of Int128 section+ /*+ // Uncomment the following two lines if you want to use Int128 outside ClipperLib+ if (typeof(document) !== "undefined") window.Int128 = Int128;+ else self.Int128 = Int128;+ */++ // ---------------------------------------------++ // Here starts the actual Clipper library:+ // Helper function to support Inheritance in Javascript+ var Inherit = function (ce, ce2)+ {+ var p;+ if (typeof (Object.getOwnPropertyNames) === 'undefined')+ {+ for (p in ce2.prototype)+ if (typeof (ce.prototype[p]) === 'undefined' || ce.prototype[p] === Object.prototype[p]) ce.prototype[p] = ce2.prototype[p];+ for (p in ce2)+ if (typeof (ce[p]) === 'undefined') ce[p] = ce2[p];+ ce.$baseCtor = ce2;+ }+ else+ {+ var props = Object.getOwnPropertyNames(ce2.prototype);+ for (var i = 0; i < props.length; i++)+ if (typeof (Object.getOwnPropertyDescriptor(ce.prototype, props[i])) === 'undefined') Object.defineProperty(ce.prototype, props[i], Object.getOwnPropertyDescriptor(ce2.prototype, props[i]));+ for (p in ce2)+ if (typeof (ce[p]) === 'undefined') ce[p] = ce2[p];+ ce.$baseCtor = ce2;+ }+ };++ /**+ * @constructor+ */+ ClipperLib.Path = function ()+ {+ return [];+ };++ ClipperLib.Path.prototype.push = Array.prototype.push;++ /**+ * @constructor+ */+ ClipperLib.Paths = function ()+ {+ return []; // Was previously [[]], but caused problems when pushed+ };++ ClipperLib.Paths.prototype.push = Array.prototype.push;++ // Preserves the calling way of original C# Clipper+ // Is essential due to compatibility, because DoublePoint is public class in original C# version+ /**+ * @constructor+ */+ ClipperLib.DoublePoint = function ()+ {+ var a = arguments;+ this.X = 0;+ this.Y = 0;+ // public DoublePoint(DoublePoint dp)+ // public DoublePoint(IntPoint ip)+ if (a.length === 1)+ {+ this.X = a[0].X;+ this.Y = a[0].Y;+ }+ else if (a.length === 2)+ {+ this.X = a[0];+ this.Y = a[1];+ }+ }; // This is internal faster function when called without arguments+ /**+ * @constructor+ */+ ClipperLib.DoublePoint0 = function ()+ {+ this.X = 0;+ this.Y = 0;+ };++ ClipperLib.DoublePoint0.prototype = ClipperLib.DoublePoint.prototype;++ // This is internal faster function when called with 1 argument (dp or ip)+ /**+ * @constructor+ */+ ClipperLib.DoublePoint1 = function (dp)+ {+ this.X = dp.X;+ this.Y = dp.Y;+ };++ ClipperLib.DoublePoint1.prototype = ClipperLib.DoublePoint.prototype;++ // This is internal faster function when called with 2 arguments (x and y)+ /**+ * @constructor+ */+ ClipperLib.DoublePoint2 = function (x, y)+ {+ this.X = x;+ this.Y = y;+ };++ ClipperLib.DoublePoint2.prototype = ClipperLib.DoublePoint.prototype;++ // PolyTree & PolyNode start+ /**+ * @suppress {missingProperties}+ */+ ClipperLib.PolyNode = function ()+ {+ this.m_Parent = null;+ this.m_polygon = new ClipperLib.Path();+ this.m_Index = 0;+ this.m_jointype = 0;+ this.m_endtype = 0;+ this.m_Childs = [];+ this.IsOpen = false;+ };++ ClipperLib.PolyNode.prototype.IsHoleNode = function ()+ {+ var result = true;+ var node = this.m_Parent;+ while (node !== null)+ {+ result = !result;+ node = node.m_Parent;+ }+ return result;+ };++ ClipperLib.PolyNode.prototype.ChildCount = function ()+ {+ return this.m_Childs.length;+ };++ ClipperLib.PolyNode.prototype.Contour = function ()+ {+ return this.m_polygon;+ };++ ClipperLib.PolyNode.prototype.AddChild = function (Child)+ {+ var cnt = this.m_Childs.length;+ this.m_Childs.push(Child);+ Child.m_Parent = this;+ Child.m_Index = cnt;+ };++ ClipperLib.PolyNode.prototype.GetNext = function ()+ {+ if (this.m_Childs.length > 0)+ return this.m_Childs[0];+ else+ return this.GetNextSiblingUp();+ };++ ClipperLib.PolyNode.prototype.GetNextSiblingUp = function ()+ {+ if (this.m_Parent === null)+ return null;+ else if (this.m_Index === this.m_Parent.m_Childs.length - 1)+ return this.m_Parent.GetNextSiblingUp();+ else+ return this.m_Parent.m_Childs[this.m_Index + 1];+ };++ ClipperLib.PolyNode.prototype.Childs = function ()+ {+ return this.m_Childs;+ };++ ClipperLib.PolyNode.prototype.Parent = function ()+ {+ return this.m_Parent;+ };++ ClipperLib.PolyNode.prototype.IsHole = function ()+ {+ return this.IsHoleNode();+ };++ // PolyTree : PolyNode+ /**+ * @suppress {missingProperties}+ * @constructor+ */+ ClipperLib.PolyTree = function ()+ {+ this.m_AllPolys = [];+ ClipperLib.PolyNode.call(this);+ };++ ClipperLib.PolyTree.prototype.Clear = function ()+ {+ for (var i = 0, ilen = this.m_AllPolys.length; i < ilen; i++)+ this.m_AllPolys[i] = null;+ this.m_AllPolys.length = 0;+ this.m_Childs.length = 0;+ };++ ClipperLib.PolyTree.prototype.GetFirst = function ()+ {+ if (this.m_Childs.length > 0)+ return this.m_Childs[0];+ else+ return null;+ };++ ClipperLib.PolyTree.prototype.Total = function ()+ {+ var result = this.m_AllPolys.length;+ //with negative offsets, ignore the hidden outer polygon ...+ if (result > 0 && this.m_Childs[0] !== this.m_AllPolys[0]) result--;+ return result;+ };++ Inherit(ClipperLib.PolyTree, ClipperLib.PolyNode);++ // PolyTree & PolyNode end++ ClipperLib.Math_Abs_Int64 = ClipperLib.Math_Abs_Int32 = ClipperLib.Math_Abs_Double = function (a)+ {+ return Math.abs(a);+ };++ ClipperLib.Math_Max_Int32_Int32 = function (a, b)+ {+ return Math.max(a, b);+ };++ /*+ -----------------------------------+ cast_32 speedtest: http://jsperf.com/truncate-float-to-integer/2+ -----------------------------------+ */+ if (browser.msie || browser.opera || browser.safari) ClipperLib.Cast_Int32 = function (a)+ {+ return a | 0;+ };++ else ClipperLib.Cast_Int32 = function (a)+ { // eg. browser.chrome || browser.chromium || browser.firefox+ return ~~a;+ };++ /*+ --------------------------+ cast_64 speedtests: http://jsperf.com/truncate-float-to-integer+ Chrome: bitwise_not_floor+ Firefox17: toInteger (typeof test)+ IE9: bitwise_or_floor+ IE7 and IE8: to_parseint+ Chromium: to_floor_or_ceil+ Firefox3: to_floor_or_ceil+ Firefox15: to_floor_or_ceil+ Opera: to_floor_or_ceil+ Safari: to_floor_or_ceil+ --------------------------+ */+ if (typeof Number.toInteger === "undefined")+ Number.toInteger = null;++ if (browser.chrome) ClipperLib.Cast_Int64 = function (a)+ {+ if (a < -2147483648 || a > 2147483647)+ return a < 0 ? Math.ceil(a) : Math.floor(a);+ else return ~~a;+ };++ else if (browser.firefox && typeof (Number.toInteger) === "function") ClipperLib.Cast_Int64 = function (a)+ {+ return Number.toInteger(a);+ };++ else if (browser.msie7 || browser.msie8) ClipperLib.Cast_Int64 = function (a)+ {+ return parseInt(a, 10);+ };++ else if (browser.msie) ClipperLib.Cast_Int64 = function (a)+ {+ if (a < -2147483648 || a > 2147483647)+ return a < 0 ? Math.ceil(a) : Math.floor(a);+ return a | 0;+ };++ // eg. browser.chromium || browser.firefox || browser.opera || browser.safari+ else ClipperLib.Cast_Int64 = function (a)+ {+ return a < 0 ? Math.ceil(a) : Math.floor(a);+ };++ ClipperLib.Clear = function (a)+ {+ a.length = 0;+ };++ //ClipperLib.MaxSteps = 64; // How many steps at maximum in arc in BuildArc() function+ ClipperLib.PI = 3.141592653589793;+ ClipperLib.PI2 = 2 * 3.141592653589793;+ /**+ * @constructor+ */+ ClipperLib.IntPoint = function ()+ {+ var a = arguments,+ alen = a.length;+ this.X = 0;+ this.Y = 0;+ if (ClipperLib.use_xyz)+ {+ this.Z = 0;+ if (alen === 3) // public IntPoint(cInt x, cInt y, cInt z = 0)+ {+ this.X = a[0];+ this.Y = a[1];+ this.Z = a[2];+ }+ else if (alen === 2) // public IntPoint(cInt x, cInt y)+ {+ this.X = a[0];+ this.Y = a[1];+ this.Z = 0;+ }+ else if (alen === 1)+ {+ if (a[0] instanceof ClipperLib.DoublePoint) // public IntPoint(DoublePoint dp)+ {+ var dp = a[0];+ this.X = ClipperLib.Clipper.Round(dp.X);+ this.Y = ClipperLib.Clipper.Round(dp.Y);+ this.Z = 0;+ }+ else // public IntPoint(IntPoint pt)+ {+ var pt = a[0];+ if (typeof (pt.Z) === "undefined") pt.Z = 0;+ this.X = pt.X;+ this.Y = pt.Y;+ this.Z = pt.Z;+ }+ }+ else // public IntPoint()+ {+ this.X = 0;+ this.Y = 0;+ this.Z = 0;+ }+ }+ else // if (!ClipperLib.use_xyz)+ {+ if (alen === 2) // public IntPoint(cInt X, cInt Y)+ {+ this.X = a[0];+ this.Y = a[1];+ }+ else if (alen === 1)+ {+ if (a[0] instanceof ClipperLib.DoublePoint) // public IntPoint(DoublePoint dp)+ {+ var dp = a[0];+ this.X = ClipperLib.Clipper.Round(dp.X);+ this.Y = ClipperLib.Clipper.Round(dp.Y);+ }+ else // public IntPoint(IntPoint pt)+ {+ var pt = a[0];+ this.X = pt.X;+ this.Y = pt.Y;+ }+ }+ else // public IntPoint(IntPoint pt)+ {+ this.X = 0;+ this.Y = 0;+ }+ }+ };++ ClipperLib.IntPoint.op_Equality = function (a, b)+ {+ //return a == b;+ return a.X === b.X && a.Y === b.Y;+ };++ ClipperLib.IntPoint.op_Inequality = function (a, b)+ {+ //return a !== b;+ return a.X !== b.X || a.Y !== b.Y;+ };++ /*+ ClipperLib.IntPoint.prototype.Equals = function (obj)+ {+ if (obj === null)+ return false;+ if (obj instanceof ClipperLib.IntPoint)+ {+ var a = Cast(obj, ClipperLib.IntPoint);+ return (this.X == a.X) && (this.Y == a.Y);+ }+ else+ return false;+ };++ */++ /**+ * @constructor+ */+ ClipperLib.IntPoint0 = function ()+ {+ this.X = 0;+ this.Y = 0;+ if (ClipperLib.use_xyz)+ this.Z = 0;+ };++ ClipperLib.IntPoint0.prototype = ClipperLib.IntPoint.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntPoint1 = function (pt)+ {+ this.X = pt.X;+ this.Y = pt.Y;+ if (ClipperLib.use_xyz)+ {+ if (typeof pt.Z === "undefined") this.Z = 0;+ else this.Z = pt.Z;+ }+ };++ ClipperLib.IntPoint1.prototype = ClipperLib.IntPoint.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntPoint1dp = function (dp)+ {+ this.X = ClipperLib.Clipper.Round(dp.X);+ this.Y = ClipperLib.Clipper.Round(dp.Y);+ if (ClipperLib.use_xyz)+ this.Z = 0;+ };++ ClipperLib.IntPoint1dp.prototype = ClipperLib.IntPoint.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntPoint2 = function (x, y, z)+ {+ this.X = x;+ this.Y = y;+ if (ClipperLib.use_xyz)+ {+ if (typeof z === "undefined") this.Z = 0;+ else this.Z = z;+ }+ };++ ClipperLib.IntPoint2.prototype = ClipperLib.IntPoint.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntRect = function ()+ {+ var a = arguments,+ alen = a.length;+ if (alen === 4) // function (l, t, r, b)+ {+ this.left = a[0];+ this.top = a[1];+ this.right = a[2];+ this.bottom = a[3];+ }+ else if (alen === 1) // function (ir)+ {+ var ir = a[0];+ this.left = ir.left;+ this.top = ir.top;+ this.right = ir.right;+ this.bottom = ir.bottom;+ }+ else // function ()+ {+ this.left = 0;+ this.top = 0;+ this.right = 0;+ this.bottom = 0;+ }+ };++ /**+ * @constructor+ */+ ClipperLib.IntRect0 = function ()+ {+ this.left = 0;+ this.top = 0;+ this.right = 0;+ this.bottom = 0;+ };++ ClipperLib.IntRect0.prototype = ClipperLib.IntRect.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntRect1 = function (ir)+ {+ this.left = ir.left;+ this.top = ir.top;+ this.right = ir.right;+ this.bottom = ir.bottom;+ };++ ClipperLib.IntRect1.prototype = ClipperLib.IntRect.prototype;++ /**+ * @constructor+ */+ ClipperLib.IntRect4 = function (l, t, r, b)+ {+ this.left = l;+ this.top = t;+ this.right = r;+ this.bottom = b;+ };++ ClipperLib.IntRect4.prototype = ClipperLib.IntRect.prototype;++ ClipperLib.ClipType = {+ ctIntersection: 0,+ ctUnion: 1,+ ctDifference: 2,+ ctXor: 3+ };++ ClipperLib.PolyType = {+ ptSubject: 0,+ ptClip: 1+ };++ ClipperLib.PolyFillType = {+ pftEvenOdd: 0,+ pftNonZero: 1,+ pftPositive: 2,+ pftNegative: 3+ };++ ClipperLib.JoinType = {+ jtSquare: 0,+ jtRound: 1,+ jtMiter: 2+ };++ ClipperLib.EndType = {+ etOpenSquare: 0,+ etOpenRound: 1,+ etOpenButt: 2,+ etClosedLine: 3,+ etClosedPolygon: 4+ };++ ClipperLib.EdgeSide = {+ esLeft: 0,+ esRight: 1+ };++ ClipperLib.Direction = {+ dRightToLeft: 0,+ dLeftToRight: 1+ };++ /**+ * @constructor+ */+ ClipperLib.TEdge = function ()+ {+ this.Bot = new ClipperLib.IntPoint0();+ this.Curr = new ClipperLib.IntPoint0(); //current (updated for every new scanbeam)+ this.Top = new ClipperLib.IntPoint0();+ this.Delta = new ClipperLib.IntPoint0();+ this.Dx = 0;+ this.PolyTyp = ClipperLib.PolyType.ptSubject;+ this.Side = ClipperLib.EdgeSide.esLeft; //side only refers to current side of solution poly+ this.WindDelta = 0; //1 or -1 depending on winding direction+ this.WindCnt = 0;+ this.WindCnt2 = 0; //winding count of the opposite polytype+ this.OutIdx = 0;+ this.Next = null;+ this.Prev = null;+ this.NextInLML = null;+ this.NextInAEL = null;+ this.PrevInAEL = null;+ this.NextInSEL = null;+ this.PrevInSEL = null;+ };++ /**+ * @constructor+ */+ ClipperLib.IntersectNode = function ()+ {+ this.Edge1 = null;+ this.Edge2 = null;+ this.Pt = new ClipperLib.IntPoint0();+ };++ ClipperLib.MyIntersectNodeSort = function () {};++ ClipperLib.MyIntersectNodeSort.Compare = function (node1, node2)+ {+ var i = node2.Pt.Y - node1.Pt.Y;+ if (i > 0) return 1;+ else if (i < 0) return -1;+ else return 0;+ };++ /**+ * @constructor+ */+ ClipperLib.LocalMinima = function ()+ {+ this.Y = 0;+ this.LeftBound = null;+ this.RightBound = null;+ this.Next = null;+ };++ /**+ * @constructor+ */+ ClipperLib.Scanbeam = function ()+ {+ this.Y = 0;+ this.Next = null;+ };++ /**+ * @constructor+ */+ ClipperLib.Maxima = function ()+ {+ this.X = 0;+ this.Next = null;+ this.Prev = null;+ };++ //OutRec: contains a path in the clipping solution. Edges in the AEL will+ //carry a pointer to an OutRec when they are part of the clipping solution.+ /**+ * @constructor+ */+ ClipperLib.OutRec = function ()+ {+ this.Idx = 0;+ this.IsHole = false;+ this.IsOpen = false;+ this.FirstLeft = null; //see comments in clipper.pas+ this.Pts = null;+ this.BottomPt = null;+ this.PolyNode = null;+ };++ /**+ * @constructor+ */+ ClipperLib.OutPt = function ()+ {+ this.Idx = 0;+ this.Pt = new ClipperLib.IntPoint0();+ this.Next = null;+ this.Prev = null;+ };++ /**+ * @constructor+ */+ ClipperLib.Join = function ()+ {+ this.OutPt1 = null;+ this.OutPt2 = null;+ this.OffPt = new ClipperLib.IntPoint0();+ };++ ClipperLib.ClipperBase = function ()+ {+ this.m_MinimaList = null;+ this.m_CurrentLM = null;+ this.m_edges = new Array();+ this.m_UseFullRange = false;+ this.m_HasOpenPaths = false;+ this.PreserveCollinear = false;+ this.m_Scanbeam = null;+ this.m_PolyOuts = null;+ this.m_ActiveEdges = null;+ };++ // Ranges are in original C# too high for Javascript (in current state 2013 september):+ // protected const double horizontal = -3.4E+38;+ // internal const cInt loRange = 0x3FFFFFFF; // = 1073741823 = sqrt(2^63 -1)/2+ // internal const cInt hiRange = 0x3FFFFFFFFFFFFFFFL; // = 4611686018427387903 = sqrt(2^127 -1)/2+ // So had to adjust them to more suitable for Javascript.+ // If JS some day supports truly 64-bit integers, then these ranges can be as in C#+ // and biginteger library can be more simpler (as then 128bit can be represented as two 64bit numbers)+ ClipperLib.ClipperBase.horizontal = -9007199254740992; //-2^53+ ClipperLib.ClipperBase.Skip = -2;+ ClipperLib.ClipperBase.Unassigned = -1;+ ClipperLib.ClipperBase.tolerance = 1E-20;+ ClipperLib.ClipperBase.loRange = 47453132; // sqrt(2^53 -1)/2+ ClipperLib.ClipperBase.hiRange = 4503599627370495; // sqrt(2^106 -1)/2++ ClipperLib.ClipperBase.near_zero = function (val)+ {+ return (val > -ClipperLib.ClipperBase.tolerance) && (val < ClipperLib.ClipperBase.tolerance);+ };++ ClipperLib.ClipperBase.IsHorizontal = function (e)+ {+ return e.Delta.Y === 0;+ };++ ClipperLib.ClipperBase.prototype.PointIsVertex = function (pt, pp)+ {+ var pp2 = pp;+ do {+ if (ClipperLib.IntPoint.op_Equality(pp2.Pt, pt))+ return true;+ pp2 = pp2.Next;+ }+ while (pp2 !== pp)+ return false;+ };++ ClipperLib.ClipperBase.prototype.PointOnLineSegment = function (pt, linePt1, linePt2, UseFullRange)+ {+ if (UseFullRange)+ return ((pt.X === linePt1.X) && (pt.Y === linePt1.Y)) ||+ ((pt.X === linePt2.X) && (pt.Y === linePt2.Y)) ||+ (((pt.X > linePt1.X) === (pt.X < linePt2.X)) &&+ ((pt.Y > linePt1.Y) === (pt.Y < linePt2.Y)) &&+ (Int128.op_Equality(Int128.Int128Mul((pt.X - linePt1.X), (linePt2.Y - linePt1.Y)),+ Int128.Int128Mul((linePt2.X - linePt1.X), (pt.Y - linePt1.Y)))));+ else+ return ((pt.X === linePt1.X) && (pt.Y === linePt1.Y)) || ((pt.X === linePt2.X) && (pt.Y === linePt2.Y)) || (((pt.X > linePt1.X) === (pt.X < linePt2.X)) && ((pt.Y > linePt1.Y) === (pt.Y < linePt2.Y)) && ((pt.X - linePt1.X) * (linePt2.Y - linePt1.Y) === (linePt2.X - linePt1.X) * (pt.Y - linePt1.Y)));+ };++ ClipperLib.ClipperBase.prototype.PointOnPolygon = function (pt, pp, UseFullRange)+ {+ var pp2 = pp;+ while (true)+ {+ if (this.PointOnLineSegment(pt, pp2.Pt, pp2.Next.Pt, UseFullRange))+ return true;+ pp2 = pp2.Next;+ if (pp2 === pp)+ break;+ }+ return false;+ };++ ClipperLib.ClipperBase.prototype.SlopesEqual = ClipperLib.ClipperBase.SlopesEqual = function ()+ {+ var a = arguments,+ alen = a.length;+ var e1, e2, pt1, pt2, pt3, pt4, UseFullRange;+ if (alen === 3) // function (e1, e2, UseFullRange)+ {+ e1 = a[0];+ e2 = a[1];+ UseFullRange = a[2];+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(e1.Delta.Y, e2.Delta.X), Int128.Int128Mul(e1.Delta.X, e2.Delta.Y));+ else+ return ClipperLib.Cast_Int64((e1.Delta.Y) * (e2.Delta.X)) === ClipperLib.Cast_Int64((e1.Delta.X) * (e2.Delta.Y));+ }+ else if (alen === 4) // function (pt1, pt2, pt3, UseFullRange)+ {+ pt1 = a[0];+ pt2 = a[1];+ pt3 = a[2];+ UseFullRange = a[3];+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(pt1.Y - pt2.Y, pt2.X - pt3.X), Int128.Int128Mul(pt1.X - pt2.X, pt2.Y - pt3.Y));+ else+ return ClipperLib.Cast_Int64((pt1.Y - pt2.Y) * (pt2.X - pt3.X)) - ClipperLib.Cast_Int64((pt1.X - pt2.X) * (pt2.Y - pt3.Y)) === 0;+ }+ else // function (pt1, pt2, pt3, pt4, UseFullRange)+ {+ pt1 = a[0];+ pt2 = a[1];+ pt3 = a[2];+ pt4 = a[3];+ UseFullRange = a[4];+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(pt1.Y - pt2.Y, pt3.X - pt4.X), Int128.Int128Mul(pt1.X - pt2.X, pt3.Y - pt4.Y));+ else+ return ClipperLib.Cast_Int64((pt1.Y - pt2.Y) * (pt3.X - pt4.X)) - ClipperLib.Cast_Int64((pt1.X - pt2.X) * (pt3.Y - pt4.Y)) === 0;+ }+ };++ ClipperLib.ClipperBase.SlopesEqual3 = function (e1, e2, UseFullRange)+ {+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(e1.Delta.Y, e2.Delta.X), Int128.Int128Mul(e1.Delta.X, e2.Delta.Y));+ else+ return ClipperLib.Cast_Int64((e1.Delta.Y) * (e2.Delta.X)) === ClipperLib.Cast_Int64((e1.Delta.X) * (e2.Delta.Y));+ };++ ClipperLib.ClipperBase.SlopesEqual4 = function (pt1, pt2, pt3, UseFullRange)+ {+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(pt1.Y - pt2.Y, pt2.X - pt3.X), Int128.Int128Mul(pt1.X - pt2.X, pt2.Y - pt3.Y));+ else+ return ClipperLib.Cast_Int64((pt1.Y - pt2.Y) * (pt2.X - pt3.X)) - ClipperLib.Cast_Int64((pt1.X - pt2.X) * (pt2.Y - pt3.Y)) === 0;+ };++ ClipperLib.ClipperBase.SlopesEqual5 = function (pt1, pt2, pt3, pt4, UseFullRange)+ {+ if (UseFullRange)+ return Int128.op_Equality(Int128.Int128Mul(pt1.Y - pt2.Y, pt3.X - pt4.X), Int128.Int128Mul(pt1.X - pt2.X, pt3.Y - pt4.Y));+ else+ return ClipperLib.Cast_Int64((pt1.Y - pt2.Y) * (pt3.X - pt4.X)) - ClipperLib.Cast_Int64((pt1.X - pt2.X) * (pt3.Y - pt4.Y)) === 0;+ };++ ClipperLib.ClipperBase.prototype.Clear = function ()+ {+ this.DisposeLocalMinimaList();+ for (var i = 0, ilen = this.m_edges.length; i < ilen; ++i)+ {+ for (var j = 0, jlen = this.m_edges[i].length; j < jlen; ++j)+ this.m_edges[i][j] = null;+ ClipperLib.Clear(this.m_edges[i]);+ }+ ClipperLib.Clear(this.m_edges);+ this.m_UseFullRange = false;+ this.m_HasOpenPaths = false;+ };++ ClipperLib.ClipperBase.prototype.DisposeLocalMinimaList = function ()+ {+ while (this.m_MinimaList !== null)+ {+ var tmpLm = this.m_MinimaList.Next;+ this.m_MinimaList = null;+ this.m_MinimaList = tmpLm;+ }+ this.m_CurrentLM = null;+ };++ ClipperLib.ClipperBase.prototype.RangeTest = function (Pt, useFullRange)+ {+ if (useFullRange.Value)+ {+ if (Pt.X > ClipperLib.ClipperBase.hiRange || Pt.Y > ClipperLib.ClipperBase.hiRange || -Pt.X > ClipperLib.ClipperBase.hiRange || -Pt.Y > ClipperLib.ClipperBase.hiRange)+ ClipperLib.Error("Coordinate outside allowed range in RangeTest().");+ }+ else if (Pt.X > ClipperLib.ClipperBase.loRange || Pt.Y > ClipperLib.ClipperBase.loRange || -Pt.X > ClipperLib.ClipperBase.loRange || -Pt.Y > ClipperLib.ClipperBase.loRange)+ {+ useFullRange.Value = true;+ this.RangeTest(Pt, useFullRange);+ }+ };++ ClipperLib.ClipperBase.prototype.InitEdge = function (e, eNext, ePrev, pt)+ {+ e.Next = eNext;+ e.Prev = ePrev;+ //e.Curr = pt;+ e.Curr.X = pt.X;+ e.Curr.Y = pt.Y;+ if (ClipperLib.use_xyz) e.Curr.Z = pt.Z;+ e.OutIdx = -1;+ };++ ClipperLib.ClipperBase.prototype.InitEdge2 = function (e, polyType)+ {+ if (e.Curr.Y >= e.Next.Curr.Y)+ {+ //e.Bot = e.Curr;+ e.Bot.X = e.Curr.X;+ e.Bot.Y = e.Curr.Y;+ if (ClipperLib.use_xyz) e.Bot.Z = e.Curr.Z;+ //e.Top = e.Next.Curr;+ e.Top.X = e.Next.Curr.X;+ e.Top.Y = e.Next.Curr.Y;+ if (ClipperLib.use_xyz) e.Top.Z = e.Next.Curr.Z;+ }+ else+ {+ //e.Top = e.Curr;+ e.Top.X = e.Curr.X;+ e.Top.Y = e.Curr.Y;+ if (ClipperLib.use_xyz) e.Top.Z = e.Curr.Z;+ //e.Bot = e.Next.Curr;+ e.Bot.X = e.Next.Curr.X;+ e.Bot.Y = e.Next.Curr.Y;+ if (ClipperLib.use_xyz) e.Bot.Z = e.Next.Curr.Z;+ }+ this.SetDx(e);+ e.PolyTyp = polyType;+ };++ ClipperLib.ClipperBase.prototype.FindNextLocMin = function (E)+ {+ var E2;+ for (;;)+ {+ while (ClipperLib.IntPoint.op_Inequality(E.Bot, E.Prev.Bot) || ClipperLib.IntPoint.op_Equality(E.Curr, E.Top))+ E = E.Next;+ if (E.Dx !== ClipperLib.ClipperBase.horizontal && E.Prev.Dx !== ClipperLib.ClipperBase.horizontal)+ break;+ while (E.Prev.Dx === ClipperLib.ClipperBase.horizontal)+ E = E.Prev;+ E2 = E;+ while (E.Dx === ClipperLib.ClipperBase.horizontal)+ E = E.Next;+ if (E.Top.Y === E.Prev.Bot.Y)+ continue;+ //ie just an intermediate horz.+ if (E2.Prev.Bot.X < E.Bot.X)+ E = E2;+ break;+ }+ return E;+ };++ ClipperLib.ClipperBase.prototype.ProcessBound = function (E, LeftBoundIsForward)+ {+ var EStart;+ var Result = E;+ var Horz;++ if (Result.OutIdx === ClipperLib.ClipperBase.Skip)+ {+ //check if there are edges beyond the skip edge in the bound and if so+ //create another LocMin and calling ProcessBound once more ...+ E = Result;+ if (LeftBoundIsForward)+ {+ while (E.Top.Y === E.Next.Bot.Y) E = E.Next;+ while (E !== Result && E.Dx === ClipperLib.ClipperBase.horizontal) E = E.Prev;+ }+ else+ {+ while (E.Top.Y === E.Prev.Bot.Y) E = E.Prev;+ while (E !== Result && E.Dx === ClipperLib.ClipperBase.horizontal) E = E.Next;+ }+ if (E === Result)+ {+ if (LeftBoundIsForward) Result = E.Next;+ else Result = E.Prev;+ }+ else+ {+ //there are more edges in the bound beyond result starting with E+ if (LeftBoundIsForward)+ E = Result.Next;+ else+ E = Result.Prev;+ var locMin = new ClipperLib.LocalMinima();+ locMin.Next = null;+ locMin.Y = E.Bot.Y;+ locMin.LeftBound = null;+ locMin.RightBound = E;+ E.WindDelta = 0;+ Result = this.ProcessBound(E, LeftBoundIsForward);+ this.InsertLocalMinima(locMin);+ }+ return Result;+ }++ if (E.Dx === ClipperLib.ClipperBase.horizontal)+ {+ //We need to be careful with open paths because this may not be a+ //true local minima (ie E may be following a skip edge).+ //Also, consecutive horz. edges may start heading left before going right.+ if (LeftBoundIsForward) EStart = E.Prev;+ else EStart = E.Next;++ if (EStart.Dx === ClipperLib.ClipperBase.horizontal) //ie an adjoining horizontal skip edge+ {+ if (EStart.Bot.X !== E.Bot.X && EStart.Top.X !== E.Bot.X)+ this.ReverseHorizontal(E);+ }+ else if (EStart.Bot.X !== E.Bot.X)+ this.ReverseHorizontal(E);+ }++ EStart = E;+ if (LeftBoundIsForward)+ {+ while (Result.Top.Y === Result.Next.Bot.Y && Result.Next.OutIdx !== ClipperLib.ClipperBase.Skip)+ Result = Result.Next;+ if (Result.Dx === ClipperLib.ClipperBase.horizontal && Result.Next.OutIdx !== ClipperLib.ClipperBase.Skip)+ {+ //nb: at the top of a bound, horizontals are added to the bound+ //only when the preceding edge attaches to the horizontal's left vertex+ //unless a Skip edge is encountered when that becomes the top divide+ Horz = Result;+ while (Horz.Prev.Dx === ClipperLib.ClipperBase.horizontal)+ Horz = Horz.Prev;+ if (Horz.Prev.Top.X > Result.Next.Top.X)+ Result = Horz.Prev;+ }+ while (E !== Result)+ {+ E.NextInLML = E.Next;+ if (E.Dx === ClipperLib.ClipperBase.horizontal && E !== EStart && E.Bot.X !== E.Prev.Top.X)+ this.ReverseHorizontal(E);+ E = E.Next;+ }+ if (E.Dx === ClipperLib.ClipperBase.horizontal && E !== EStart && E.Bot.X !== E.Prev.Top.X)+ this.ReverseHorizontal(E);+ Result = Result.Next;+ //move to the edge just beyond current bound+ }+ else+ {+ while (Result.Top.Y === Result.Prev.Bot.Y && Result.Prev.OutIdx !== ClipperLib.ClipperBase.Skip)+ Result = Result.Prev;+ if (Result.Dx === ClipperLib.ClipperBase.horizontal && Result.Prev.OutIdx !== ClipperLib.ClipperBase.Skip)+ {+ Horz = Result;+ while (Horz.Next.Dx === ClipperLib.ClipperBase.horizontal)+ Horz = Horz.Next;+ if (Horz.Next.Top.X === Result.Prev.Top.X || Horz.Next.Top.X > Result.Prev.Top.X)+ {+ Result = Horz.Next;+ }+ }+ while (E !== Result)+ {+ E.NextInLML = E.Prev;+ if (E.Dx === ClipperLib.ClipperBase.horizontal && E !== EStart && E.Bot.X !== E.Next.Top.X)+ this.ReverseHorizontal(E);+ E = E.Prev;+ }+ if (E.Dx === ClipperLib.ClipperBase.horizontal && E !== EStart && E.Bot.X !== E.Next.Top.X)+ this.ReverseHorizontal(E);+ Result = Result.Prev;+ //move to the edge just beyond current bound+ }++ return Result;+ };++ ClipperLib.ClipperBase.prototype.AddPath = function (pg, polyType, Closed)+ {+ if (ClipperLib.use_lines)+ {+ if (!Closed && polyType === ClipperLib.PolyType.ptClip)+ ClipperLib.Error("AddPath: Open paths must be subject.");+ }+ else+ {+ if (!Closed)+ ClipperLib.Error("AddPath: Open paths have been disabled.");+ }+ var highI = pg.length - 1;+ if (Closed)+ while (highI > 0 && (ClipperLib.IntPoint.op_Equality(pg[highI], pg[0])))+ --highI;+ while (highI > 0 && (ClipperLib.IntPoint.op_Equality(pg[highI], pg[highI - 1])))+ --highI;+ if ((Closed && highI < 2) || (!Closed && highI < 1))+ return false;+ //create a new edge array ...+ var edges = new Array();+ for (var i = 0; i <= highI; i++)+ edges.push(new ClipperLib.TEdge());+ var IsFlat = true;+ //1. Basic (first) edge initialization ...++ //edges[1].Curr = pg[1];+ edges[1].Curr.X = pg[1].X;+ edges[1].Curr.Y = pg[1].Y;+ if (ClipperLib.use_xyz) edges[1].Curr.Z = pg[1].Z;++ var $1 = {+ Value: this.m_UseFullRange+ };++ this.RangeTest(pg[0], $1);+ this.m_UseFullRange = $1.Value;++ $1.Value = this.m_UseFullRange;+ this.RangeTest(pg[highI], $1);+ this.m_UseFullRange = $1.Value;++ this.InitEdge(edges[0], edges[1], edges[highI], pg[0]);+ this.InitEdge(edges[highI], edges[0], edges[highI - 1], pg[highI]);+ for (var i = highI - 1; i >= 1; --i)+ {+ $1.Value = this.m_UseFullRange;+ this.RangeTest(pg[i], $1);+ this.m_UseFullRange = $1.Value;++ this.InitEdge(edges[i], edges[i + 1], edges[i - 1], pg[i]);+ }++ var eStart = edges[0];+ //2. Remove duplicate vertices, and (when closed) collinear edges ...+ var E = eStart,+ eLoopStop = eStart;+ for (;;)+ {+ //console.log(E.Next, eStart);+ //nb: allows matching start and end points when not Closed ...+ if (E.Curr === E.Next.Curr && (Closed || E.Next !== eStart))+ {+ if (E === E.Next)+ break;+ if (E === eStart)+ eStart = E.Next;+ E = this.RemoveEdge(E);+ eLoopStop = E;+ continue;+ }+ if (E.Prev === E.Next)+ break;+ else if (Closed && ClipperLib.ClipperBase.SlopesEqual4(E.Prev.Curr, E.Curr, E.Next.Curr, this.m_UseFullRange) && (!this.PreserveCollinear || !this.Pt2IsBetweenPt1AndPt3(E.Prev.Curr, E.Curr, E.Next.Curr)))+ {+ //Collinear edges are allowed for open paths but in closed paths+ //the default is to merge adjacent collinear edges into a single edge.+ //However, if the PreserveCollinear property is enabled, only overlapping+ //collinear edges (ie spikes) will be removed from closed paths.+ if (E === eStart)+ eStart = E.Next;+ E = this.RemoveEdge(E);+ E = E.Prev;+ eLoopStop = E;+ continue;+ }+ E = E.Next;+ if ((E === eLoopStop) || (!Closed && E.Next === eStart)) break;+ }+ if ((!Closed && (E === E.Next)) || (Closed && (E.Prev === E.Next)))+ return false;+ if (!Closed)+ {+ this.m_HasOpenPaths = true;+ eStart.Prev.OutIdx = ClipperLib.ClipperBase.Skip;+ }+ //3. Do second stage of edge initialization ...+ E = eStart;+ do {+ this.InitEdge2(E, polyType);+ E = E.Next;+ if (IsFlat && E.Curr.Y !== eStart.Curr.Y)+ IsFlat = false;+ }+ while (E !== eStart)+ //4. Finally, add edge bounds to LocalMinima list ...+ //Totally flat paths must be handled differently when adding them+ //to LocalMinima list to avoid endless loops etc ...+ if (IsFlat)+ {+ if (Closed)+ return false;++ E.Prev.OutIdx = ClipperLib.ClipperBase.Skip;++ var locMin = new ClipperLib.LocalMinima();+ locMin.Next = null;+ locMin.Y = E.Bot.Y;+ locMin.LeftBound = null;+ locMin.RightBound = E;+ locMin.RightBound.Side = ClipperLib.EdgeSide.esRight;+ locMin.RightBound.WindDelta = 0;++ for (;;)+ {+ if (E.Bot.X !== E.Prev.Top.X) this.ReverseHorizontal(E);+ if (E.Next.OutIdx === ClipperLib.ClipperBase.Skip) break;+ E.NextInLML = E.Next;+ E = E.Next;+ }+ this.InsertLocalMinima(locMin);+ this.m_edges.push(edges);+ return true;+ }+ this.m_edges.push(edges);+ var leftBoundIsForward;+ var EMin = null;++ //workaround to avoid an endless loop in the while loop below when+ //open paths have matching start and end points ...+ if (ClipperLib.IntPoint.op_Equality(E.Prev.Bot, E.Prev.Top))+ E = E.Next;++ for (;;)+ {+ E = this.FindNextLocMin(E);+ if (E === EMin)+ break;+ else if (EMin === null)+ EMin = E;+ //E and E.Prev now share a local minima (left aligned if horizontal).+ //Compare their slopes to find which starts which bound ...+ var locMin = new ClipperLib.LocalMinima();+ locMin.Next = null;+ locMin.Y = E.Bot.Y;+ if (E.Dx < E.Prev.Dx)+ {+ locMin.LeftBound = E.Prev;+ locMin.RightBound = E;+ leftBoundIsForward = false;+ //Q.nextInLML = Q.prev+ }+ else+ {+ locMin.LeftBound = E;+ locMin.RightBound = E.Prev;+ leftBoundIsForward = true;+ //Q.nextInLML = Q.next+ }+ locMin.LeftBound.Side = ClipperLib.EdgeSide.esLeft;+ locMin.RightBound.Side = ClipperLib.EdgeSide.esRight;+ if (!Closed)+ locMin.LeftBound.WindDelta = 0;+ else if (locMin.LeftBound.Next === locMin.RightBound)+ locMin.LeftBound.WindDelta = -1;+ else+ locMin.LeftBound.WindDelta = 1;+ locMin.RightBound.WindDelta = -locMin.LeftBound.WindDelta;+ E = this.ProcessBound(locMin.LeftBound, leftBoundIsForward);+ if (E.OutIdx === ClipperLib.ClipperBase.Skip)+ E = this.ProcessBound(E, leftBoundIsForward);+ var E2 = this.ProcessBound(locMin.RightBound, !leftBoundIsForward);+ if (E2.OutIdx === ClipperLib.ClipperBase.Skip) E2 = this.ProcessBound(E2, !leftBoundIsForward);+ if (locMin.LeftBound.OutIdx === ClipperLib.ClipperBase.Skip)+ locMin.LeftBound = null;+ else if (locMin.RightBound.OutIdx === ClipperLib.ClipperBase.Skip)+ locMin.RightBound = null;+ this.InsertLocalMinima(locMin);+ if (!leftBoundIsForward)+ E = E2;+ }+ return true;+ };++ ClipperLib.ClipperBase.prototype.AddPaths = function (ppg, polyType, closed)+ {+ // console.log("-------------------------------------------");+ // console.log(JSON.stringify(ppg));+ var result = false;+ for (var i = 0, ilen = ppg.length; i < ilen; ++i)+ if (this.AddPath(ppg[i], polyType, closed))+ result = true;+ return result;+ };++ ClipperLib.ClipperBase.prototype.Pt2IsBetweenPt1AndPt3 = function (pt1, pt2, pt3)+ {+ if ((ClipperLib.IntPoint.op_Equality(pt1, pt3)) || (ClipperLib.IntPoint.op_Equality(pt1, pt2)) || (ClipperLib.IntPoint.op_Equality(pt3, pt2)))++ //if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))+ return false;++ else if (pt1.X !== pt3.X)+ return (pt2.X > pt1.X) === (pt2.X < pt3.X);+ else+ return (pt2.Y > pt1.Y) === (pt2.Y < pt3.Y);+ };++ ClipperLib.ClipperBase.prototype.RemoveEdge = function (e)+ {+ //removes e from double_linked_list (but without removing from memory)+ e.Prev.Next = e.Next;+ e.Next.Prev = e.Prev;+ var result = e.Next;+ e.Prev = null; //flag as removed (see ClipperBase.Clear)+ return result;+ };++ ClipperLib.ClipperBase.prototype.SetDx = function (e)+ {+ e.Delta.X = (e.Top.X - e.Bot.X);+ e.Delta.Y = (e.Top.Y - e.Bot.Y);+ if (e.Delta.Y === 0) e.Dx = ClipperLib.ClipperBase.horizontal;+ else e.Dx = (e.Delta.X) / (e.Delta.Y);+ };++ ClipperLib.ClipperBase.prototype.InsertLocalMinima = function (newLm)+ {+ if (this.m_MinimaList === null)+ {+ this.m_MinimaList = newLm;+ }+ else if (newLm.Y >= this.m_MinimaList.Y)+ {+ newLm.Next = this.m_MinimaList;+ this.m_MinimaList = newLm;+ }+ else+ {+ var tmpLm = this.m_MinimaList;+ while (tmpLm.Next !== null && (newLm.Y < tmpLm.Next.Y))+ tmpLm = tmpLm.Next;+ newLm.Next = tmpLm.Next;+ tmpLm.Next = newLm;+ }+ };++ ClipperLib.ClipperBase.prototype.PopLocalMinima = function (Y, current)+ {+ current.v = this.m_CurrentLM;+ if (this.m_CurrentLM !== null && this.m_CurrentLM.Y === Y)+ {+ this.m_CurrentLM = this.m_CurrentLM.Next;+ return true;+ }+ return false;+ };++ ClipperLib.ClipperBase.prototype.ReverseHorizontal = function (e)+ {+ //swap horizontal edges' top and bottom x's so they follow the natural+ //progression of the bounds - ie so their xbots will align with the+ //adjoining lower edge. [Helpful in the ProcessHorizontal() method.]+ var tmp = e.Top.X;+ e.Top.X = e.Bot.X;+ e.Bot.X = tmp;+ if (ClipperLib.use_xyz)+ {+ tmp = e.Top.Z;+ e.Top.Z = e.Bot.Z;+ e.Bot.Z = tmp;+ }+ };++ ClipperLib.ClipperBase.prototype.Reset = function ()+ {+ this.m_CurrentLM = this.m_MinimaList;+ if (this.m_CurrentLM === null) //ie nothing to process+ return;+ //reset all edges ...+ this.m_Scanbeam = null;+ var lm = this.m_MinimaList;+ while (lm !== null)+ {+ this.InsertScanbeam(lm.Y);+ var e = lm.LeftBound;+ if (e !== null)+ {+ //e.Curr = e.Bot;+ e.Curr.X = e.Bot.X;+ e.Curr.Y = e.Bot.Y;+ if (ClipperLib.use_xyz) e.Curr.Z = e.Bot.Z;+ e.OutIdx = ClipperLib.ClipperBase.Unassigned;+ }+ e = lm.RightBound;+ if (e !== null)+ {+ //e.Curr = e.Bot;+ e.Curr.X = e.Bot.X;+ e.Curr.Y = e.Bot.Y;+ if (ClipperLib.use_xyz) e.Curr.Z = e.Bot.Z;+ e.OutIdx = ClipperLib.ClipperBase.Unassigned;+ }+ lm = lm.Next;+ }+ this.m_ActiveEdges = null;+ };++ ClipperLib.ClipperBase.prototype.InsertScanbeam = function (Y)+ {+ //single-linked list: sorted descending, ignoring dups.+ if (this.m_Scanbeam === null)+ {+ this.m_Scanbeam = new ClipperLib.Scanbeam();+ this.m_Scanbeam.Next = null;+ this.m_Scanbeam.Y = Y;+ }+ else if (Y > this.m_Scanbeam.Y)+ {+ var newSb = new ClipperLib.Scanbeam();+ newSb.Y = Y;+ newSb.Next = this.m_Scanbeam;+ this.m_Scanbeam = newSb;+ }+ else+ {+ var sb2 = this.m_Scanbeam;+ while (sb2.Next !== null && Y <= sb2.Next.Y)+ {+ sb2 = sb2.Next;+ }+ if (Y === sb2.Y)+ {+ return;+ } //ie ignores duplicates+ var newSb1 = new ClipperLib.Scanbeam();+ newSb1.Y = Y;+ newSb1.Next = sb2.Next;+ sb2.Next = newSb1;+ }+ };++ ClipperLib.ClipperBase.prototype.PopScanbeam = function (Y)+ {+ if (this.m_Scanbeam === null)+ {+ Y.v = 0;+ return false;+ }+ Y.v = this.m_Scanbeam.Y;+ this.m_Scanbeam = this.m_Scanbeam.Next;+ return true;+ };++ ClipperLib.ClipperBase.prototype.LocalMinimaPending = function ()+ {+ return (this.m_CurrentLM !== null);+ };++ ClipperLib.ClipperBase.prototype.CreateOutRec = function ()+ {+ var result = new ClipperLib.OutRec();+ result.Idx = ClipperLib.ClipperBase.Unassigned;+ result.IsHole = false;+ result.IsOpen = false;+ result.FirstLeft = null;+ result.Pts = null;+ result.BottomPt = null;+ result.PolyNode = null;+ this.m_PolyOuts.push(result);+ result.Idx = this.m_PolyOuts.length - 1;+ return result;+ };++ ClipperLib.ClipperBase.prototype.DisposeOutRec = function (index)+ {+ var outRec = this.m_PolyOuts[index];+ outRec.Pts = null;+ outRec = null;+ this.m_PolyOuts[index] = null;+ };++ ClipperLib.ClipperBase.prototype.UpdateEdgeIntoAEL = function (e)+ {+ if (e.NextInLML === null)+ {+ ClipperLib.Error("UpdateEdgeIntoAEL: invalid call");+ }+ var AelPrev = e.PrevInAEL;+ var AelNext = e.NextInAEL;+ e.NextInLML.OutIdx = e.OutIdx;+ if (AelPrev !== null)+ {+ AelPrev.NextInAEL = e.NextInLML;+ }+ else+ {+ this.m_ActiveEdges = e.NextInLML;+ }+ if (AelNext !== null)+ {+ AelNext.PrevInAEL = e.NextInLML;+ }+ e.NextInLML.Side = e.Side;+ e.NextInLML.WindDelta = e.WindDelta;+ e.NextInLML.WindCnt = e.WindCnt;+ e.NextInLML.WindCnt2 = e.WindCnt2;+ e = e.NextInLML;+ e.Curr.X = e.Bot.X;+ e.Curr.Y = e.Bot.Y;+ e.PrevInAEL = AelPrev;+ e.NextInAEL = AelNext;+ if (!ClipperLib.ClipperBase.IsHorizontal(e))+ {+ this.InsertScanbeam(e.Top.Y);+ }+ return e;+ };++ ClipperLib.ClipperBase.prototype.SwapPositionsInAEL = function (edge1, edge2)+ {+ //check that one or other edge hasn't already been removed from AEL ...+ if (edge1.NextInAEL === edge1.PrevInAEL || edge2.NextInAEL === edge2.PrevInAEL)+ {+ return;+ }++ if (edge1.NextInAEL === edge2)+ {+ var next = edge2.NextInAEL;+ if (next !== null)+ {+ next.PrevInAEL = edge1;+ }+ var prev = edge1.PrevInAEL;+ if (prev !== null)+ {+ prev.NextInAEL = edge2;+ }+ edge2.PrevInAEL = prev;+ edge2.NextInAEL = edge1;+ edge1.PrevInAEL = edge2;+ edge1.NextInAEL = next;+ }+ else if (edge2.NextInAEL === edge1)+ {+ var next1 = edge1.NextInAEL;+ if (next1 !== null)+ {+ next1.PrevInAEL = edge2;+ }+ var prev1 = edge2.PrevInAEL;+ if (prev1 !== null)+ {+ prev1.NextInAEL = edge1;+ }+ edge1.PrevInAEL = prev1;+ edge1.NextInAEL = edge2;+ edge2.PrevInAEL = edge1;+ edge2.NextInAEL = next1;+ }+ else+ {+ var next2 = edge1.NextInAEL;+ var prev2 = edge1.PrevInAEL;+ edge1.NextInAEL = edge2.NextInAEL;+ if (edge1.NextInAEL !== null)+ {+ edge1.NextInAEL.PrevInAEL = edge1;+ }+ edge1.PrevInAEL = edge2.PrevInAEL;+ if (edge1.PrevInAEL !== null)+ {+ edge1.PrevInAEL.NextInAEL = edge1;+ }+ edge2.NextInAEL = next2;+ if (edge2.NextInAEL !== null)+ {+ edge2.NextInAEL.PrevInAEL = edge2;+ }+ edge2.PrevInAEL = prev2;+ if (edge2.PrevInAEL !== null)+ {+ edge2.PrevInAEL.NextInAEL = edge2;+ }+ }++ if (edge1.PrevInAEL === null)+ {+ this.m_ActiveEdges = edge1;+ }+ else+ {+ if (edge2.PrevInAEL === null)+ {+ this.m_ActiveEdges = edge2;+ }+ }+ };++ ClipperLib.ClipperBase.prototype.DeleteFromAEL = function (e)+ {+ var AelPrev = e.PrevInAEL;+ var AelNext = e.NextInAEL;+ if (AelPrev === null && AelNext === null && e !== this.m_ActiveEdges)+ {+ return;+ } //already deleted+ if (AelPrev !== null)+ {+ AelPrev.NextInAEL = AelNext;+ }+ else+ {+ this.m_ActiveEdges = AelNext;+ }+ if (AelNext !== null)+ {+ AelNext.PrevInAEL = AelPrev;+ }+ e.NextInAEL = null;+ e.PrevInAEL = null;+ }++ // public Clipper(int InitOptions = 0)+ /**+ * @suppress {missingProperties}+ */+ ClipperLib.Clipper = function (InitOptions)+ {+ if (typeof (InitOptions) === "undefined") InitOptions = 0;+ this.m_PolyOuts = null;+ this.m_ClipType = ClipperLib.ClipType.ctIntersection;+ this.m_Scanbeam = null;+ this.m_Maxima = null;+ this.m_ActiveEdges = null;+ this.m_SortedEdges = null;+ this.m_IntersectList = null;+ this.m_IntersectNodeComparer = null;+ this.m_ExecuteLocked = false;+ this.m_ClipFillType = ClipperLib.PolyFillType.pftEvenOdd;+ this.m_SubjFillType = ClipperLib.PolyFillType.pftEvenOdd;+ this.m_Joins = null;+ this.m_GhostJoins = null;+ this.m_UsingPolyTree = false;+ this.ReverseSolution = false;+ this.StrictlySimple = false;++ ClipperLib.ClipperBase.call(this);++ this.m_Scanbeam = null;+ this.m_Maxima = null;+ this.m_ActiveEdges = null;+ this.m_SortedEdges = null;+ this.m_IntersectList = new Array();+ this.m_IntersectNodeComparer = ClipperLib.MyIntersectNodeSort.Compare;+ this.m_ExecuteLocked = false;+ this.m_UsingPolyTree = false;+ this.m_PolyOuts = new Array();+ this.m_Joins = new Array();+ this.m_GhostJoins = new Array();+ this.ReverseSolution = (1 & InitOptions) !== 0;+ this.StrictlySimple = (2 & InitOptions) !== 0;+ this.PreserveCollinear = (4 & InitOptions) !== 0;+ if (ClipperLib.use_xyz)+ {+ this.ZFillFunction = null; // function (IntPoint vert1, IntPoint vert2, ref IntPoint intersectPt);+ }+ };++ ClipperLib.Clipper.ioReverseSolution = 1;+ ClipperLib.Clipper.ioStrictlySimple = 2;+ ClipperLib.Clipper.ioPreserveCollinear = 4;++ ClipperLib.Clipper.prototype.Clear = function ()+ {+ if (this.m_edges.length === 0)+ return;+ //avoids problems with ClipperBase destructor+ this.DisposeAllPolyPts();+ ClipperLib.ClipperBase.prototype.Clear.call(this);+ };++ ClipperLib.Clipper.prototype.InsertMaxima = function (X)+ {+ //double-linked list: sorted ascending, ignoring dups.+ var newMax = new ClipperLib.Maxima();+ newMax.X = X;+ if (this.m_Maxima === null)+ {+ this.m_Maxima = newMax;+ this.m_Maxima.Next = null;+ this.m_Maxima.Prev = null;+ }+ else if (X < this.m_Maxima.X)+ {+ newMax.Next = this.m_Maxima;+ newMax.Prev = null;+ this.m_Maxima = newMax;+ }+ else+ {+ var m = this.m_Maxima;+ while (m.Next !== null && X >= m.Next.X)+ {+ m = m.Next;+ }+ if (X === m.X)+ {+ return;+ } //ie ignores duplicates (& CG to clean up newMax)+ //insert newMax between m and m.Next ...+ newMax.Next = m.Next;+ newMax.Prev = m;+ if (m.Next !== null)+ {+ m.Next.Prev = newMax;+ }+ m.Next = newMax;+ }+ };++ // ************************************+ ClipperLib.Clipper.prototype.Execute = function ()+ {+ var a = arguments,+ alen = a.length,+ ispolytree = a[1] instanceof ClipperLib.PolyTree;+ if (alen === 4 && !ispolytree) // function (clipType, solution, subjFillType, clipFillType)+ {+ var clipType = a[0],+ solution = a[1],+ subjFillType = a[2],+ clipFillType = a[3];+ if (this.m_ExecuteLocked)+ return false;+ if (this.m_HasOpenPaths)+ ClipperLib.Error("Error: PolyTree struct is needed for open path clipping.");+ this.m_ExecuteLocked = true;+ ClipperLib.Clear(solution);+ this.m_SubjFillType = subjFillType;+ this.m_ClipFillType = clipFillType;+ this.m_ClipType = clipType;+ this.m_UsingPolyTree = false;+ try+ {+ var succeeded = this.ExecuteInternal();+ //build the return polygons ...+ if (succeeded) this.BuildResult(solution);+ }+ finally+ {+ this.DisposeAllPolyPts();+ this.m_ExecuteLocked = false;+ }+ return succeeded;+ }+ else if (alen === 4 && ispolytree) // function (clipType, polytree, subjFillType, clipFillType)+ {+ var clipType = a[0],+ polytree = a[1],+ subjFillType = a[2],+ clipFillType = a[3];+ if (this.m_ExecuteLocked)+ return false;+ this.m_ExecuteLocked = true;+ this.m_SubjFillType = subjFillType;+ this.m_ClipFillType = clipFillType;+ this.m_ClipType = clipType;+ this.m_UsingPolyTree = true;+ try+ {+ var succeeded = this.ExecuteInternal();+ //build the return polygons ...+ if (succeeded) this.BuildResult2(polytree);+ }+ finally+ {+ this.DisposeAllPolyPts();+ this.m_ExecuteLocked = false;+ }+ return succeeded;+ }+ else if (alen === 2 && !ispolytree) // function (clipType, solution)+ {+ var clipType = a[0],+ solution = a[1];+ return this.Execute(clipType, solution, ClipperLib.PolyFillType.pftEvenOdd, ClipperLib.PolyFillType.pftEvenOdd);+ }+ else if (alen === 2 && ispolytree) // function (clipType, polytree)+ {+ var clipType = a[0],+ polytree = a[1];+ return this.Execute(clipType, polytree, ClipperLib.PolyFillType.pftEvenOdd, ClipperLib.PolyFillType.pftEvenOdd);+ }+ };++ ClipperLib.Clipper.prototype.FixHoleLinkage = function (outRec)+ {+ //skip if an outermost polygon or+ //already already points to the correct FirstLeft ...+ if (outRec.FirstLeft === null || (outRec.IsHole !== outRec.FirstLeft.IsHole && outRec.FirstLeft.Pts !== null))+ return;+ var orfl = outRec.FirstLeft;+ while (orfl !== null && ((orfl.IsHole === outRec.IsHole) || orfl.Pts === null))+ orfl = orfl.FirstLeft;+ outRec.FirstLeft = orfl;+ };++ ClipperLib.Clipper.prototype.ExecuteInternal = function ()+ {+ try+ {+ this.Reset();+ this.m_SortedEdges = null;+ this.m_Maxima = null;++ var botY = {},+ topY = {};++ if (!this.PopScanbeam(botY))+ {+ return false;+ }+ this.InsertLocalMinimaIntoAEL(botY.v);+ while (this.PopScanbeam(topY) || this.LocalMinimaPending())+ {+ this.ProcessHorizontals();+ this.m_GhostJoins.length = 0;+ if (!this.ProcessIntersections(topY.v))+ {+ return false;+ }+ this.ProcessEdgesAtTopOfScanbeam(topY.v);+ botY.v = topY.v;+ this.InsertLocalMinimaIntoAEL(botY.v);+ }++ //fix orientations ...+ var outRec, i, ilen;+ //fix orientations ...+ for (i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ outRec = this.m_PolyOuts[i];+ if (outRec.Pts === null || outRec.IsOpen) continue;+ if ((outRec.IsHole ^ this.ReverseSolution) == (this.Area$1(outRec) > 0))+ this.ReversePolyPtLinks(outRec.Pts);+ }++ this.JoinCommonEdges();++ for (i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ outRec = this.m_PolyOuts[i];+ if (outRec.Pts === null)+ continue;+ else if (outRec.IsOpen)+ this.FixupOutPolyline(outRec);+ else+ this.FixupOutPolygon(outRec);+ }++ if (this.StrictlySimple) this.DoSimplePolygons();+ return true;+ }+ //catch { return false; }+ finally+ {+ this.m_Joins.length = 0;+ this.m_GhostJoins.length = 0;+ }+ };++ ClipperLib.Clipper.prototype.DisposeAllPolyPts = function ()+ {+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; ++i)+ this.DisposeOutRec(i);+ ClipperLib.Clear(this.m_PolyOuts);+ };++ ClipperLib.Clipper.prototype.AddJoin = function (Op1, Op2, OffPt)+ {+ var j = new ClipperLib.Join();+ j.OutPt1 = Op1;+ j.OutPt2 = Op2;+ //j.OffPt = OffPt;+ j.OffPt.X = OffPt.X;+ j.OffPt.Y = OffPt.Y;+ if (ClipperLib.use_xyz) j.OffPt.Z = OffPt.Z;+ this.m_Joins.push(j);+ };++ ClipperLib.Clipper.prototype.AddGhostJoin = function (Op, OffPt)+ {+ var j = new ClipperLib.Join();+ j.OutPt1 = Op;+ //j.OffPt = OffPt;+ j.OffPt.X = OffPt.X;+ j.OffPt.Y = OffPt.Y;+ if (ClipperLib.use_xyz) j.OffPt.Z = OffPt.Z;+ this.m_GhostJoins.push(j);+ };++ //if (ClipperLib.use_xyz)+ //{+ ClipperLib.Clipper.prototype.SetZ = function (pt, e1, e2)+ {+ if (this.ZFillFunction !== null)+ {+ if (pt.Z !== 0 || this.ZFillFunction === null) return;+ else if (ClipperLib.IntPoint.op_Equality(pt, e1.Bot)) pt.Z = e1.Bot.Z;+ else if (ClipperLib.IntPoint.op_Equality(pt, e1.Top)) pt.Z = e1.Top.Z;+ else if (ClipperLib.IntPoint.op_Equality(pt, e2.Bot)) pt.Z = e2.Bot.Z;+ else if (ClipperLib.IntPoint.op_Equality(pt, e2.Top)) pt.Z = e2.Top.Z;+ else this.ZFillFunction(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);+ }+ };+ //}++ ClipperLib.Clipper.prototype.InsertLocalMinimaIntoAEL = function (botY)+ {+ var lm = {};++ var lb;+ var rb;+ while (this.PopLocalMinima(botY, lm))+ {+ lb = lm.v.LeftBound;+ rb = lm.v.RightBound;++ var Op1 = null;+ if (lb === null)+ {+ this.InsertEdgeIntoAEL(rb, null);+ this.SetWindingCount(rb);+ if (this.IsContributing(rb))+ Op1 = this.AddOutPt(rb, rb.Bot);+ }+ else if (rb === null)+ {+ this.InsertEdgeIntoAEL(lb, null);+ this.SetWindingCount(lb);+ if (this.IsContributing(lb))+ Op1 = this.AddOutPt(lb, lb.Bot);+ this.InsertScanbeam(lb.Top.Y);+ }+ else+ {+ this.InsertEdgeIntoAEL(lb, null);+ this.InsertEdgeIntoAEL(rb, lb);+ this.SetWindingCount(lb);+ rb.WindCnt = lb.WindCnt;+ rb.WindCnt2 = lb.WindCnt2;+ if (this.IsContributing(lb))+ Op1 = this.AddLocalMinPoly(lb, rb, lb.Bot);+ this.InsertScanbeam(lb.Top.Y);+ }+ if (rb !== null)+ {+ if (ClipperLib.ClipperBase.IsHorizontal(rb))+ {+ if (rb.NextInLML !== null)+ {+ this.InsertScanbeam(rb.NextInLML.Top.Y);+ }+ this.AddEdgeToSEL(rb);+ }+ else+ {+ this.InsertScanbeam(rb.Top.Y);+ }+ }+ if (lb === null || rb === null) continue;+ //if output polygons share an Edge with a horizontal rb, they'll need joining later ...+ if (Op1 !== null && ClipperLib.ClipperBase.IsHorizontal(rb) && this.m_GhostJoins.length > 0 && rb.WindDelta !== 0)+ {+ for (var i = 0, ilen = this.m_GhostJoins.length; i < ilen; i++)+ {+ //if the horizontal Rb and a 'ghost' horizontal overlap, then convert+ //the 'ghost' join to a real join ready for later ...+ var j = this.m_GhostJoins[i];++ if (this.HorzSegmentsOverlap(j.OutPt1.Pt.X, j.OffPt.X, rb.Bot.X, rb.Top.X))+ this.AddJoin(j.OutPt1, Op1, j.OffPt);+ }+ }++ if (lb.OutIdx >= 0 && lb.PrevInAEL !== null &&+ lb.PrevInAEL.Curr.X === lb.Bot.X &&+ lb.PrevInAEL.OutIdx >= 0 &&+ ClipperLib.ClipperBase.SlopesEqual5(lb.PrevInAEL.Curr, lb.PrevInAEL.Top, lb.Curr, lb.Top, this.m_UseFullRange) &&+ lb.WindDelta !== 0 && lb.PrevInAEL.WindDelta !== 0)+ {+ var Op2 = this.AddOutPt(lb.PrevInAEL, lb.Bot);+ this.AddJoin(Op1, Op2, lb.Top);+ }+ if (lb.NextInAEL !== rb)+ {+ if (rb.OutIdx >= 0 && rb.PrevInAEL.OutIdx >= 0 &&+ ClipperLib.ClipperBase.SlopesEqual5(rb.PrevInAEL.Curr, rb.PrevInAEL.Top, rb.Curr, rb.Top, this.m_UseFullRange) &&+ rb.WindDelta !== 0 && rb.PrevInAEL.WindDelta !== 0)+ {+ var Op2 = this.AddOutPt(rb.PrevInAEL, rb.Bot);+ this.AddJoin(Op1, Op2, rb.Top);+ }+ var e = lb.NextInAEL;+ if (e !== null)+ while (e !== rb)+ {+ //nb: For calculating winding counts etc, IntersectEdges() assumes+ //that param1 will be to the right of param2 ABOVE the intersection ...+ this.IntersectEdges(rb, e, lb.Curr);+ //order important here+ e = e.NextInAEL;+ }+ }+ }+ };++ ClipperLib.Clipper.prototype.InsertEdgeIntoAEL = function (edge, startEdge)+ {+ if (this.m_ActiveEdges === null)+ {+ edge.PrevInAEL = null;+ edge.NextInAEL = null;+ this.m_ActiveEdges = edge;+ }+ else if (startEdge === null && this.E2InsertsBeforeE1(this.m_ActiveEdges, edge))+ {+ edge.PrevInAEL = null;+ edge.NextInAEL = this.m_ActiveEdges;+ this.m_ActiveEdges.PrevInAEL = edge;+ this.m_ActiveEdges = edge;+ }+ else+ {+ if (startEdge === null)+ startEdge = this.m_ActiveEdges;+ while (startEdge.NextInAEL !== null && !this.E2InsertsBeforeE1(startEdge.NextInAEL, edge))+ startEdge = startEdge.NextInAEL;+ edge.NextInAEL = startEdge.NextInAEL;+ if (startEdge.NextInAEL !== null)+ startEdge.NextInAEL.PrevInAEL = edge;+ edge.PrevInAEL = startEdge;+ startEdge.NextInAEL = edge;+ }+ };++ ClipperLib.Clipper.prototype.E2InsertsBeforeE1 = function (e1, e2)+ {+ if (e2.Curr.X === e1.Curr.X)+ {+ if (e2.Top.Y > e1.Top.Y)+ return e2.Top.X < ClipperLib.Clipper.TopX(e1, e2.Top.Y);+ else+ return e1.Top.X > ClipperLib.Clipper.TopX(e2, e1.Top.Y);+ }+ else+ return e2.Curr.X < e1.Curr.X;+ };++ ClipperLib.Clipper.prototype.IsEvenOddFillType = function (edge)+ {+ if (edge.PolyTyp === ClipperLib.PolyType.ptSubject)+ return this.m_SubjFillType === ClipperLib.PolyFillType.pftEvenOdd;+ else+ return this.m_ClipFillType === ClipperLib.PolyFillType.pftEvenOdd;+ };++ ClipperLib.Clipper.prototype.IsEvenOddAltFillType = function (edge)+ {+ if (edge.PolyTyp === ClipperLib.PolyType.ptSubject)+ return this.m_ClipFillType === ClipperLib.PolyFillType.pftEvenOdd;+ else+ return this.m_SubjFillType === ClipperLib.PolyFillType.pftEvenOdd;+ };++ ClipperLib.Clipper.prototype.IsContributing = function (edge)+ {+ var pft, pft2;+ if (edge.PolyTyp === ClipperLib.PolyType.ptSubject)+ {+ pft = this.m_SubjFillType;+ pft2 = this.m_ClipFillType;+ }+ else+ {+ pft = this.m_ClipFillType;+ pft2 = this.m_SubjFillType;+ }+ switch (pft)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ if (edge.WindDelta === 0 && edge.WindCnt !== 1)+ return false;+ break;+ case ClipperLib.PolyFillType.pftNonZero:+ if (Math.abs(edge.WindCnt) !== 1)+ return false;+ break;+ case ClipperLib.PolyFillType.pftPositive:+ if (edge.WindCnt !== 1)+ return false;+ break;+ default:+ if (edge.WindCnt !== -1)+ return false;+ break;+ }+ switch (this.m_ClipType)+ {+ case ClipperLib.ClipType.ctIntersection:+ switch (pft2)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ case ClipperLib.PolyFillType.pftNonZero:+ return (edge.WindCnt2 !== 0);+ case ClipperLib.PolyFillType.pftPositive:+ return (edge.WindCnt2 > 0);+ default:+ return (edge.WindCnt2 < 0);+ }+ case ClipperLib.ClipType.ctUnion:+ switch (pft2)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ case ClipperLib.PolyFillType.pftNonZero:+ return (edge.WindCnt2 === 0);+ case ClipperLib.PolyFillType.pftPositive:+ return (edge.WindCnt2 <= 0);+ default:+ return (edge.WindCnt2 >= 0);+ }+ case ClipperLib.ClipType.ctDifference:+ if (edge.PolyTyp === ClipperLib.PolyType.ptSubject)+ switch (pft2)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ case ClipperLib.PolyFillType.pftNonZero:+ return (edge.WindCnt2 === 0);+ case ClipperLib.PolyFillType.pftPositive:+ return (edge.WindCnt2 <= 0);+ default:+ return (edge.WindCnt2 >= 0);+ }+ else+ switch (pft2)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ case ClipperLib.PolyFillType.pftNonZero:+ return (edge.WindCnt2 !== 0);+ case ClipperLib.PolyFillType.pftPositive:+ return (edge.WindCnt2 > 0);+ default:+ return (edge.WindCnt2 < 0);+ }+ case ClipperLib.ClipType.ctXor:+ if (edge.WindDelta === 0)+ switch (pft2)+ {+ case ClipperLib.PolyFillType.pftEvenOdd:+ case ClipperLib.PolyFillType.pftNonZero:+ return (edge.WindCnt2 === 0);+ case ClipperLib.PolyFillType.pftPositive:+ return (edge.WindCnt2 <= 0);+ default:+ return (edge.WindCnt2 >= 0);+ }+ else+ return true;+ }+ return true;+ };++ ClipperLib.Clipper.prototype.SetWindingCount = function (edge)+ {+ var e = edge.PrevInAEL;+ //find the edge of the same polytype that immediately preceeds 'edge' in AEL+ while (e !== null && ((e.PolyTyp !== edge.PolyTyp) || (e.WindDelta === 0)))+ e = e.PrevInAEL;+ if (e === null)+ {+ var pft = (edge.PolyTyp === ClipperLib.PolyType.ptSubject ? this.m_SubjFillType : this.m_ClipFillType);+ if (edge.WindDelta === 0)+ {+ edge.WindCnt = (pft === ClipperLib.PolyFillType.pftNegative ? -1 : 1);+ }+ else+ {+ edge.WindCnt = edge.WindDelta;+ }+ edge.WindCnt2 = 0;+ e = this.m_ActiveEdges;+ //ie get ready to calc WindCnt2+ }+ else if (edge.WindDelta === 0 && this.m_ClipType !== ClipperLib.ClipType.ctUnion)+ {+ edge.WindCnt = 1;+ edge.WindCnt2 = e.WindCnt2;+ e = e.NextInAEL;+ //ie get ready to calc WindCnt2+ }+ else if (this.IsEvenOddFillType(edge))+ {+ //EvenOdd filling ...+ if (edge.WindDelta === 0)+ {+ //are we inside a subj polygon ...+ var Inside = true;+ var e2 = e.PrevInAEL;+ while (e2 !== null)+ {+ if (e2.PolyTyp === e.PolyTyp && e2.WindDelta !== 0)+ Inside = !Inside;+ e2 = e2.PrevInAEL;+ }+ edge.WindCnt = (Inside ? 0 : 1);+ }+ else+ {+ edge.WindCnt = edge.WindDelta;+ }+ edge.WindCnt2 = e.WindCnt2;+ e = e.NextInAEL;+ //ie get ready to calc WindCnt2+ }+ else+ {+ //nonZero, Positive or Negative filling ...+ if (e.WindCnt * e.WindDelta < 0)+ {+ //prev edge is 'decreasing' WindCount (WC) toward zero+ //so we're outside the previous polygon ...+ if (Math.abs(e.WindCnt) > 1)+ {+ //outside prev poly but still inside another.+ //when reversing direction of prev poly use the same WC+ if (e.WindDelta * edge.WindDelta < 0)+ edge.WindCnt = e.WindCnt;+ else+ edge.WindCnt = e.WindCnt + edge.WindDelta;+ }+ else+ edge.WindCnt = (edge.WindDelta === 0 ? 1 : edge.WindDelta);+ }+ else+ {+ //prev edge is 'increasing' WindCount (WC) away from zero+ //so we're inside the previous polygon ...+ if (edge.WindDelta === 0)+ edge.WindCnt = (e.WindCnt < 0 ? e.WindCnt - 1 : e.WindCnt + 1);+ else if (e.WindDelta * edge.WindDelta < 0)+ edge.WindCnt = e.WindCnt;+ else+ edge.WindCnt = e.WindCnt + edge.WindDelta;+ }+ edge.WindCnt2 = e.WindCnt2;+ e = e.NextInAEL;+ //ie get ready to calc WindCnt2+ }+ //update WindCnt2 ...+ if (this.IsEvenOddAltFillType(edge))+ {+ //EvenOdd filling ...+ while (e !== edge)+ {+ if (e.WindDelta !== 0)+ edge.WindCnt2 = (edge.WindCnt2 === 0 ? 1 : 0);+ e = e.NextInAEL;+ }+ }+ else+ {+ //nonZero, Positive or Negative filling ...+ while (e !== edge)+ {+ edge.WindCnt2 += e.WindDelta;+ e = e.NextInAEL;+ }+ }+ };++ ClipperLib.Clipper.prototype.AddEdgeToSEL = function (edge)+ {+ //SEL pointers in PEdge are use to build transient lists of horizontal edges.+ //However, since we don't need to worry about processing order, all additions+ //are made to the front of the list ...+ if (this.m_SortedEdges === null)+ {+ this.m_SortedEdges = edge;+ edge.PrevInSEL = null;+ edge.NextInSEL = null;+ }+ else+ {+ edge.NextInSEL = this.m_SortedEdges;+ edge.PrevInSEL = null;+ this.m_SortedEdges.PrevInSEL = edge;+ this.m_SortedEdges = edge;+ }+ };++ ClipperLib.Clipper.prototype.PopEdgeFromSEL = function (e)+ {+ //Pop edge from front of SEL (ie SEL is a FILO list)+ e.v = this.m_SortedEdges;+ if (e.v === null)+ {+ return false;+ }+ var oldE = e.v;+ this.m_SortedEdges = e.v.NextInSEL;+ if (this.m_SortedEdges !== null)+ {+ this.m_SortedEdges.PrevInSEL = null;+ }+ oldE.NextInSEL = null;+ oldE.PrevInSEL = null;+ return true;+ };++ ClipperLib.Clipper.prototype.CopyAELToSEL = function ()+ {+ var e = this.m_ActiveEdges;+ this.m_SortedEdges = e;+ while (e !== null)+ {+ e.PrevInSEL = e.PrevInAEL;+ e.NextInSEL = e.NextInAEL;+ e = e.NextInAEL;+ }+ };++ ClipperLib.Clipper.prototype.SwapPositionsInSEL = function (edge1, edge2)+ {+ if (edge1.NextInSEL === null && edge1.PrevInSEL === null)+ return;+ if (edge2.NextInSEL === null && edge2.PrevInSEL === null)+ return;+ if (edge1.NextInSEL === edge2)+ {+ var next = edge2.NextInSEL;+ if (next !== null)+ next.PrevInSEL = edge1;+ var prev = edge1.PrevInSEL;+ if (prev !== null)+ prev.NextInSEL = edge2;+ edge2.PrevInSEL = prev;+ edge2.NextInSEL = edge1;+ edge1.PrevInSEL = edge2;+ edge1.NextInSEL = next;+ }+ else if (edge2.NextInSEL === edge1)+ {+ var next = edge1.NextInSEL;+ if (next !== null)+ next.PrevInSEL = edge2;+ var prev = edge2.PrevInSEL;+ if (prev !== null)+ prev.NextInSEL = edge1;+ edge1.PrevInSEL = prev;+ edge1.NextInSEL = edge2;+ edge2.PrevInSEL = edge1;+ edge2.NextInSEL = next;+ }+ else+ {+ var next = edge1.NextInSEL;+ var prev = edge1.PrevInSEL;+ edge1.NextInSEL = edge2.NextInSEL;+ if (edge1.NextInSEL !== null)+ edge1.NextInSEL.PrevInSEL = edge1;+ edge1.PrevInSEL = edge2.PrevInSEL;+ if (edge1.PrevInSEL !== null)+ edge1.PrevInSEL.NextInSEL = edge1;+ edge2.NextInSEL = next;+ if (edge2.NextInSEL !== null)+ edge2.NextInSEL.PrevInSEL = edge2;+ edge2.PrevInSEL = prev;+ if (edge2.PrevInSEL !== null)+ edge2.PrevInSEL.NextInSEL = edge2;+ }+ if (edge1.PrevInSEL === null)+ this.m_SortedEdges = edge1;+ else if (edge2.PrevInSEL === null)+ this.m_SortedEdges = edge2;+ };++ ClipperLib.Clipper.prototype.AddLocalMaxPoly = function (e1, e2, pt)+ {+ this.AddOutPt(e1, pt);+ if (e2.WindDelta === 0) this.AddOutPt(e2, pt);+ if (e1.OutIdx === e2.OutIdx)+ {+ e1.OutIdx = -1;+ e2.OutIdx = -1;+ }+ else if (e1.OutIdx < e2.OutIdx)+ this.AppendPolygon(e1, e2);+ else+ this.AppendPolygon(e2, e1);+ };++ ClipperLib.Clipper.prototype.AddLocalMinPoly = function (e1, e2, pt)+ {+ var result;+ var e, prevE;+ if (ClipperLib.ClipperBase.IsHorizontal(e2) || (e1.Dx > e2.Dx))+ {+ result = this.AddOutPt(e1, pt);+ e2.OutIdx = e1.OutIdx;+ e1.Side = ClipperLib.EdgeSide.esLeft;+ e2.Side = ClipperLib.EdgeSide.esRight;+ e = e1;+ if (e.PrevInAEL === e2)+ prevE = e2.PrevInAEL;+ else+ prevE = e.PrevInAEL;+ }+ else+ {+ result = this.AddOutPt(e2, pt);+ e1.OutIdx = e2.OutIdx;+ e1.Side = ClipperLib.EdgeSide.esRight;+ e2.Side = ClipperLib.EdgeSide.esLeft;+ e = e2;+ if (e.PrevInAEL === e1)+ prevE = e1.PrevInAEL;+ else+ prevE = e.PrevInAEL;+ }++ if (prevE !== null && prevE.OutIdx >= 0 && prevE.Top.Y < pt.Y && e.Top.Y < pt.Y)+ {+ var xPrev = ClipperLib.Clipper.TopX(prevE, pt.Y);+ var xE = ClipperLib.Clipper.TopX(e, pt.Y);+ if ((xPrev === xE) && (e.WindDelta !== 0) && (prevE.WindDelta !== 0) && ClipperLib.ClipperBase.SlopesEqual5(new ClipperLib.IntPoint2(xPrev, pt.Y), prevE.Top, new ClipperLib.IntPoint2(xE, pt.Y), e.Top, this.m_UseFullRange))+ {+ var outPt = this.AddOutPt(prevE, pt);+ this.AddJoin(result, outPt, e.Top);+ }+ }+ return result;+ };++ ClipperLib.Clipper.prototype.AddOutPt = function (e, pt)+ {+ if (e.OutIdx < 0)+ {+ var outRec = this.CreateOutRec();+ outRec.IsOpen = (e.WindDelta === 0);+ var newOp = new ClipperLib.OutPt();+ outRec.Pts = newOp;+ newOp.Idx = outRec.Idx;+ //newOp.Pt = pt;+ newOp.Pt.X = pt.X;+ newOp.Pt.Y = pt.Y;+ if (ClipperLib.use_xyz) newOp.Pt.Z = pt.Z;+ newOp.Next = newOp;+ newOp.Prev = newOp;+ if (!outRec.IsOpen)+ this.SetHoleState(e, outRec);+ e.OutIdx = outRec.Idx;+ //nb: do this after SetZ !+ return newOp;+ }+ else+ {+ var outRec = this.m_PolyOuts[e.OutIdx];+ //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'+ var op = outRec.Pts;+ var ToFront = (e.Side === ClipperLib.EdgeSide.esLeft);+ if (ToFront && ClipperLib.IntPoint.op_Equality(pt, op.Pt))+ return op;+ else if (!ToFront && ClipperLib.IntPoint.op_Equality(pt, op.Prev.Pt))+ return op.Prev;+ var newOp = new ClipperLib.OutPt();+ newOp.Idx = outRec.Idx;+ //newOp.Pt = pt;+ newOp.Pt.X = pt.X;+ newOp.Pt.Y = pt.Y;+ if (ClipperLib.use_xyz) newOp.Pt.Z = pt.Z;+ newOp.Next = op;+ newOp.Prev = op.Prev;+ newOp.Prev.Next = newOp;+ op.Prev = newOp;+ if (ToFront)+ outRec.Pts = newOp;+ return newOp;+ }+ };++ ClipperLib.Clipper.prototype.GetLastOutPt = function (e)+ {+ var outRec = this.m_PolyOuts[e.OutIdx];+ if (e.Side === ClipperLib.EdgeSide.esLeft)+ {+ return outRec.Pts;+ }+ else+ {+ return outRec.Pts.Prev;+ }+ };++ ClipperLib.Clipper.prototype.SwapPoints = function (pt1, pt2)+ {+ var tmp = new ClipperLib.IntPoint1(pt1.Value);+ //pt1.Value = pt2.Value;+ pt1.Value.X = pt2.Value.X;+ pt1.Value.Y = pt2.Value.Y;+ if (ClipperLib.use_xyz) pt1.Value.Z = pt2.Value.Z;+ //pt2.Value = tmp;+ pt2.Value.X = tmp.X;+ pt2.Value.Y = tmp.Y;+ if (ClipperLib.use_xyz) pt2.Value.Z = tmp.Z;+ };++ ClipperLib.Clipper.prototype.HorzSegmentsOverlap = function (seg1a, seg1b, seg2a, seg2b)+ {+ var tmp;+ if (seg1a > seg1b)+ {+ tmp = seg1a;+ seg1a = seg1b;+ seg1b = tmp;+ }+ if (seg2a > seg2b)+ {+ tmp = seg2a;+ seg2a = seg2b;+ seg2b = tmp;+ }+ return (seg1a < seg2b) && (seg2a < seg1b);+ }++ ClipperLib.Clipper.prototype.SetHoleState = function (e, outRec)+ {+ var e2 = e.PrevInAEL;+ var eTmp = null;+ while (e2 !== null)+ {+ if (e2.OutIdx >= 0 && e2.WindDelta !== 0)+ {+ if (eTmp === null)+ eTmp = e2;+ else if (eTmp.OutIdx === e2.OutIdx)+ eTmp = null; //paired+ }+ e2 = e2.PrevInAEL;+ }++ if (eTmp === null)+ {+ outRec.FirstLeft = null;+ outRec.IsHole = false;+ }+ else+ {+ outRec.FirstLeft = this.m_PolyOuts[eTmp.OutIdx];+ outRec.IsHole = !outRec.FirstLeft.IsHole;+ }+ };++ ClipperLib.Clipper.prototype.GetDx = function (pt1, pt2)+ {+ if (pt1.Y === pt2.Y)+ return ClipperLib.ClipperBase.horizontal;+ else+ return (pt2.X - pt1.X) / (pt2.Y - pt1.Y);+ };++ ClipperLib.Clipper.prototype.FirstIsBottomPt = function (btmPt1, btmPt2)+ {+ var p = btmPt1.Prev;+ while ((ClipperLib.IntPoint.op_Equality(p.Pt, btmPt1.Pt)) && (p !== btmPt1))+ p = p.Prev;+ var dx1p = Math.abs(this.GetDx(btmPt1.Pt, p.Pt));+ p = btmPt1.Next;+ while ((ClipperLib.IntPoint.op_Equality(p.Pt, btmPt1.Pt)) && (p !== btmPt1))+ p = p.Next;+ var dx1n = Math.abs(this.GetDx(btmPt1.Pt, p.Pt));+ p = btmPt2.Prev;+ while ((ClipperLib.IntPoint.op_Equality(p.Pt, btmPt2.Pt)) && (p !== btmPt2))+ p = p.Prev;+ var dx2p = Math.abs(this.GetDx(btmPt2.Pt, p.Pt));+ p = btmPt2.Next;+ while ((ClipperLib.IntPoint.op_Equality(p.Pt, btmPt2.Pt)) && (p !== btmPt2))+ p = p.Next;+ var dx2n = Math.abs(this.GetDx(btmPt2.Pt, p.Pt));++ if (Math.max(dx1p, dx1n) === Math.max(dx2p, dx2n) && Math.min(dx1p, dx1n) === Math.min(dx2p, dx2n))+ {+ return this.Area(btmPt1) > 0; //if otherwise identical use orientation+ }+ else+ {+ return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);+ }+ };++ ClipperLib.Clipper.prototype.GetBottomPt = function (pp)+ {+ var dups = null;+ var p = pp.Next;+ while (p !== pp)+ {+ if (p.Pt.Y > pp.Pt.Y)+ {+ pp = p;+ dups = null;+ }+ else if (p.Pt.Y === pp.Pt.Y && p.Pt.X <= pp.Pt.X)+ {+ if (p.Pt.X < pp.Pt.X)+ {+ dups = null;+ pp = p;+ }+ else+ {+ if (p.Next !== pp && p.Prev !== pp)+ dups = p;+ }+ }+ p = p.Next;+ }+ if (dups !== null)+ {+ //there appears to be at least 2 vertices at bottomPt so ...+ while (dups !== p)+ {+ if (!this.FirstIsBottomPt(p, dups))+ pp = dups;+ dups = dups.Next;+ while (ClipperLib.IntPoint.op_Inequality(dups.Pt, pp.Pt))+ dups = dups.Next;+ }+ }+ return pp;+ };++ ClipperLib.Clipper.prototype.GetLowermostRec = function (outRec1, outRec2)+ {+ //work out which polygon fragment has the correct hole state ...+ if (outRec1.BottomPt === null)+ outRec1.BottomPt = this.GetBottomPt(outRec1.Pts);+ if (outRec2.BottomPt === null)+ outRec2.BottomPt = this.GetBottomPt(outRec2.Pts);+ var bPt1 = outRec1.BottomPt;+ var bPt2 = outRec2.BottomPt;+ if (bPt1.Pt.Y > bPt2.Pt.Y)+ return outRec1;+ else if (bPt1.Pt.Y < bPt2.Pt.Y)+ return outRec2;+ else if (bPt1.Pt.X < bPt2.Pt.X)+ return outRec1;+ else if (bPt1.Pt.X > bPt2.Pt.X)+ return outRec2;+ else if (bPt1.Next === bPt1)+ return outRec2;+ else if (bPt2.Next === bPt2)+ return outRec1;+ else if (this.FirstIsBottomPt(bPt1, bPt2))+ return outRec1;+ else+ return outRec2;+ };++ ClipperLib.Clipper.prototype.OutRec1RightOfOutRec2 = function (outRec1, outRec2)+ {+ do {+ outRec1 = outRec1.FirstLeft;+ if (outRec1 === outRec2)+ return true;+ }+ while (outRec1 !== null)+ return false;+ };++ ClipperLib.Clipper.prototype.GetOutRec = function (idx)+ {+ var outrec = this.m_PolyOuts[idx];+ while (outrec !== this.m_PolyOuts[outrec.Idx])+ outrec = this.m_PolyOuts[outrec.Idx];+ return outrec;+ };++ ClipperLib.Clipper.prototype.AppendPolygon = function (e1, e2)+ {+ //get the start and ends of both output polygons ...+ var outRec1 = this.m_PolyOuts[e1.OutIdx];+ var outRec2 = this.m_PolyOuts[e2.OutIdx];+ var holeStateRec;+ if (this.OutRec1RightOfOutRec2(outRec1, outRec2))+ holeStateRec = outRec2;+ else if (this.OutRec1RightOfOutRec2(outRec2, outRec1))+ holeStateRec = outRec1;+ else+ holeStateRec = this.GetLowermostRec(outRec1, outRec2);++ //get the start and ends of both output polygons and+ //join E2 poly onto E1 poly and delete pointers to E2 ...++ var p1_lft = outRec1.Pts;+ var p1_rt = p1_lft.Prev;+ var p2_lft = outRec2.Pts;+ var p2_rt = p2_lft.Prev;+ //join e2 poly onto e1 poly and delete pointers to e2 ...+ if (e1.Side === ClipperLib.EdgeSide.esLeft)+ {+ if (e2.Side === ClipperLib.EdgeSide.esLeft)+ {+ //z y x a b c+ this.ReversePolyPtLinks(p2_lft);+ p2_lft.Next = p1_lft;+ p1_lft.Prev = p2_lft;+ p1_rt.Next = p2_rt;+ p2_rt.Prev = p1_rt;+ outRec1.Pts = p2_rt;+ }+ else+ {+ //x y z a b c+ p2_rt.Next = p1_lft;+ p1_lft.Prev = p2_rt;+ p2_lft.Prev = p1_rt;+ p1_rt.Next = p2_lft;+ outRec1.Pts = p2_lft;+ }+ }+ else+ {+ if (e2.Side === ClipperLib.EdgeSide.esRight)+ {+ //a b c z y x+ this.ReversePolyPtLinks(p2_lft);+ p1_rt.Next = p2_rt;+ p2_rt.Prev = p1_rt;+ p2_lft.Next = p1_lft;+ p1_lft.Prev = p2_lft;+ }+ else+ {+ //a b c x y z+ p1_rt.Next = p2_lft;+ p2_lft.Prev = p1_rt;+ p1_lft.Prev = p2_rt;+ p2_rt.Next = p1_lft;+ }+ }+ outRec1.BottomPt = null;+ if (holeStateRec === outRec2)+ {+ if (outRec2.FirstLeft !== outRec1)+ outRec1.FirstLeft = outRec2.FirstLeft;+ outRec1.IsHole = outRec2.IsHole;+ }+ outRec2.Pts = null;+ outRec2.BottomPt = null;+ outRec2.FirstLeft = outRec1;+ var OKIdx = e1.OutIdx;+ var ObsoleteIdx = e2.OutIdx;+ e1.OutIdx = -1;+ //nb: safe because we only get here via AddLocalMaxPoly+ e2.OutIdx = -1;+ var e = this.m_ActiveEdges;+ while (e !== null)+ {+ if (e.OutIdx === ObsoleteIdx)+ {+ e.OutIdx = OKIdx;+ e.Side = e1.Side;+ break;+ }+ e = e.NextInAEL;+ }+ outRec2.Idx = outRec1.Idx;+ };++ ClipperLib.Clipper.prototype.ReversePolyPtLinks = function (pp)+ {+ if (pp === null)+ return;+ var pp1;+ var pp2;+ pp1 = pp;+ do {+ pp2 = pp1.Next;+ pp1.Next = pp1.Prev;+ pp1.Prev = pp2;+ pp1 = pp2;+ }+ while (pp1 !== pp)+ };++ ClipperLib.Clipper.SwapSides = function (edge1, edge2)+ {+ var side = edge1.Side;+ edge1.Side = edge2.Side;+ edge2.Side = side;+ };++ ClipperLib.Clipper.SwapPolyIndexes = function (edge1, edge2)+ {+ var outIdx = edge1.OutIdx;+ edge1.OutIdx = edge2.OutIdx;+ edge2.OutIdx = outIdx;+ };++ ClipperLib.Clipper.prototype.IntersectEdges = function (e1, e2, pt)+ {+ //e1 will be to the left of e2 BELOW the intersection. Therefore e1 is before+ //e2 in AEL except when e1 is being inserted at the intersection point ...+ var e1Contributing = (e1.OutIdx >= 0);+ var e2Contributing = (e2.OutIdx >= 0);++ if (ClipperLib.use_xyz)+ this.SetZ(pt, e1, e2);++ if (ClipperLib.use_lines)+ {+ //if either edge is on an OPEN path ...+ if (e1.WindDelta === 0 || e2.WindDelta === 0)+ {+ //ignore subject-subject open path intersections UNLESS they+ //are both open paths, AND they are both 'contributing maximas' ...+ if (e1.WindDelta === 0 && e2.WindDelta === 0) return;+ //if intersecting a subj line with a subj poly ...+ else if (e1.PolyTyp === e2.PolyTyp &&+ e1.WindDelta !== e2.WindDelta && this.m_ClipType === ClipperLib.ClipType.ctUnion)+ {+ if (e1.WindDelta === 0)+ {+ if (e2Contributing)+ {+ this.AddOutPt(e1, pt);+ if (e1Contributing)+ e1.OutIdx = -1;+ }+ }+ else+ {+ if (e1Contributing)+ {+ this.AddOutPt(e2, pt);+ if (e2Contributing)+ e2.OutIdx = -1;+ }+ }+ }+ else if (e1.PolyTyp !== e2.PolyTyp)+ {+ if ((e1.WindDelta === 0) && Math.abs(e2.WindCnt) === 1 &&+ (this.m_ClipType !== ClipperLib.ClipType.ctUnion || e2.WindCnt2 === 0))+ {+ this.AddOutPt(e1, pt);+ if (e1Contributing)+ e1.OutIdx = -1;+ }+ else if ((e2.WindDelta === 0) && (Math.abs(e1.WindCnt) === 1) &&+ (this.m_ClipType !== ClipperLib.ClipType.ctUnion || e1.WindCnt2 === 0))+ {+ this.AddOutPt(e2, pt);+ if (e2Contributing)+ e2.OutIdx = -1;+ }+ }+ return;+ }+ }+ //update winding counts...+ //assumes that e1 will be to the Right of e2 ABOVE the intersection+ if (e1.PolyTyp === e2.PolyTyp)+ {+ if (this.IsEvenOddFillType(e1))+ {+ var oldE1WindCnt = e1.WindCnt;+ e1.WindCnt = e2.WindCnt;+ e2.WindCnt = oldE1WindCnt;+ }+ else+ {+ if (e1.WindCnt + e2.WindDelta === 0)+ e1.WindCnt = -e1.WindCnt;+ else+ e1.WindCnt += e2.WindDelta;+ if (e2.WindCnt - e1.WindDelta === 0)+ e2.WindCnt = -e2.WindCnt;+ else+ e2.WindCnt -= e1.WindDelta;+ }+ }+ else+ {+ if (!this.IsEvenOddFillType(e2))+ e1.WindCnt2 += e2.WindDelta;+ else+ e1.WindCnt2 = (e1.WindCnt2 === 0) ? 1 : 0;+ if (!this.IsEvenOddFillType(e1))+ e2.WindCnt2 -= e1.WindDelta;+ else+ e2.WindCnt2 = (e2.WindCnt2 === 0) ? 1 : 0;+ }+ var e1FillType, e2FillType, e1FillType2, e2FillType2;+ if (e1.PolyTyp === ClipperLib.PolyType.ptSubject)+ {+ e1FillType = this.m_SubjFillType;+ e1FillType2 = this.m_ClipFillType;+ }+ else+ {+ e1FillType = this.m_ClipFillType;+ e1FillType2 = this.m_SubjFillType;+ }+ if (e2.PolyTyp === ClipperLib.PolyType.ptSubject)+ {+ e2FillType = this.m_SubjFillType;+ e2FillType2 = this.m_ClipFillType;+ }+ else+ {+ e2FillType = this.m_ClipFillType;+ e2FillType2 = this.m_SubjFillType;+ }+ var e1Wc, e2Wc;+ switch (e1FillType)+ {+ case ClipperLib.PolyFillType.pftPositive:+ e1Wc = e1.WindCnt;+ break;+ case ClipperLib.PolyFillType.pftNegative:+ e1Wc = -e1.WindCnt;+ break;+ default:+ e1Wc = Math.abs(e1.WindCnt);+ break;+ }+ switch (e2FillType)+ {+ case ClipperLib.PolyFillType.pftPositive:+ e2Wc = e2.WindCnt;+ break;+ case ClipperLib.PolyFillType.pftNegative:+ e2Wc = -e2.WindCnt;+ break;+ default:+ e2Wc = Math.abs(e2.WindCnt);+ break;+ }+ if (e1Contributing && e2Contributing)+ {+ if ((e1Wc !== 0 && e1Wc !== 1) || (e2Wc !== 0 && e2Wc !== 1) ||+ (e1.PolyTyp !== e2.PolyTyp && this.m_ClipType !== ClipperLib.ClipType.ctXor))+ {+ this.AddLocalMaxPoly(e1, e2, pt);+ }+ else+ {+ this.AddOutPt(e1, pt);+ this.AddOutPt(e2, pt);+ ClipperLib.Clipper.SwapSides(e1, e2);+ ClipperLib.Clipper.SwapPolyIndexes(e1, e2);+ }+ }+ else if (e1Contributing)+ {+ if (e2Wc === 0 || e2Wc === 1)+ {+ this.AddOutPt(e1, pt);+ ClipperLib.Clipper.SwapSides(e1, e2);+ ClipperLib.Clipper.SwapPolyIndexes(e1, e2);+ }+ }+ else if (e2Contributing)+ {+ if (e1Wc === 0 || e1Wc === 1)+ {+ this.AddOutPt(e2, pt);+ ClipperLib.Clipper.SwapSides(e1, e2);+ ClipperLib.Clipper.SwapPolyIndexes(e1, e2);+ }+ }+ else if ((e1Wc === 0 || e1Wc === 1) && (e2Wc === 0 || e2Wc === 1))+ {+ //neither edge is currently contributing ...+ var e1Wc2, e2Wc2;+ switch (e1FillType2)+ {+ case ClipperLib.PolyFillType.pftPositive:+ e1Wc2 = e1.WindCnt2;+ break;+ case ClipperLib.PolyFillType.pftNegative:+ e1Wc2 = -e1.WindCnt2;+ break;+ default:+ e1Wc2 = Math.abs(e1.WindCnt2);+ break;+ }+ switch (e2FillType2)+ {+ case ClipperLib.PolyFillType.pftPositive:+ e2Wc2 = e2.WindCnt2;+ break;+ case ClipperLib.PolyFillType.pftNegative:+ e2Wc2 = -e2.WindCnt2;+ break;+ default:+ e2Wc2 = Math.abs(e2.WindCnt2);+ break;+ }+ if (e1.PolyTyp !== e2.PolyTyp)+ {+ this.AddLocalMinPoly(e1, e2, pt);+ }+ else if (e1Wc === 1 && e2Wc === 1)+ switch (this.m_ClipType)+ {+ case ClipperLib.ClipType.ctIntersection:+ if (e1Wc2 > 0 && e2Wc2 > 0)+ this.AddLocalMinPoly(e1, e2, pt);+ break;+ case ClipperLib.ClipType.ctUnion:+ if (e1Wc2 <= 0 && e2Wc2 <= 0)+ this.AddLocalMinPoly(e1, e2, pt);+ break;+ case ClipperLib.ClipType.ctDifference:+ if (((e1.PolyTyp === ClipperLib.PolyType.ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||+ ((e1.PolyTyp === ClipperLib.PolyType.ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))+ this.AddLocalMinPoly(e1, e2, pt);+ break;+ case ClipperLib.ClipType.ctXor:+ this.AddLocalMinPoly(e1, e2, pt);+ break;+ }+ else+ ClipperLib.Clipper.SwapSides(e1, e2);+ }+ };++ ClipperLib.Clipper.prototype.DeleteFromSEL = function (e)+ {+ var SelPrev = e.PrevInSEL;+ var SelNext = e.NextInSEL;+ if (SelPrev === null && SelNext === null && (e !== this.m_SortedEdges))+ return;+ //already deleted+ if (SelPrev !== null)+ SelPrev.NextInSEL = SelNext;+ else+ this.m_SortedEdges = SelNext;+ if (SelNext !== null)+ SelNext.PrevInSEL = SelPrev;+ e.NextInSEL = null;+ e.PrevInSEL = null;+ };++ ClipperLib.Clipper.prototype.ProcessHorizontals = function ()+ {+ var horzEdge = {}; //m_SortedEdges;+ while (this.PopEdgeFromSEL(horzEdge))+ {+ this.ProcessHorizontal(horzEdge.v);+ }+ };++ ClipperLib.Clipper.prototype.GetHorzDirection = function (HorzEdge, $var)+ {+ if (HorzEdge.Bot.X < HorzEdge.Top.X)+ {+ $var.Left = HorzEdge.Bot.X;+ $var.Right = HorzEdge.Top.X;+ $var.Dir = ClipperLib.Direction.dLeftToRight;+ }+ else+ {+ $var.Left = HorzEdge.Top.X;+ $var.Right = HorzEdge.Bot.X;+ $var.Dir = ClipperLib.Direction.dRightToLeft;+ }+ };++ ClipperLib.Clipper.prototype.ProcessHorizontal = function (horzEdge)+ {+ var $var = {+ Dir: null,+ Left: null,+ Right: null+ };++ this.GetHorzDirection(horzEdge, $var);+ var dir = $var.Dir;+ var horzLeft = $var.Left;+ var horzRight = $var.Right;++ var IsOpen = horzEdge.WindDelta === 0;++ var eLastHorz = horzEdge,+ eMaxPair = null;+ while (eLastHorz.NextInLML !== null && ClipperLib.ClipperBase.IsHorizontal(eLastHorz.NextInLML))+ eLastHorz = eLastHorz.NextInLML;+ if (eLastHorz.NextInLML === null)+ eMaxPair = this.GetMaximaPair(eLastHorz);++ var currMax = this.m_Maxima;+ if (currMax !== null)+ {+ //get the first maxima in range (X) ...+ if (dir === ClipperLib.Direction.dLeftToRight)+ {+ while (currMax !== null && currMax.X <= horzEdge.Bot.X)+ {+ currMax = currMax.Next;+ }+ if (currMax !== null && currMax.X >= eLastHorz.Top.X)+ {+ currMax = null;+ }+ }+ else+ {+ while (currMax.Next !== null && currMax.Next.X < horzEdge.Bot.X)+ {+ currMax = currMax.Next;+ }+ if (currMax.X <= eLastHorz.Top.X)+ {+ currMax = null;+ }+ }+ }+ var op1 = null;+ for (;;) //loop through consec. horizontal edges+ {+ var IsLastHorz = (horzEdge === eLastHorz);+ var e = this.GetNextInAEL(horzEdge, dir);+ while (e !== null)+ {+ //this code block inserts extra coords into horizontal edges (in output+ //polygons) whereever maxima touch these horizontal edges. This helps+ //'simplifying' polygons (ie if the Simplify property is set).+ if (currMax !== null)+ {+ if (dir === ClipperLib.Direction.dLeftToRight)+ {+ while (currMax !== null && currMax.X < e.Curr.X)+ {+ if (horzEdge.OutIdx >= 0 && !IsOpen)+ {+ this.AddOutPt(horzEdge, new ClipperLib.IntPoint2(currMax.X, horzEdge.Bot.Y));+ }+ currMax = currMax.Next;+ }+ }+ else+ {+ while (currMax !== null && currMax.X > e.Curr.X)+ {+ if (horzEdge.OutIdx >= 0 && !IsOpen)+ {+ this.AddOutPt(horzEdge, new ClipperLib.IntPoint2(currMax.X, horzEdge.Bot.Y));+ }+ currMax = currMax.Prev;+ }+ }+ }++ if ((dir === ClipperLib.Direction.dLeftToRight && e.Curr.X > horzRight) || (dir === ClipperLib.Direction.dRightToLeft && e.Curr.X < horzLeft))+ {+ break;+ }++ //Also break if we've got to the end of an intermediate horizontal edge ...+ //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.+ if (e.Curr.X === horzEdge.Top.X && horzEdge.NextInLML !== null && e.Dx < horzEdge.NextInLML.Dx)+ break;++ if (horzEdge.OutIdx >= 0 && !IsOpen) //note: may be done multiple times+ {+ if (ClipperLib.use_xyz)+ {+ if (dir === ClipperLib.Direction.dLeftToRight)+ this.SetZ(e.Curr, horzEdge, e);+ else this.SetZ(e.Curr, e, horzEdge);+ }++ op1 = this.AddOutPt(horzEdge, e.Curr);+ var eNextHorz = this.m_SortedEdges;+ while (eNextHorz !== null)+ {+ if (eNextHorz.OutIdx >= 0 && this.HorzSegmentsOverlap(horzEdge.Bot.X, horzEdge.Top.X, eNextHorz.Bot.X, eNextHorz.Top.X))+ {+ var op2 = this.GetLastOutPt(eNextHorz);+ this.AddJoin(op2, op1, eNextHorz.Top);+ }+ eNextHorz = eNextHorz.NextInSEL;+ }+ this.AddGhostJoin(op1, horzEdge.Bot);+ }++ //OK, so far we're still in range of the horizontal Edge but make sure+ //we're at the last of consec. horizontals when matching with eMaxPair+ if (e === eMaxPair && IsLastHorz)+ {+ if (horzEdge.OutIdx >= 0)+ {+ this.AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge.Top);+ }+ this.DeleteFromAEL(horzEdge);+ this.DeleteFromAEL(eMaxPair);+ return;+ }++ if (dir === ClipperLib.Direction.dLeftToRight)+ {+ var Pt = new ClipperLib.IntPoint2(e.Curr.X, horzEdge.Curr.Y);+ this.IntersectEdges(horzEdge, e, Pt);+ }+ else+ {+ var Pt = new ClipperLib.IntPoint2(e.Curr.X, horzEdge.Curr.Y);+ this.IntersectEdges(e, horzEdge, Pt);+ }+ var eNext = this.GetNextInAEL(e, dir);+ this.SwapPositionsInAEL(horzEdge, e);+ e = eNext;+ } //end while(e !== null)++ //Break out of loop if HorzEdge.NextInLML is not also horizontal ...+ if (horzEdge.NextInLML === null || !ClipperLib.ClipperBase.IsHorizontal(horzEdge.NextInLML))+ {+ break;+ }++ horzEdge = this.UpdateEdgeIntoAEL(horzEdge);+ if (horzEdge.OutIdx >= 0)+ {+ this.AddOutPt(horzEdge, horzEdge.Bot);+ }++ $var = {+ Dir: dir,+ Left: horzLeft,+ Right: horzRight+ };++ this.GetHorzDirection(horzEdge, $var);+ dir = $var.Dir;+ horzLeft = $var.Left;+ horzRight = $var.Right;++ } //end for (;;)++ if (horzEdge.OutIdx >= 0 && op1 === null)+ {+ op1 = this.GetLastOutPt(horzEdge);+ var eNextHorz = this.m_SortedEdges;+ while (eNextHorz !== null)+ {+ if (eNextHorz.OutIdx >= 0 && this.HorzSegmentsOverlap(horzEdge.Bot.X, horzEdge.Top.X, eNextHorz.Bot.X, eNextHorz.Top.X))+ {+ var op2 = this.GetLastOutPt(eNextHorz);+ this.AddJoin(op2, op1, eNextHorz.Top);+ }+ eNextHorz = eNextHorz.NextInSEL;+ }+ this.AddGhostJoin(op1, horzEdge.Top);+ }++ if (horzEdge.NextInLML !== null)+ {+ if (horzEdge.OutIdx >= 0)+ {+ op1 = this.AddOutPt(horzEdge, horzEdge.Top);++ horzEdge = this.UpdateEdgeIntoAEL(horzEdge);+ if (horzEdge.WindDelta === 0)+ {+ return;+ }+ //nb: HorzEdge is no longer horizontal here+ var ePrev = horzEdge.PrevInAEL;+ var eNext = horzEdge.NextInAEL;+ if (ePrev !== null && ePrev.Curr.X === horzEdge.Bot.X && ePrev.Curr.Y === horzEdge.Bot.Y && ePrev.WindDelta === 0 && (ePrev.OutIdx >= 0 && ePrev.Curr.Y > ePrev.Top.Y && ClipperLib.ClipperBase.SlopesEqual3(horzEdge, ePrev, this.m_UseFullRange)))+ {+ var op2 = this.AddOutPt(ePrev, horzEdge.Bot);+ this.AddJoin(op1, op2, horzEdge.Top);+ }+ else if (eNext !== null && eNext.Curr.X === horzEdge.Bot.X && eNext.Curr.Y === horzEdge.Bot.Y && eNext.WindDelta !== 0 && eNext.OutIdx >= 0 && eNext.Curr.Y > eNext.Top.Y && ClipperLib.ClipperBase.SlopesEqual3(horzEdge, eNext, this.m_UseFullRange))+ {+ var op2 = this.AddOutPt(eNext, horzEdge.Bot);+ this.AddJoin(op1, op2, horzEdge.Top);+ }+ }+ else+ {+ horzEdge = this.UpdateEdgeIntoAEL(horzEdge);+ }+ }+ else+ {+ if (horzEdge.OutIdx >= 0)+ {+ this.AddOutPt(horzEdge, horzEdge.Top);+ }+ this.DeleteFromAEL(horzEdge);+ }+ };++ ClipperLib.Clipper.prototype.GetNextInAEL = function (e, Direction)+ {+ return Direction === ClipperLib.Direction.dLeftToRight ? e.NextInAEL : e.PrevInAEL;+ };++ ClipperLib.Clipper.prototype.IsMinima = function (e)+ {+ return e !== null && (e.Prev.NextInLML !== e) && (e.Next.NextInLML !== e);+ };++ ClipperLib.Clipper.prototype.IsMaxima = function (e, Y)+ {+ return (e !== null && e.Top.Y === Y && e.NextInLML === null);+ };++ ClipperLib.Clipper.prototype.IsIntermediate = function (e, Y)+ {+ return (e.Top.Y === Y && e.NextInLML !== null);+ };++ ClipperLib.Clipper.prototype.GetMaximaPair = function (e)+ {+ if ((ClipperLib.IntPoint.op_Equality(e.Next.Top, e.Top)) && e.Next.NextInLML === null)+ {+ return e.Next;+ }+ else+ {+ if ((ClipperLib.IntPoint.op_Equality(e.Prev.Top, e.Top)) && e.Prev.NextInLML === null)+ {+ return e.Prev;+ }+ else+ {+ return null;+ }+ }+ };++ ClipperLib.Clipper.prototype.GetMaximaPairEx = function (e)+ {+ //as above but returns null if MaxPair isn't in AEL (unless it's horizontal)+ var result = this.GetMaximaPair(e);+ if (result === null || result.OutIdx === ClipperLib.ClipperBase.Skip ||+ ((result.NextInAEL === result.PrevInAEL) && !ClipperLib.ClipperBase.IsHorizontal(result)))+ {+ return null;+ }+ return result;+ };++ ClipperLib.Clipper.prototype.ProcessIntersections = function (topY)+ {+ if (this.m_ActiveEdges === null)+ return true;+ try+ {+ this.BuildIntersectList(topY);+ if (this.m_IntersectList.length === 0)+ return true;+ if (this.m_IntersectList.length === 1 || this.FixupIntersectionOrder())+ this.ProcessIntersectList();+ else+ return false;+ }+ catch ($$e2)+ {+ this.m_SortedEdges = null;+ this.m_IntersectList.length = 0;+ ClipperLib.Error("ProcessIntersections error");+ }+ this.m_SortedEdges = null;+ return true;+ };++ ClipperLib.Clipper.prototype.BuildIntersectList = function (topY)+ {+ if (this.m_ActiveEdges === null)+ return;+ //prepare for sorting ...+ var e = this.m_ActiveEdges;+ //console.log(JSON.stringify(JSON.decycle( e )));+ this.m_SortedEdges = e;+ while (e !== null)+ {+ e.PrevInSEL = e.PrevInAEL;+ e.NextInSEL = e.NextInAEL;+ e.Curr.X = ClipperLib.Clipper.TopX(e, topY);+ e = e.NextInAEL;+ }+ //bubblesort ...+ var isModified = true;+ while (isModified && this.m_SortedEdges !== null)+ {+ isModified = false;+ e = this.m_SortedEdges;+ while (e.NextInSEL !== null)+ {+ var eNext = e.NextInSEL;+ var pt = new ClipperLib.IntPoint0();+ //console.log("e.Curr.X: " + e.Curr.X + " eNext.Curr.X" + eNext.Curr.X);+ if (e.Curr.X > eNext.Curr.X)+ {+ this.IntersectPoint(e, eNext, pt);+ if (pt.Y < topY)+ {+ pt = new ClipperLib.IntPoint2(ClipperLib.Clipper.TopX(e, topY), topY);+ }+ var newNode = new ClipperLib.IntersectNode();+ newNode.Edge1 = e;+ newNode.Edge2 = eNext;+ //newNode.Pt = pt;+ newNode.Pt.X = pt.X;+ newNode.Pt.Y = pt.Y;+ if (ClipperLib.use_xyz) newNode.Pt.Z = pt.Z;+ this.m_IntersectList.push(newNode);+ this.SwapPositionsInSEL(e, eNext);+ isModified = true;+ }+ else+ e = eNext;+ }+ if (e.PrevInSEL !== null)+ e.PrevInSEL.NextInSEL = null;+ else+ break;+ }+ this.m_SortedEdges = null;+ };++ ClipperLib.Clipper.prototype.EdgesAdjacent = function (inode)+ {+ return (inode.Edge1.NextInSEL === inode.Edge2) || (inode.Edge1.PrevInSEL === inode.Edge2);+ };++ ClipperLib.Clipper.IntersectNodeSort = function (node1, node2)+ {+ //the following typecast is safe because the differences in Pt.Y will+ //be limited to the height of the scanbeam.+ return (node2.Pt.Y - node1.Pt.Y);+ };++ ClipperLib.Clipper.prototype.FixupIntersectionOrder = function ()+ {+ //pre-condition: intersections are sorted bottom-most first.+ //Now it's crucial that intersections are made only between adjacent edges,+ //so to ensure this the order of intersections may need adjusting ...+ this.m_IntersectList.sort(this.m_IntersectNodeComparer);+ this.CopyAELToSEL();+ var cnt = this.m_IntersectList.length;+ for (var i = 0; i < cnt; i++)+ {+ if (!this.EdgesAdjacent(this.m_IntersectList[i]))+ {+ var j = i + 1;+ while (j < cnt && !this.EdgesAdjacent(this.m_IntersectList[j]))+ j++;+ if (j === cnt)+ return false;+ var tmp = this.m_IntersectList[i];+ this.m_IntersectList[i] = this.m_IntersectList[j];+ this.m_IntersectList[j] = tmp;+ }+ this.SwapPositionsInSEL(this.m_IntersectList[i].Edge1, this.m_IntersectList[i].Edge2);+ }+ return true;+ };++ ClipperLib.Clipper.prototype.ProcessIntersectList = function ()+ {+ for (var i = 0, ilen = this.m_IntersectList.length; i < ilen; i++)+ {+ var iNode = this.m_IntersectList[i];+ this.IntersectEdges(iNode.Edge1, iNode.Edge2, iNode.Pt);+ this.SwapPositionsInAEL(iNode.Edge1, iNode.Edge2);+ }+ this.m_IntersectList.length = 0;+ };++ /*+ --------------------------------+ Round speedtest: http://jsperf.com/fastest-round+ --------------------------------+ */+ var R1 = function (a)+ {+ return a < 0 ? Math.ceil(a - 0.5) : Math.round(a)+ };++ var R2 = function (a)+ {+ return a < 0 ? Math.ceil(a - 0.5) : Math.floor(a + 0.5)+ };++ var R3 = function (a)+ {+ return a < 0 ? -Math.round(Math.abs(a)) : Math.round(a)+ };++ var R4 = function (a)+ {+ if (a < 0)+ {+ a -= 0.5;+ return a < -2147483648 ? Math.ceil(a) : a | 0;+ }+ else+ {+ a += 0.5;+ return a > 2147483647 ? Math.floor(a) : a | 0;+ }+ };++ if (browser.msie) ClipperLib.Clipper.Round = R1;+ else if (browser.chromium) ClipperLib.Clipper.Round = R3;+ else if (browser.safari) ClipperLib.Clipper.Round = R4;+ else ClipperLib.Clipper.Round = R2; // eg. browser.chrome || browser.firefox || browser.opera+ ClipperLib.Clipper.TopX = function (edge, currentY)+ {+ //if (edge.Bot == edge.Curr) alert ("edge.Bot = edge.Curr");+ //if (edge.Bot == edge.Top) alert ("edge.Bot = edge.Top");+ if (currentY === edge.Top.Y)+ return edge.Top.X;+ return edge.Bot.X + ClipperLib.Clipper.Round(edge.Dx * (currentY - edge.Bot.Y));+ };++ ClipperLib.Clipper.prototype.IntersectPoint = function (edge1, edge2, ip)+ {+ ip.X = 0;+ ip.Y = 0;+ var b1, b2;+ //nb: with very large coordinate values, it's possible for SlopesEqual() to+ //return false but for the edge.Dx value be equal due to double precision rounding.+ if (edge1.Dx === edge2.Dx)+ {+ ip.Y = edge1.Curr.Y;+ ip.X = ClipperLib.Clipper.TopX(edge1, ip.Y);+ return;+ }+ if (edge1.Delta.X === 0)+ {+ ip.X = edge1.Bot.X;+ if (ClipperLib.ClipperBase.IsHorizontal(edge2))+ {+ ip.Y = edge2.Bot.Y;+ }+ else+ {+ b2 = edge2.Bot.Y - (edge2.Bot.X / edge2.Dx);+ ip.Y = ClipperLib.Clipper.Round(ip.X / edge2.Dx + b2);+ }+ }+ else if (edge2.Delta.X === 0)+ {+ ip.X = edge2.Bot.X;+ if (ClipperLib.ClipperBase.IsHorizontal(edge1))+ {+ ip.Y = edge1.Bot.Y;+ }+ else+ {+ b1 = edge1.Bot.Y - (edge1.Bot.X / edge1.Dx);+ ip.Y = ClipperLib.Clipper.Round(ip.X / edge1.Dx + b1);+ }+ }+ else+ {+ b1 = edge1.Bot.X - edge1.Bot.Y * edge1.Dx;+ b2 = edge2.Bot.X - edge2.Bot.Y * edge2.Dx;+ var q = (b2 - b1) / (edge1.Dx - edge2.Dx);+ ip.Y = ClipperLib.Clipper.Round(q);+ if (Math.abs(edge1.Dx) < Math.abs(edge2.Dx))+ ip.X = ClipperLib.Clipper.Round(edge1.Dx * q + b1);+ else+ ip.X = ClipperLib.Clipper.Round(edge2.Dx * q + b2);+ }+ if (ip.Y < edge1.Top.Y || ip.Y < edge2.Top.Y)+ {+ if (edge1.Top.Y > edge2.Top.Y)+ {+ ip.Y = edge1.Top.Y;+ ip.X = ClipperLib.Clipper.TopX(edge2, edge1.Top.Y);+ return ip.X < edge1.Top.X;+ }+ else+ ip.Y = edge2.Top.Y;+ if (Math.abs(edge1.Dx) < Math.abs(edge2.Dx))+ ip.X = ClipperLib.Clipper.TopX(edge1, ip.Y);+ else+ ip.X = ClipperLib.Clipper.TopX(edge2, ip.Y);+ }+ //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...+ if (ip.Y > edge1.Curr.Y)+ {+ ip.Y = edge1.Curr.Y;+ //better to use the more vertical edge to derive X ...+ if (Math.abs(edge1.Dx) > Math.abs(edge2.Dx))+ ip.X = ClipperLib.Clipper.TopX(edge2, ip.Y);+ else+ ip.X = ClipperLib.Clipper.TopX(edge1, ip.Y);+ }+ };++ ClipperLib.Clipper.prototype.ProcessEdgesAtTopOfScanbeam = function (topY)+ {+ var e = this.m_ActiveEdges;++ while (e !== null)+ {+ //1. process maxima, treating them as if they're 'bent' horizontal edges,+ // but exclude maxima with horizontal edges. nb: e can't be a horizontal.+ var IsMaximaEdge = this.IsMaxima(e, topY);+ if (IsMaximaEdge)+ {+ var eMaxPair = this.GetMaximaPairEx(e);+ IsMaximaEdge = (eMaxPair === null || !ClipperLib.ClipperBase.IsHorizontal(eMaxPair));+ }+ if (IsMaximaEdge)+ {+ if (this.StrictlySimple)+ {+ this.InsertMaxima(e.Top.X);+ }+ var ePrev = e.PrevInAEL;+ this.DoMaxima(e);+ if (ePrev === null)+ e = this.m_ActiveEdges;+ else+ e = ePrev.NextInAEL;+ }+ else+ {+ //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...+ if (this.IsIntermediate(e, topY) && ClipperLib.ClipperBase.IsHorizontal(e.NextInLML))+ {+ e = this.UpdateEdgeIntoAEL(e);+ if (e.OutIdx >= 0)+ this.AddOutPt(e, e.Bot);+ this.AddEdgeToSEL(e);+ }+ else+ {+ e.Curr.X = ClipperLib.Clipper.TopX(e, topY);+ e.Curr.Y = topY;+ }++ if (ClipperLib.use_xyz)+ {+ if (e.Top.Y === topY) e.Curr.Z = e.Top.Z;+ else if (e.Bot.Y === topY) e.Curr.Z = e.Bot.Z;+ else e.Curr.Z = 0;+ }++ //When StrictlySimple and 'e' is being touched by another edge, then+ //make sure both edges have a vertex here ...+ if (this.StrictlySimple)+ {+ var ePrev = e.PrevInAEL;+ if ((e.OutIdx >= 0) && (e.WindDelta !== 0) && ePrev !== null &&+ (ePrev.OutIdx >= 0) && (ePrev.Curr.X === e.Curr.X) &&+ (ePrev.WindDelta !== 0))+ {+ var ip = new ClipperLib.IntPoint1(e.Curr);++ if (ClipperLib.use_xyz)+ {+ this.SetZ(ip, ePrev, e);+ }++ var op = this.AddOutPt(ePrev, ip);+ var op2 = this.AddOutPt(e, ip);+ this.AddJoin(op, op2, ip); //StrictlySimple (type-3) join+ }+ }+ e = e.NextInAEL;+ }+ }+ //3. Process horizontals at the Top of the scanbeam ...+ this.ProcessHorizontals();+ this.m_Maxima = null;+ //4. Promote intermediate vertices ...+ e = this.m_ActiveEdges;+ while (e !== null)+ {+ if (this.IsIntermediate(e, topY))+ {+ var op = null;+ if (e.OutIdx >= 0)+ op = this.AddOutPt(e, e.Top);+ e = this.UpdateEdgeIntoAEL(e);+ //if output polygons share an edge, they'll need joining later ...+ var ePrev = e.PrevInAEL;+ var eNext = e.NextInAEL;++ if (ePrev !== null && ePrev.Curr.X === e.Bot.X && ePrev.Curr.Y === e.Bot.Y && op !== null && ePrev.OutIdx >= 0 && ePrev.Curr.Y === ePrev.Top.Y && ClipperLib.ClipperBase.SlopesEqual5(e.Curr, e.Top, ePrev.Curr, ePrev.Top, this.m_UseFullRange) && (e.WindDelta !== 0) && (ePrev.WindDelta !== 0))+ {+ var op2 = this.AddOutPt(ePrev2, e.Bot);+ this.AddJoin(op, op2, e.Top);+ }+ else if (eNext !== null && eNext.Curr.X === e.Bot.X && eNext.Curr.Y === e.Bot.Y && op !== null && eNext.OutIdx >= 0 && eNext.Curr.Y === eNext.Top.Y && ClipperLib.ClipperBase.SlopesEqual5(e.Curr, e.Top, eNext.Curr, eNext.Top, this.m_UseFullRange) && (e.WindDelta !== 0) && (eNext.WindDelta !== 0))+ {+ var op2 = this.AddOutPt(eNext, e.Bot);+ this.AddJoin(op, op2, e.Top);+ }+ }+ e = e.NextInAEL;+ }+ };++ ClipperLib.Clipper.prototype.DoMaxima = function (e)+ {+ var eMaxPair = this.GetMaximaPairEx(e);+ if (eMaxPair === null)+ {+ if (e.OutIdx >= 0)+ this.AddOutPt(e, e.Top);+ this.DeleteFromAEL(e);+ return;+ }+ var eNext = e.NextInAEL;+ while (eNext !== null && eNext !== eMaxPair)+ {+ this.IntersectEdges(e, eNext, e.Top);+ this.SwapPositionsInAEL(e, eNext);+ eNext = e.NextInAEL;+ }+ if (e.OutIdx === -1 && eMaxPair.OutIdx === -1)+ {+ this.DeleteFromAEL(e);+ this.DeleteFromAEL(eMaxPair);+ }+ else if (e.OutIdx >= 0 && eMaxPair.OutIdx >= 0)+ {+ if (e.OutIdx >= 0) this.AddLocalMaxPoly(e, eMaxPair, e.Top);+ this.DeleteFromAEL(e);+ this.DeleteFromAEL(eMaxPair);+ }+ else if (ClipperLib.use_lines && e.WindDelta === 0)+ {+ if (e.OutIdx >= 0)+ {+ this.AddOutPt(e, e.Top);+ e.OutIdx = ClipperLib.ClipperBase.Unassigned;+ }+ this.DeleteFromAEL(e);+ if (eMaxPair.OutIdx >= 0)+ {+ this.AddOutPt(eMaxPair, e.Top);+ eMaxPair.OutIdx = ClipperLib.ClipperBase.Unassigned;+ }+ this.DeleteFromAEL(eMaxPair);+ }+ else+ ClipperLib.Error("DoMaxima error");+ };++ ClipperLib.Clipper.ReversePaths = function (polys)+ {+ for (var i = 0, len = polys.length; i < len; i++)+ polys[i].reverse();+ };++ ClipperLib.Clipper.Orientation = function (poly)+ {+ return ClipperLib.Clipper.Area(poly) >= 0;+ };++ ClipperLib.Clipper.prototype.PointCount = function (pts)+ {+ if (pts === null)+ return 0;+ var result = 0;+ var p = pts;+ do {+ result++;+ p = p.Next;+ }+ while (p !== pts)+ return result;+ };++ ClipperLib.Clipper.prototype.BuildResult = function (polyg)+ {+ ClipperLib.Clear(polyg);+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ var outRec = this.m_PolyOuts[i];+ if (outRec.Pts === null)+ continue;+ var p = outRec.Pts.Prev;+ var cnt = this.PointCount(p);+ if (cnt < 2)+ continue;+ var pg = new Array(cnt);+ for (var j = 0; j < cnt; j++)+ {+ pg[j] = p.Pt;+ p = p.Prev;+ }+ polyg.push(pg);+ }+ };++ ClipperLib.Clipper.prototype.BuildResult2 = function (polytree)+ {+ polytree.Clear();+ //add each output polygon/contour to polytree ...+ //polytree.m_AllPolys.set_Capacity(this.m_PolyOuts.length);+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ var outRec = this.m_PolyOuts[i];+ var cnt = this.PointCount(outRec.Pts);+ if ((outRec.IsOpen && cnt < 2) || (!outRec.IsOpen && cnt < 3))+ continue;+ this.FixHoleLinkage(outRec);+ var pn = new ClipperLib.PolyNode();+ polytree.m_AllPolys.push(pn);+ outRec.PolyNode = pn;+ pn.m_polygon.length = cnt;+ var op = outRec.Pts.Prev;+ for (var j = 0; j < cnt; j++)+ {+ pn.m_polygon[j] = op.Pt;+ op = op.Prev;+ }+ }+ //fixup PolyNode links etc ...+ //polytree.m_Childs.set_Capacity(this.m_PolyOuts.length);+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ var outRec = this.m_PolyOuts[i];+ if (outRec.PolyNode === null)+ continue;+ else if (outRec.IsOpen)+ {+ outRec.PolyNode.IsOpen = true;+ polytree.AddChild(outRec.PolyNode);+ }+ else if (outRec.FirstLeft !== null && outRec.FirstLeft.PolyNode !== null)+ outRec.FirstLeft.PolyNode.AddChild(outRec.PolyNode);+ else+ polytree.AddChild(outRec.PolyNode);+ }+ };++ ClipperLib.Clipper.prototype.FixupOutPolyline = function (outRec)+ {+ var pp = outRec.Pts;+ var lastPP = pp.Prev;+ while (pp !== lastPP)+ {+ pp = pp.Next;+ if (ClipperLib.IntPoint.op_Equality(pp.Pt, pp.Prev.Pt))+ {+ if (pp === lastPP)+ {+ lastPP = pp.Prev;+ }+ var tmpPP = pp.Prev;+ tmpPP.Next = pp.Next;+ pp.Next.Prev = tmpPP;+ pp = tmpPP;+ }+ }+ if (pp === pp.Prev)+ {+ outRec.Pts = null;+ }+ };++ ClipperLib.Clipper.prototype.FixupOutPolygon = function (outRec)+ {+ //FixupOutPolygon() - removes duplicate points and simplifies consecutive+ //parallel edges by removing the middle vertex.+ var lastOK = null;+ outRec.BottomPt = null;+ var pp = outRec.Pts;+ var preserveCol = this.PreserveCollinear || this.StrictlySimple;+ for (;;)+ {+ if (pp.Prev === pp || pp.Prev === pp.Next)+ {+ outRec.Pts = null;+ return;+ }++ //test for duplicate points and collinear edges ...+ if ((ClipperLib.IntPoint.op_Equality(pp.Pt, pp.Next.Pt)) || (ClipperLib.IntPoint.op_Equality(pp.Pt, pp.Prev.Pt)) || (ClipperLib.ClipperBase.SlopesEqual4(pp.Prev.Pt, pp.Pt, pp.Next.Pt, this.m_UseFullRange) && (!preserveCol || !this.Pt2IsBetweenPt1AndPt3(pp.Prev.Pt, pp.Pt, pp.Next.Pt))))+ {+ lastOK = null;+ pp.Prev.Next = pp.Next;+ pp.Next.Prev = pp.Prev;+ pp = pp.Prev;+ }+ else if (pp === lastOK)+ break;+ else+ {+ if (lastOK === null)+ lastOK = pp;+ pp = pp.Next;+ }+ }+ outRec.Pts = pp;+ };++ ClipperLib.Clipper.prototype.DupOutPt = function (outPt, InsertAfter)+ {+ var result = new ClipperLib.OutPt();+ //result.Pt = outPt.Pt;+ result.Pt.X = outPt.Pt.X;+ result.Pt.Y = outPt.Pt.Y;+ if (ClipperLib.use_xyz) result.Pt.Z = outPt.Pt.Z;+ result.Idx = outPt.Idx;+ if (InsertAfter)+ {+ result.Next = outPt.Next;+ result.Prev = outPt;+ outPt.Next.Prev = result;+ outPt.Next = result;+ }+ else+ {+ result.Prev = outPt.Prev;+ result.Next = outPt;+ outPt.Prev.Next = result;+ outPt.Prev = result;+ }+ return result;+ };++ ClipperLib.Clipper.prototype.GetOverlap = function (a1, a2, b1, b2, $val)+ {+ if (a1 < a2)+ {+ if (b1 < b2)+ {+ $val.Left = Math.max(a1, b1);+ $val.Right = Math.min(a2, b2);+ }+ else+ {+ $val.Left = Math.max(a1, b2);+ $val.Right = Math.min(a2, b1);+ }+ }+ else+ {+ if (b1 < b2)+ {+ $val.Left = Math.max(a2, b1);+ $val.Right = Math.min(a1, b2);+ }+ else+ {+ $val.Left = Math.max(a2, b2);+ $val.Right = Math.min(a1, b1);+ }+ }+ return $val.Left < $val.Right;+ };++ ClipperLib.Clipper.prototype.JoinHorz = function (op1, op1b, op2, op2b, Pt, DiscardLeft)+ {+ var Dir1 = (op1.Pt.X > op1b.Pt.X ? ClipperLib.Direction.dRightToLeft : ClipperLib.Direction.dLeftToRight);+ var Dir2 = (op2.Pt.X > op2b.Pt.X ? ClipperLib.Direction.dRightToLeft : ClipperLib.Direction.dLeftToRight);+ if (Dir1 === Dir2)+ return false;+ //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we+ //want Op1b to be on the Right. (And likewise with Op2 and Op2b.)+ //So, to facilitate this while inserting Op1b and Op2b ...+ //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,+ //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)+ if (Dir1 === ClipperLib.Direction.dLeftToRight)+ {+ while (op1.Next.Pt.X <= Pt.X &&+ op1.Next.Pt.X >= op1.Pt.X && op1.Next.Pt.Y === Pt.Y)+ op1 = op1.Next;+ if (DiscardLeft && (op1.Pt.X !== Pt.X))+ op1 = op1.Next;+ op1b = this.DupOutPt(op1, !DiscardLeft);+ if (ClipperLib.IntPoint.op_Inequality(op1b.Pt, Pt))+ {+ op1 = op1b;+ //op1.Pt = Pt;+ op1.Pt.X = Pt.X;+ op1.Pt.Y = Pt.Y;+ if (ClipperLib.use_xyz) op1.Pt.Z = Pt.Z;+ op1b = this.DupOutPt(op1, !DiscardLeft);+ }+ }+ else+ {+ while (op1.Next.Pt.X >= Pt.X &&+ op1.Next.Pt.X <= op1.Pt.X && op1.Next.Pt.Y === Pt.Y)+ op1 = op1.Next;+ if (!DiscardLeft && (op1.Pt.X !== Pt.X))+ op1 = op1.Next;+ op1b = this.DupOutPt(op1, DiscardLeft);+ if (ClipperLib.IntPoint.op_Inequality(op1b.Pt, Pt))+ {+ op1 = op1b;+ //op1.Pt = Pt;+ op1.Pt.X = Pt.X;+ op1.Pt.Y = Pt.Y;+ if (ClipperLib.use_xyz) op1.Pt.Z = Pt.Z;+ op1b = this.DupOutPt(op1, DiscardLeft);+ }+ }+ if (Dir2 === ClipperLib.Direction.dLeftToRight)+ {+ while (op2.Next.Pt.X <= Pt.X &&+ op2.Next.Pt.X >= op2.Pt.X && op2.Next.Pt.Y === Pt.Y)+ op2 = op2.Next;+ if (DiscardLeft && (op2.Pt.X !== Pt.X))+ op2 = op2.Next;+ op2b = this.DupOutPt(op2, !DiscardLeft);+ if (ClipperLib.IntPoint.op_Inequality(op2b.Pt, Pt))+ {+ op2 = op2b;+ //op2.Pt = Pt;+ op2.Pt.X = Pt.X;+ op2.Pt.Y = Pt.Y;+ if (ClipperLib.use_xyz) op2.Pt.Z = Pt.Z;+ op2b = this.DupOutPt(op2, !DiscardLeft);+ }+ }+ else+ {+ while (op2.Next.Pt.X >= Pt.X &&+ op2.Next.Pt.X <= op2.Pt.X && op2.Next.Pt.Y === Pt.Y)+ op2 = op2.Next;+ if (!DiscardLeft && (op2.Pt.X !== Pt.X))+ op2 = op2.Next;+ op2b = this.DupOutPt(op2, DiscardLeft);+ if (ClipperLib.IntPoint.op_Inequality(op2b.Pt, Pt))+ {+ op2 = op2b;+ //op2.Pt = Pt;+ op2.Pt.X = Pt.X;+ op2.Pt.Y = Pt.Y;+ if (ClipperLib.use_xyz) op2.Pt.Z = Pt.Z;+ op2b = this.DupOutPt(op2, DiscardLeft);+ }+ }+ if ((Dir1 === ClipperLib.Direction.dLeftToRight) === DiscardLeft)+ {+ op1.Prev = op2;+ op2.Next = op1;+ op1b.Next = op2b;+ op2b.Prev = op1b;+ }+ else+ {+ op1.Next = op2;+ op2.Prev = op1;+ op1b.Prev = op2b;+ op2b.Next = op1b;+ }+ return true;+ };++ ClipperLib.Clipper.prototype.JoinPoints = function (j, outRec1, outRec2)+ {+ var op1 = j.OutPt1,+ op1b = new ClipperLib.OutPt();+ var op2 = j.OutPt2,+ op2b = new ClipperLib.OutPt();+ //There are 3 kinds of joins for output polygons ...+ //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere+ //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).+ //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same+ //location at the Bottom of the overlapping segment (& Join.OffPt is above).+ //3. StrictlySimple joins where edges touch but are not collinear and where+ //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.+ var isHorizontal = (j.OutPt1.Pt.Y === j.OffPt.Y);+ if (isHorizontal && (ClipperLib.IntPoint.op_Equality(j.OffPt, j.OutPt1.Pt)) && (ClipperLib.IntPoint.op_Equality(j.OffPt, j.OutPt2.Pt)))+ {+ //Strictly Simple join ...+ if (outRec1 !== outRec2) return false;++ op1b = j.OutPt1.Next;+ while (op1b !== op1 && (ClipperLib.IntPoint.op_Equality(op1b.Pt, j.OffPt)))+ op1b = op1b.Next;+ var reverse1 = (op1b.Pt.Y > j.OffPt.Y);+ op2b = j.OutPt2.Next;+ while (op2b !== op2 && (ClipperLib.IntPoint.op_Equality(op2b.Pt, j.OffPt)))+ op2b = op2b.Next;+ var reverse2 = (op2b.Pt.Y > j.OffPt.Y);+ if (reverse1 === reverse2)+ return false;+ if (reverse1)+ {+ op1b = this.DupOutPt(op1, false);+ op2b = this.DupOutPt(op2, true);+ op1.Prev = op2;+ op2.Next = op1;+ op1b.Next = op2b;+ op2b.Prev = op1b;+ j.OutPt1 = op1;+ j.OutPt2 = op1b;+ return true;+ }+ else+ {+ op1b = this.DupOutPt(op1, true);+ op2b = this.DupOutPt(op2, false);+ op1.Next = op2;+ op2.Prev = op1;+ op1b.Prev = op2b;+ op2b.Next = op1b;+ j.OutPt1 = op1;+ j.OutPt2 = op1b;+ return true;+ }+ }+ else if (isHorizontal)+ {+ //treat horizontal joins differently to non-horizontal joins since with+ //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt+ //may be anywhere along the horizontal edge.+ op1b = op1;+ while (op1.Prev.Pt.Y === op1.Pt.Y && op1.Prev !== op1b && op1.Prev !== op2)+ op1 = op1.Prev;+ while (op1b.Next.Pt.Y === op1b.Pt.Y && op1b.Next !== op1 && op1b.Next !== op2)+ op1b = op1b.Next;+ if (op1b.Next === op1 || op1b.Next === op2)+ return false;+ //a flat 'polygon'+ op2b = op2;+ while (op2.Prev.Pt.Y === op2.Pt.Y && op2.Prev !== op2b && op2.Prev !== op1b)+ op2 = op2.Prev;+ while (op2b.Next.Pt.Y === op2b.Pt.Y && op2b.Next !== op2 && op2b.Next !== op1)+ op2b = op2b.Next;+ if (op2b.Next === op2 || op2b.Next === op1)+ return false;+ //a flat 'polygon'+ //Op1 -. Op1b & Op2 -. Op2b are the extremites of the horizontal edges++ var $val = {+ Left: null,+ Right: null+ };++ if (!this.GetOverlap(op1.Pt.X, op1b.Pt.X, op2.Pt.X, op2b.Pt.X, $val))+ return false;+ var Left = $val.Left;+ var Right = $val.Right;++ //DiscardLeftSide: when overlapping edges are joined, a spike will created+ //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up+ //on the discard Side as either may still be needed for other joins ...+ var Pt = new ClipperLib.IntPoint0();+ var DiscardLeftSide;+ if (op1.Pt.X >= Left && op1.Pt.X <= Right)+ {+ //Pt = op1.Pt;+ Pt.X = op1.Pt.X;+ Pt.Y = op1.Pt.Y;+ if (ClipperLib.use_xyz) Pt.Z = op1.Pt.Z;+ DiscardLeftSide = (op1.Pt.X > op1b.Pt.X);+ }+ else if (op2.Pt.X >= Left && op2.Pt.X <= Right)+ {+ //Pt = op2.Pt;+ Pt.X = op2.Pt.X;+ Pt.Y = op2.Pt.Y;+ if (ClipperLib.use_xyz) Pt.Z = op2.Pt.Z;+ DiscardLeftSide = (op2.Pt.X > op2b.Pt.X);+ }+ else if (op1b.Pt.X >= Left && op1b.Pt.X <= Right)+ {+ //Pt = op1b.Pt;+ Pt.X = op1b.Pt.X;+ Pt.Y = op1b.Pt.Y;+ if (ClipperLib.use_xyz) Pt.Z = op1b.Pt.Z;+ DiscardLeftSide = op1b.Pt.X > op1.Pt.X;+ }+ else+ {+ //Pt = op2b.Pt;+ Pt.X = op2b.Pt.X;+ Pt.Y = op2b.Pt.Y;+ if (ClipperLib.use_xyz) Pt.Z = op2b.Pt.Z;+ DiscardLeftSide = (op2b.Pt.X > op2.Pt.X);+ }+ j.OutPt1 = op1;+ j.OutPt2 = op2;+ return this.JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);+ }+ else+ {+ //nb: For non-horizontal joins ...+ // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y+ // 2. Jr.OutPt1.Pt > Jr.OffPt.Y+ //make sure the polygons are correctly oriented ...+ op1b = op1.Next;+ while ((ClipperLib.IntPoint.op_Equality(op1b.Pt, op1.Pt)) && (op1b !== op1))+ op1b = op1b.Next;+ var Reverse1 = ((op1b.Pt.Y > op1.Pt.Y) || !ClipperLib.ClipperBase.SlopesEqual4(op1.Pt, op1b.Pt, j.OffPt, this.m_UseFullRange));+ if (Reverse1)+ {+ op1b = op1.Prev;+ while ((ClipperLib.IntPoint.op_Equality(op1b.Pt, op1.Pt)) && (op1b !== op1))+ op1b = op1b.Prev;++ if ((op1b.Pt.Y > op1.Pt.Y) || !ClipperLib.ClipperBase.SlopesEqual4(op1.Pt, op1b.Pt, j.OffPt, this.m_UseFullRange))+ return false;+ }+ op2b = op2.Next;+ while ((ClipperLib.IntPoint.op_Equality(op2b.Pt, op2.Pt)) && (op2b !== op2))+ op2b = op2b.Next;++ var Reverse2 = ((op2b.Pt.Y > op2.Pt.Y) || !ClipperLib.ClipperBase.SlopesEqual4(op2.Pt, op2b.Pt, j.OffPt, this.m_UseFullRange));+ if (Reverse2)+ {+ op2b = op2.Prev;+ while ((ClipperLib.IntPoint.op_Equality(op2b.Pt, op2.Pt)) && (op2b !== op2))+ op2b = op2b.Prev;++ if ((op2b.Pt.Y > op2.Pt.Y) || !ClipperLib.ClipperBase.SlopesEqual4(op2.Pt, op2b.Pt, j.OffPt, this.m_UseFullRange))+ return false;+ }+ if ((op1b === op1) || (op2b === op2) || (op1b === op2b) ||+ ((outRec1 === outRec2) && (Reverse1 === Reverse2)))+ return false;+ if (Reverse1)+ {+ op1b = this.DupOutPt(op1, false);+ op2b = this.DupOutPt(op2, true);+ op1.Prev = op2;+ op2.Next = op1;+ op1b.Next = op2b;+ op2b.Prev = op1b;+ j.OutPt1 = op1;+ j.OutPt2 = op1b;+ return true;+ }+ else+ {+ op1b = this.DupOutPt(op1, true);+ op2b = this.DupOutPt(op2, false);+ op1.Next = op2;+ op2.Prev = op1;+ op1b.Prev = op2b;+ op2b.Next = op1b;+ j.OutPt1 = op1;+ j.OutPt2 = op1b;+ return true;+ }+ }+ };++ ClipperLib.Clipper.GetBounds = function (paths)+ {+ var i = 0,+ cnt = paths.length;+ while (i < cnt && paths[i].length === 0) i++;+ if (i === cnt) return new ClipperLib.IntRect(0, 0, 0, 0);+ var result = new ClipperLib.IntRect();+ result.left = paths[i][0].X;+ result.right = result.left;+ result.top = paths[i][0].Y;+ result.bottom = result.top;+ for (; i < cnt; i++)+ for (var j = 0, jlen = paths[i].length; j < jlen; j++)+ {+ if (paths[i][j].X < result.left) result.left = paths[i][j].X;+ else if (paths[i][j].X > result.right) result.right = paths[i][j].X;+ if (paths[i][j].Y < result.top) result.top = paths[i][j].Y;+ else if (paths[i][j].Y > result.bottom) result.bottom = paths[i][j].Y;+ }+ return result;+ }+ ClipperLib.Clipper.prototype.GetBounds2 = function (ops)+ {+ var opStart = ops;+ var result = new ClipperLib.IntRect();+ result.left = ops.Pt.X;+ result.right = ops.Pt.X;+ result.top = ops.Pt.Y;+ result.bottom = ops.Pt.Y;+ ops = ops.Next;+ while (ops !== opStart)+ {+ if (ops.Pt.X < result.left)+ result.left = ops.Pt.X;+ if (ops.Pt.X > result.right)+ result.right = ops.Pt.X;+ if (ops.Pt.Y < result.top)+ result.top = ops.Pt.Y;+ if (ops.Pt.Y > result.bottom)+ result.bottom = ops.Pt.Y;+ ops = ops.Next;+ }+ return result;+ };++ ClipperLib.Clipper.PointInPolygon = function (pt, path)+ {+ //returns 0 if false, +1 if true, -1 if pt ON polygon boundary+ //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos+ //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf+ var result = 0,+ cnt = path.length;+ if (cnt < 3)+ return 0;+ var ip = path[0];+ for (var i = 1; i <= cnt; ++i)+ {+ var ipNext = (i === cnt ? path[0] : path[i]);+ if (ipNext.Y === pt.Y)+ {+ if ((ipNext.X === pt.X) || (ip.Y === pt.Y && ((ipNext.X > pt.X) === (ip.X < pt.X))))+ return -1;+ }+ if ((ip.Y < pt.Y) !== (ipNext.Y < pt.Y))+ {+ if (ip.X >= pt.X)+ {+ if (ipNext.X > pt.X)+ result = 1 - result;+ else+ {+ var d = (ip.X - pt.X) * (ipNext.Y - pt.Y) - (ipNext.X - pt.X) * (ip.Y - pt.Y);+ if (d === 0)+ return -1;+ else if ((d > 0) === (ipNext.Y > ip.Y))+ result = 1 - result;+ }+ }+ else+ {+ if (ipNext.X > pt.X)+ {+ var d = (ip.X - pt.X) * (ipNext.Y - pt.Y) - (ipNext.X - pt.X) * (ip.Y - pt.Y);+ if (d === 0)+ return -1;+ else if ((d > 0) === (ipNext.Y > ip.Y))+ result = 1 - result;+ }+ }+ }+ ip = ipNext;+ }+ return result;+ };++ ClipperLib.Clipper.prototype.PointInPolygon = function (pt, op)+ {+ //returns 0 if false, +1 if true, -1 if pt ON polygon boundary+ var result = 0;+ var startOp = op;+ var ptx = pt.X,+ pty = pt.Y;+ var poly0x = op.Pt.X,+ poly0y = op.Pt.Y;+ do {+ op = op.Next;+ var poly1x = op.Pt.X,+ poly1y = op.Pt.Y;+ if (poly1y === pty)+ {+ if ((poly1x === ptx) || (poly0y === pty && ((poly1x > ptx) === (poly0x < ptx))))+ return -1;+ }+ if ((poly0y < pty) !== (poly1y < pty))+ {+ if (poly0x >= ptx)+ {+ if (poly1x > ptx)+ result = 1 - result;+ else+ {+ var d = (poly0x - ptx) * (poly1y - pty) - (poly1x - ptx) * (poly0y - pty);+ if (d === 0)+ return -1;+ if ((d > 0) === (poly1y > poly0y))+ result = 1 - result;+ }+ }+ else+ {+ if (poly1x > ptx)+ {+ var d = (poly0x - ptx) * (poly1y - pty) - (poly1x - ptx) * (poly0y - pty);+ if (d === 0)+ return -1;+ if ((d > 0) === (poly1y > poly0y))+ result = 1 - result;+ }+ }+ }+ poly0x = poly1x;+ poly0y = poly1y;+ } while (startOp !== op);++ return result;+ };++ ClipperLib.Clipper.prototype.Poly2ContainsPoly1 = function (outPt1, outPt2)+ {+ var op = outPt1;+ do {+ //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon+ var res = this.PointInPolygon(op.Pt, outPt2);+ if (res >= 0)+ return res > 0;+ op = op.Next;+ }+ while (op !== outPt1)+ return true;+ };++ ClipperLib.Clipper.prototype.FixupFirstLefts1 = function (OldOutRec, NewOutRec)+ {+ var outRec, firstLeft;+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ outRec = this.m_PolyOuts[i];+ firstLeft = ClipperLib.Clipper.ParseFirstLeft(outRec.FirstLeft);+ if (outRec.Pts !== null && firstLeft === OldOutRec)+ {+ if (this.Poly2ContainsPoly1(outRec.Pts, NewOutRec.Pts))+ outRec.FirstLeft = NewOutRec;+ }+ }+ }++ ClipperLib.Clipper.prototype.FixupFirstLefts2 = function (innerOutRec, outerOutRec)+ {+ //A polygon has split into two such that one is now the inner of the other.+ //It's possible that these polygons now wrap around other polygons, so check+ //every polygon that's also contained by OuterOutRec's FirstLeft container+ //(including nil) to see if they've become inner to the new inner polygon ...+ var orfl = outerOutRec.FirstLeft;+ var outRec, firstLeft;+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ outRec = this.m_PolyOuts[i];+ if (outRec.Pts === null || outRec === outerOutRec || outRec === innerOutRec)+ continue;+ firstLeft = ClipperLib.Clipper.ParseFirstLeft(outRec.FirstLeft);+ if (firstLeft !== orfl && firstLeft !== innerOutRec && firstLeft !== outerOutRec)+ continue;+ if (this.Poly2ContainsPoly1(outRec.Pts, innerOutRec.Pts))+ outRec.FirstLeft = innerOutRec;+ else if (this.Poly2ContainsPoly1(outRec.Pts, outerOutRec.Pts))+ outRec.FirstLeft = outerOutRec;+ else if (outRec.FirstLeft === innerOutRec || outRec.FirstLeft === outerOutRec)+ outRec.FirstLeft = orfl;+ }+ }++ ClipperLib.Clipper.prototype.FixupFirstLefts3 = function (OldOutRec, NewOutRec)+ {+ //same as FixupFirstLefts1 but doesn't call Poly2ContainsPoly1()+ var outRec;+ var firstLeft;+ for (var i = 0, ilen = this.m_PolyOuts.length; i < ilen; i++)+ {+ outRec = this.m_PolyOuts[i];+ firstLeft = ClipperLib.Clipper.ParseFirstLeft(outRec.FirstLeft);+ if (outRec.Pts !== null && firstLeft === OldOutRec)+ outRec.FirstLeft = NewOutRec;+ }+ }++ ClipperLib.Clipper.ParseFirstLeft = function (FirstLeft)+ {+ while (FirstLeft !== null && FirstLeft.Pts === null)+ FirstLeft = FirstLeft.FirstLeft;+ return FirstLeft;+ };++ ClipperLib.Clipper.prototype.JoinCommonEdges = function ()+ {+ for (var i = 0, ilen = this.m_Joins.length; i < ilen; i++)+ {+ var join = this.m_Joins[i];+ var outRec1 = this.GetOutRec(join.OutPt1.Idx);+ var outRec2 = this.GetOutRec(join.OutPt2.Idx);+ if (outRec1.Pts === null || outRec2.Pts === null)+ continue;++ if (outRec1.IsOpen || outRec2.IsOpen)+ {+ continue;+ }++ //get the polygon fragment with the correct hole state (FirstLeft)+ //before calling JoinPoints() ...+ var holeStateRec;+ if (outRec1 === outRec2)+ holeStateRec = outRec1;+ else if (this.OutRec1RightOfOutRec2(outRec1, outRec2))+ holeStateRec = outRec2;+ else if (this.OutRec1RightOfOutRec2(outRec2, outRec1))+ holeStateRec = outRec1;+ else+ holeStateRec = this.GetLowermostRec(outRec1, outRec2);++ if (!this.JoinPoints(join, outRec1, outRec2)) continue;++ if (outRec1 === outRec2)+ {+ //instead of joining two polygons, we've just created a new one by+ //splitting one polygon into two.+ outRec1.Pts = join.OutPt1;+ outRec1.BottomPt = null;+ outRec2 = this.CreateOutRec();+ outRec2.Pts = join.OutPt2;+ //update all OutRec2.Pts Idx's ...+ this.UpdateOutPtIdxs(outRec2);++ if (this.Poly2ContainsPoly1(outRec2.Pts, outRec1.Pts))+ {+ //outRec1 contains outRec2 ...+ outRec2.IsHole = !outRec1.IsHole;+ outRec2.FirstLeft = outRec1;+ if (this.m_UsingPolyTree)+ this.FixupFirstLefts2(outRec2, outRec1);+ if ((outRec2.IsHole ^ this.ReverseSolution) == (this.Area$1(outRec2) > 0))+ this.ReversePolyPtLinks(outRec2.Pts);+ }+ else if (this.Poly2ContainsPoly1(outRec1.Pts, outRec2.Pts))+ {+ //outRec2 contains outRec1 ...+ outRec2.IsHole = outRec1.IsHole;+ outRec1.IsHole = !outRec2.IsHole;+ outRec2.FirstLeft = outRec1.FirstLeft;+ outRec1.FirstLeft = outRec2;+ if (this.m_UsingPolyTree)+ this.FixupFirstLefts2(outRec1, outRec2);++ if ((outRec1.IsHole ^ this.ReverseSolution) == (this.Area$1(outRec1) > 0))+ this.ReversePolyPtLinks(outRec1.Pts);+ }+ else+ {+ //the 2 polygons are completely separate ...+ outRec2.IsHole = outRec1.IsHole;+ outRec2.FirstLeft = outRec1.FirstLeft;+ //fixup FirstLeft pointers that may need reassigning to OutRec2+ if (this.m_UsingPolyTree)+ this.FixupFirstLefts1(outRec1, outRec2);+ }+ }+ else+ {+ //joined 2 polygons together ...+ outRec2.Pts = null;+ outRec2.BottomPt = null;+ outRec2.Idx = outRec1.Idx;+ outRec1.IsHole = holeStateRec.IsHole;+ if (holeStateRec === outRec2)+ outRec1.FirstLeft = outRec2.FirstLeft;+ outRec2.FirstLeft = outRec1;+ //fixup FirstLeft pointers that may need reassigning to OutRec1+ if (this.m_UsingPolyTree)+ this.FixupFirstLefts3(outRec2, outRec1);+ }+ }+ };++ ClipperLib.Clipper.prototype.UpdateOutPtIdxs = function (outrec)+ {+ var op = outrec.Pts;+ do {+ op.Idx = outrec.Idx;+ op = op.Prev;+ }+ while (op !== outrec.Pts)+ };++ ClipperLib.Clipper.prototype.DoSimplePolygons = function ()+ {+ var i = 0;+ while (i < this.m_PolyOuts.length)+ {+ var outrec = this.m_PolyOuts[i++];+ var op = outrec.Pts;+ if (op === null || outrec.IsOpen)+ continue;+ do //for each Pt in Polygon until duplicate found do ...+ {+ var op2 = op.Next;+ while (op2 !== outrec.Pts)+ {+ if ((ClipperLib.IntPoint.op_Equality(op.Pt, op2.Pt)) && op2.Next !== op && op2.Prev !== op)+ {+ //split the polygon into two ...+ var op3 = op.Prev;+ var op4 = op2.Prev;+ op.Prev = op4;+ op4.Next = op;+ op2.Prev = op3;+ op3.Next = op2;+ outrec.Pts = op;+ var outrec2 = this.CreateOutRec();+ outrec2.Pts = op2;+ this.UpdateOutPtIdxs(outrec2);+ if (this.Poly2ContainsPoly1(outrec2.Pts, outrec.Pts))+ {+ //OutRec2 is contained by OutRec1 ...+ outrec2.IsHole = !outrec.IsHole;+ outrec2.FirstLeft = outrec;+ if (this.m_UsingPolyTree) this.FixupFirstLefts2(outrec2, outrec);++ }+ else if (this.Poly2ContainsPoly1(outrec.Pts, outrec2.Pts))+ {+ //OutRec1 is contained by OutRec2 ...+ outrec2.IsHole = outrec.IsHole;+ outrec.IsHole = !outrec2.IsHole;+ outrec2.FirstLeft = outrec.FirstLeft;+ outrec.FirstLeft = outrec2;+ if (this.m_UsingPolyTree) this.FixupFirstLefts2(outrec, outrec2);+ }+ else+ {+ //the 2 polygons are separate ...+ outrec2.IsHole = outrec.IsHole;+ outrec2.FirstLeft = outrec.FirstLeft;+ if (this.m_UsingPolyTree) this.FixupFirstLefts1(outrec, outrec2);+ }+ op2 = op;+ //ie get ready for the next iteration+ }+ op2 = op2.Next;+ }+ op = op.Next;+ }+ while (op !== outrec.Pts)+ }+ };++ ClipperLib.Clipper.Area = function (poly)+ {+ if (!Array.isArray(poly))+ return 0;+ var cnt = poly.length;+ if (cnt < 3)+ return 0;+ var a = 0;+ for (var i = 0, j = cnt - 1; i < cnt; ++i)+ {+ a += (poly[j].X + poly[i].X) * (poly[j].Y - poly[i].Y);+ j = i;+ }+ return -a * 0.5;+ };++ ClipperLib.Clipper.prototype.Area = function (op)+ {+ var opFirst = op;+ if (op === null) return 0;+ var a = 0;+ do {+ a = a + (op.Prev.Pt.X + op.Pt.X) * (op.Prev.Pt.Y - op.Pt.Y);+ op = op.Next;+ } while (op !== opFirst); // && typeof op !== 'undefined');+ return a * 0.5;+ }++ ClipperLib.Clipper.prototype.Area$1 = function (outRec)+ {+ return this.Area(outRec.Pts);+ };++ ClipperLib.Clipper.SimplifyPolygon = function (poly, fillType)+ {+ var result = new Array();+ var c = new ClipperLib.Clipper(0);+ c.StrictlySimple = true;+ c.AddPath(poly, ClipperLib.PolyType.ptSubject, true);+ c.Execute(ClipperLib.ClipType.ctUnion, result, fillType, fillType);+ return result;+ };++ ClipperLib.Clipper.SimplifyPolygons = function (polys, fillType)+ {+ if (typeof (fillType) === "undefined") fillType = ClipperLib.PolyFillType.pftEvenOdd;+ var result = new Array();+ var c = new ClipperLib.Clipper(0);+ c.StrictlySimple = true;+ c.AddPaths(polys, ClipperLib.PolyType.ptSubject, true);+ c.Execute(ClipperLib.ClipType.ctUnion, result, fillType, fillType);+ return result;+ };++ ClipperLib.Clipper.DistanceSqrd = function (pt1, pt2)+ {+ var dx = (pt1.X - pt2.X);+ var dy = (pt1.Y - pt2.Y);+ return (dx * dx + dy * dy);+ };++ ClipperLib.Clipper.DistanceFromLineSqrd = function (pt, ln1, ln2)+ {+ //The equation of a line in general form (Ax + By + C = 0)+ //given 2 points (x¹,y¹) & (x²,y²) is ...+ //(y¹ - y²)x + (x² - x¹)y + (y² - y¹)x¹ - (x² - x¹)y¹ = 0+ //A = (y¹ - y²); B = (x² - x¹); C = (y² - y¹)x¹ - (x² - x¹)y¹+ //perpendicular distance of point (x³,y³) = (Ax³ + By³ + C)/Sqrt(A² + B²)+ //see http://en.wikipedia.org/wiki/Perpendicular_distance+ var A = ln1.Y - ln2.Y;+ var B = ln2.X - ln1.X;+ var C = A * ln1.X + B * ln1.Y;+ C = A * pt.X + B * pt.Y - C;+ return (C * C) / (A * A + B * B);+ };++ ClipperLib.Clipper.SlopesNearCollinear = function (pt1, pt2, pt3, distSqrd)+ {+ //this function is more accurate when the point that's GEOMETRICALLY+ //between the other 2 points is the one that's tested for distance.+ //nb: with 'spikes', either pt1 or pt3 is geometrically between the other pts+ if (Math.abs(pt1.X - pt2.X) > Math.abs(pt1.Y - pt2.Y))+ {+ if ((pt1.X > pt2.X) === (pt1.X < pt3.X))+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;+ else if ((pt2.X > pt1.X) === (pt2.X < pt3.X))+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;+ else+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;+ }+ else+ {+ if ((pt1.Y > pt2.Y) === (pt1.Y < pt3.Y))+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;+ else if ((pt2.Y > pt1.Y) === (pt2.Y < pt3.Y))+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;+ else+ return ClipperLib.Clipper.DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;+ }+ }++ ClipperLib.Clipper.PointsAreClose = function (pt1, pt2, distSqrd)+ {+ var dx = pt1.X - pt2.X;+ var dy = pt1.Y - pt2.Y;+ return ((dx * dx) + (dy * dy) <= distSqrd);+ };++ ClipperLib.Clipper.ExcludeOp = function (op)+ {+ var result = op.Prev;+ result.Next = op.Next;+ op.Next.Prev = result;+ result.Idx = 0;+ return result;+ };++ ClipperLib.Clipper.CleanPolygon = function (path, distance)+ {+ if (typeof (distance) === "undefined") distance = 1.415;+ //distance = proximity in units/pixels below which vertices will be stripped.+ //Default ~= sqrt(2) so when adjacent vertices or semi-adjacent vertices have+ //both x & y coords within 1 unit, then the second vertex will be stripped.+ var cnt = path.length;+ if (cnt === 0)+ return new Array();+ var outPts = new Array(cnt);+ for (var i = 0; i < cnt; ++i)+ outPts[i] = new ClipperLib.OutPt();+ for (var i = 0; i < cnt; ++i)+ {+ outPts[i].Pt = path[i];+ outPts[i].Next = outPts[(i + 1) % cnt];+ outPts[i].Next.Prev = outPts[i];+ outPts[i].Idx = 0;+ }+ var distSqrd = distance * distance;+ var op = outPts[0];+ while (op.Idx === 0 && op.Next !== op.Prev)+ {+ if (ClipperLib.Clipper.PointsAreClose(op.Pt, op.Prev.Pt, distSqrd))+ {+ op = ClipperLib.Clipper.ExcludeOp(op);+ cnt--;+ }+ else if (ClipperLib.Clipper.PointsAreClose(op.Prev.Pt, op.Next.Pt, distSqrd))+ {+ ClipperLib.Clipper.ExcludeOp(op.Next);+ op = ClipperLib.Clipper.ExcludeOp(op);+ cnt -= 2;+ }+ else if (ClipperLib.Clipper.SlopesNearCollinear(op.Prev.Pt, op.Pt, op.Next.Pt, distSqrd))+ {+ op = ClipperLib.Clipper.ExcludeOp(op);+ cnt--;+ }+ else+ {+ op.Idx = 1;+ op = op.Next;+ }+ }+ if (cnt < 3)+ cnt = 0;+ var result = new Array(cnt);+ for (var i = 0; i < cnt; ++i)+ {+ result[i] = new ClipperLib.IntPoint1(op.Pt);+ op = op.Next;+ }+ outPts = null;+ return result;+ };++ ClipperLib.Clipper.CleanPolygons = function (polys, distance)+ {+ var result = new Array(polys.length);+ for (var i = 0, ilen = polys.length; i < ilen; i++)+ result[i] = ClipperLib.Clipper.CleanPolygon(polys[i], distance);+ return result;+ };++ ClipperLib.Clipper.Minkowski = function (pattern, path, IsSum, IsClosed)+ {+ var delta = (IsClosed ? 1 : 0);+ var polyCnt = pattern.length;+ var pathCnt = path.length;+ var result = new Array();+ if (IsSum)+ for (var i = 0; i < pathCnt; i++)+ {+ var p = new Array(polyCnt);+ for (var j = 0, jlen = pattern.length, ip = pattern[j]; j < jlen; j++, ip = pattern[j])+ p[j] = new ClipperLib.IntPoint2(path[i].X + ip.X, path[i].Y + ip.Y);+ result.push(p);+ }+ else+ for (var i = 0; i < pathCnt; i++)+ {+ var p = new Array(polyCnt);+ for (var j = 0, jlen = pattern.length, ip = pattern[j]; j < jlen; j++, ip = pattern[j])+ p[j] = new ClipperLib.IntPoint2(path[i].X - ip.X, path[i].Y - ip.Y);+ result.push(p);+ }+ var quads = new Array();+ for (var i = 0; i < pathCnt - 1 + delta; i++)+ for (var j = 0; j < polyCnt; j++)+ {+ var quad = new Array();+ quad.push(result[i % pathCnt][j % polyCnt]);+ quad.push(result[(i + 1) % pathCnt][j % polyCnt]);+ quad.push(result[(i + 1) % pathCnt][(j + 1) % polyCnt]);+ quad.push(result[i % pathCnt][(j + 1) % polyCnt]);+ if (!ClipperLib.Clipper.Orientation(quad))+ quad.reverse();+ quads.push(quad);+ }+ return quads;+ };++ ClipperLib.Clipper.MinkowskiSum = function (pattern, path_or_paths, pathIsClosed)+ {+ if (!(path_or_paths[0] instanceof Array))+ {+ var path = path_or_paths;+ var paths = ClipperLib.Clipper.Minkowski(pattern, path, true, pathIsClosed);+ var c = new ClipperLib.Clipper();+ c.AddPaths(paths, ClipperLib.PolyType.ptSubject, true);+ c.Execute(ClipperLib.ClipType.ctUnion, paths, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);+ return paths;+ }+ else+ {+ var paths = path_or_paths;+ var solution = new ClipperLib.Paths();+ var c = new ClipperLib.Clipper();+ for (var i = 0; i < paths.length; ++i)+ {+ var tmp = ClipperLib.Clipper.Minkowski(pattern, paths[i], true, pathIsClosed);+ c.AddPaths(tmp, ClipperLib.PolyType.ptSubject, true);+ if (pathIsClosed)+ {+ var path = ClipperLib.Clipper.TranslatePath(paths[i], pattern[0]);+ c.AddPath(path, ClipperLib.PolyType.ptClip, true);+ }+ }+ c.Execute(ClipperLib.ClipType.ctUnion, solution,+ ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);+ return solution;+ }+ }++ ClipperLib.Clipper.TranslatePath = function (path, delta)+ {+ var outPath = new ClipperLib.Path();+ for (var i = 0; i < path.length; i++)+ outPath.push(new ClipperLib.IntPoint2(path[i].X + delta.X, path[i].Y + delta.Y));+ return outPath;+ }++ ClipperLib.Clipper.MinkowskiDiff = function (poly1, poly2)+ {+ var paths = ClipperLib.Clipper.Minkowski(poly1, poly2, false, true);+ var c = new ClipperLib.Clipper();+ c.AddPaths(paths, ClipperLib.PolyType.ptSubject, true);+ c.Execute(ClipperLib.ClipType.ctUnion, paths, ClipperLib.PolyFillType.pftNonZero, ClipperLib.PolyFillType.pftNonZero);+ return paths;+ }++ ClipperLib.Clipper.PolyTreeToPaths = function (polytree)+ {+ var result = new Array();+ //result.set_Capacity(polytree.get_Total());+ ClipperLib.Clipper.AddPolyNodeToPaths(polytree, ClipperLib.Clipper.NodeType.ntAny, result);+ return result;+ };++ ClipperLib.Clipper.AddPolyNodeToPaths = function (polynode, nt, paths)+ {+ var match = true;+ switch (nt)+ {+ case ClipperLib.Clipper.NodeType.ntOpen:+ return;+ case ClipperLib.Clipper.NodeType.ntClosed:+ match = !polynode.IsOpen;+ break;+ default:+ break;+ }+ if (polynode.m_polygon.length > 0 && match)+ paths.push(polynode.m_polygon);+ for (var $i3 = 0, $t3 = polynode.Childs(), $l3 = $t3.length, pn = $t3[$i3]; $i3 < $l3; $i3++, pn = $t3[$i3])+ ClipperLib.Clipper.AddPolyNodeToPaths(pn, nt, paths);+ };++ ClipperLib.Clipper.OpenPathsFromPolyTree = function (polytree)+ {+ var result = new ClipperLib.Paths();+ //result.set_Capacity(polytree.ChildCount());+ for (var i = 0, ilen = polytree.ChildCount(); i < ilen; i++)+ if (polytree.Childs()[i].IsOpen)+ result.push(polytree.Childs()[i].m_polygon);+ return result;+ };++ ClipperLib.Clipper.ClosedPathsFromPolyTree = function (polytree)+ {+ var result = new ClipperLib.Paths();+ //result.set_Capacity(polytree.Total());+ ClipperLib.Clipper.AddPolyNodeToPaths(polytree, ClipperLib.Clipper.NodeType.ntClosed, result);+ return result;+ };++ Inherit(ClipperLib.Clipper, ClipperLib.ClipperBase);+ ClipperLib.Clipper.NodeType = {+ ntAny: 0,+ ntOpen: 1,+ ntClosed: 2+ };++ /**+ * @constructor+ */+ ClipperLib.ClipperOffset = function (miterLimit, arcTolerance)+ {+ if (typeof (miterLimit) === "undefined") miterLimit = 2;+ if (typeof (arcTolerance) === "undefined") arcTolerance = ClipperLib.ClipperOffset.def_arc_tolerance;+ this.m_destPolys = new ClipperLib.Paths();+ this.m_srcPoly = new ClipperLib.Path();+ this.m_destPoly = new ClipperLib.Path();+ this.m_normals = new Array();+ this.m_delta = 0;+ this.m_sinA = 0;+ this.m_sin = 0;+ this.m_cos = 0;+ this.m_miterLim = 0;+ this.m_StepsPerRad = 0;+ this.m_lowest = new ClipperLib.IntPoint0();+ this.m_polyNodes = new ClipperLib.PolyNode();+ this.MiterLimit = miterLimit;+ this.ArcTolerance = arcTolerance;+ this.m_lowest.X = -1;+ };++ ClipperLib.ClipperOffset.two_pi = 6.28318530717959;+ ClipperLib.ClipperOffset.def_arc_tolerance = 0.25;+ ClipperLib.ClipperOffset.prototype.Clear = function ()+ {+ ClipperLib.Clear(this.m_polyNodes.Childs());+ this.m_lowest.X = -1;+ };++ ClipperLib.ClipperOffset.Round = ClipperLib.Clipper.Round;+ ClipperLib.ClipperOffset.prototype.AddPath = function (path, joinType, endType)+ {+ var highI = path.length - 1;+ if (highI < 0)+ return;+ var newNode = new ClipperLib.PolyNode();+ newNode.m_jointype = joinType;+ newNode.m_endtype = endType;+ //strip duplicate points from path and also get index to the lowest point ...+ if (endType === ClipperLib.EndType.etClosedLine || endType === ClipperLib.EndType.etClosedPolygon)+ while (highI > 0 && ClipperLib.IntPoint.op_Equality(path[0], path[highI]))+ highI--;+ //newNode.m_polygon.set_Capacity(highI + 1);+ newNode.m_polygon.push(path[0]);+ var j = 0,+ k = 0;+ for (var i = 1; i <= highI; i++)+ if (ClipperLib.IntPoint.op_Inequality(newNode.m_polygon[j], path[i]))+ {+ j++;+ newNode.m_polygon.push(path[i]);+ if (path[i].Y > newNode.m_polygon[k].Y || (path[i].Y === newNode.m_polygon[k].Y && path[i].X < newNode.m_polygon[k].X))+ k = j;+ }+ if (endType === ClipperLib.EndType.etClosedPolygon && j < 2) return;++ this.m_polyNodes.AddChild(newNode);+ //if this path's lowest pt is lower than all the others then update m_lowest+ if (endType !== ClipperLib.EndType.etClosedPolygon)+ return;+ if (this.m_lowest.X < 0)+ this.m_lowest = new ClipperLib.IntPoint2(this.m_polyNodes.ChildCount() - 1, k);+ else+ {+ var ip = this.m_polyNodes.Childs()[this.m_lowest.X].m_polygon[this.m_lowest.Y];+ if (newNode.m_polygon[k].Y > ip.Y || (newNode.m_polygon[k].Y === ip.Y && newNode.m_polygon[k].X < ip.X))+ this.m_lowest = new ClipperLib.IntPoint2(this.m_polyNodes.ChildCount() - 1, k);+ }+ };++ ClipperLib.ClipperOffset.prototype.AddPaths = function (paths, joinType, endType)+ {+ for (var i = 0, ilen = paths.length; i < ilen; i++)+ this.AddPath(paths[i], joinType, endType);+ };++ ClipperLib.ClipperOffset.prototype.FixOrientations = function ()+ {+ //fixup orientations of all closed paths if the orientation of the+ //closed path with the lowermost vertex is wrong ...+ if (this.m_lowest.X >= 0 && !ClipperLib.Clipper.Orientation(this.m_polyNodes.Childs()[this.m_lowest.X].m_polygon))+ {+ for (var i = 0; i < this.m_polyNodes.ChildCount(); i++)+ {+ var node = this.m_polyNodes.Childs()[i];+ if (node.m_endtype === ClipperLib.EndType.etClosedPolygon || (node.m_endtype === ClipperLib.EndType.etClosedLine && ClipperLib.Clipper.Orientation(node.m_polygon)))+ node.m_polygon.reverse();+ }+ }+ else+ {+ for (var i = 0; i < this.m_polyNodes.ChildCount(); i++)+ {+ var node = this.m_polyNodes.Childs()[i];+ if (node.m_endtype === ClipperLib.EndType.etClosedLine && !ClipperLib.Clipper.Orientation(node.m_polygon))+ node.m_polygon.reverse();+ }+ }+ };++ ClipperLib.ClipperOffset.GetUnitNormal = function (pt1, pt2)+ {+ var dx = (pt2.X - pt1.X);+ var dy = (pt2.Y - pt1.Y);+ if ((dx === 0) && (dy === 0))+ return new ClipperLib.DoublePoint2(0, 0);+ var f = 1 / Math.sqrt(dx * dx + dy * dy);+ dx *= f;+ dy *= f;+ return new ClipperLib.DoublePoint2(dy, -dx);+ };++ ClipperLib.ClipperOffset.prototype.DoOffset = function (delta)+ {+ this.m_destPolys = new Array();+ this.m_delta = delta;+ //if Zero offset, just copy any CLOSED polygons to m_p and return ...+ if (ClipperLib.ClipperBase.near_zero(delta))+ {+ //this.m_destPolys.set_Capacity(this.m_polyNodes.ChildCount);+ for (var i = 0; i < this.m_polyNodes.ChildCount(); i++)+ {+ var node = this.m_polyNodes.Childs()[i];+ if (node.m_endtype === ClipperLib.EndType.etClosedPolygon)+ this.m_destPolys.push(node.m_polygon);+ }+ return;+ }+ //see offset_triginometry3.svg in the documentation folder ...+ if (this.MiterLimit > 2)+ this.m_miterLim = 2 / (this.MiterLimit * this.MiterLimit);+ else+ this.m_miterLim = 0.5;+ var y;+ if (this.ArcTolerance <= 0)+ y = ClipperLib.ClipperOffset.def_arc_tolerance;+ else if (this.ArcTolerance > Math.abs(delta) * ClipperLib.ClipperOffset.def_arc_tolerance)+ y = Math.abs(delta) * ClipperLib.ClipperOffset.def_arc_tolerance;+ else+ y = this.ArcTolerance;+ //see offset_triginometry2.svg in the documentation folder ...+ var steps = 3.14159265358979 / Math.acos(1 - y / Math.abs(delta));+ this.m_sin = Math.sin(ClipperLib.ClipperOffset.two_pi / steps);+ this.m_cos = Math.cos(ClipperLib.ClipperOffset.two_pi / steps);+ this.m_StepsPerRad = steps / ClipperLib.ClipperOffset.two_pi;+ if (delta < 0)+ this.m_sin = -this.m_sin;+ //this.m_destPolys.set_Capacity(this.m_polyNodes.ChildCount * 2);+ for (var i = 0; i < this.m_polyNodes.ChildCount(); i++)+ {+ var node = this.m_polyNodes.Childs()[i];+ this.m_srcPoly = node.m_polygon;+ var len = this.m_srcPoly.length;+ if (len === 0 || (delta <= 0 && (len < 3 || node.m_endtype !== ClipperLib.EndType.etClosedPolygon)))+ continue;+ this.m_destPoly = new Array();+ if (len === 1)+ {+ if (node.m_jointype === ClipperLib.JoinType.jtRound)+ {+ var X = 1,+ Y = 0;+ for (var j = 1; j <= steps; j++)+ {+ this.m_destPoly.push(new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].X + X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].Y + Y * delta)));+ var X2 = X;+ X = X * this.m_cos - this.m_sin * Y;+ Y = X2 * this.m_sin + Y * this.m_cos;+ }+ }+ else+ {+ var X = -1,+ Y = -1;+ for (var j = 0; j < 4; ++j)+ {+ this.m_destPoly.push(new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].X + X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].Y + Y * delta)));+ if (X < 0)+ X = 1;+ else if (Y < 0)+ Y = 1;+ else+ X = -1;+ }+ }+ this.m_destPolys.push(this.m_destPoly);+ continue;+ }+ //build m_normals ...+ this.m_normals.length = 0;+ //this.m_normals.set_Capacity(len);+ for (var j = 0; j < len - 1; j++)+ this.m_normals.push(ClipperLib.ClipperOffset.GetUnitNormal(this.m_srcPoly[j], this.m_srcPoly[j + 1]));+ if (node.m_endtype === ClipperLib.EndType.etClosedLine || node.m_endtype === ClipperLib.EndType.etClosedPolygon)+ this.m_normals.push(ClipperLib.ClipperOffset.GetUnitNormal(this.m_srcPoly[len - 1], this.m_srcPoly[0]));+ else+ this.m_normals.push(new ClipperLib.DoublePoint1(this.m_normals[len - 2]));+ if (node.m_endtype === ClipperLib.EndType.etClosedPolygon)+ {+ var k = len - 1;+ for (var j = 0; j < len; j++)+ k = this.OffsetPoint(j, k, node.m_jointype);+ this.m_destPolys.push(this.m_destPoly);+ }+ else if (node.m_endtype === ClipperLib.EndType.etClosedLine)+ {+ var k = len - 1;+ for (var j = 0; j < len; j++)+ k = this.OffsetPoint(j, k, node.m_jointype);+ this.m_destPolys.push(this.m_destPoly);+ this.m_destPoly = new Array();+ //re-build m_normals ...+ var n = this.m_normals[len - 1];+ for (var j = len - 1; j > 0; j--)+ this.m_normals[j] = new ClipperLib.DoublePoint2(-this.m_normals[j - 1].X, -this.m_normals[j - 1].Y);+ this.m_normals[0] = new ClipperLib.DoublePoint2(-n.X, -n.Y);+ k = 0;+ for (var j = len - 1; j >= 0; j--)+ k = this.OffsetPoint(j, k, node.m_jointype);+ this.m_destPolys.push(this.m_destPoly);+ }+ else+ {+ var k = 0;+ for (var j = 1; j < len - 1; ++j)+ k = this.OffsetPoint(j, k, node.m_jointype);+ var pt1;+ if (node.m_endtype === ClipperLib.EndType.etOpenButt)+ {+ var j = len - 1;+ pt1 = new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_normals[j].X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_normals[j].Y * delta));+ this.m_destPoly.push(pt1);+ pt1 = new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X - this.m_normals[j].X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y - this.m_normals[j].Y * delta));+ this.m_destPoly.push(pt1);+ }+ else+ {+ var j = len - 1;+ k = len - 2;+ this.m_sinA = 0;+ this.m_normals[j] = new ClipperLib.DoublePoint2(-this.m_normals[j].X, -this.m_normals[j].Y);+ if (node.m_endtype === ClipperLib.EndType.etOpenSquare)+ this.DoSquare(j, k);+ else+ this.DoRound(j, k);+ }+ //re-build m_normals ...+ for (var j = len - 1; j > 0; j--)+ this.m_normals[j] = new ClipperLib.DoublePoint2(-this.m_normals[j - 1].X, -this.m_normals[j - 1].Y);+ this.m_normals[0] = new ClipperLib.DoublePoint2(-this.m_normals[1].X, -this.m_normals[1].Y);+ k = len - 1;+ for (var j = k - 1; j > 0; --j)+ k = this.OffsetPoint(j, k, node.m_jointype);+ if (node.m_endtype === ClipperLib.EndType.etOpenButt)+ {+ pt1 = new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].X - this.m_normals[0].X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].Y - this.m_normals[0].Y * delta));+ this.m_destPoly.push(pt1);+ pt1 = new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].X + this.m_normals[0].X * delta), ClipperLib.ClipperOffset.Round(this.m_srcPoly[0].Y + this.m_normals[0].Y * delta));+ this.m_destPoly.push(pt1);+ }+ else+ {+ k = 1;+ this.m_sinA = 0;+ if (node.m_endtype === ClipperLib.EndType.etOpenSquare)+ this.DoSquare(0, 1);+ else+ this.DoRound(0, 1);+ }+ this.m_destPolys.push(this.m_destPoly);+ }+ }+ };++ ClipperLib.ClipperOffset.prototype.Execute = function ()+ {+ var a = arguments,+ ispolytree = a[0] instanceof ClipperLib.PolyTree;+ if (!ispolytree) // function (solution, delta)+ {+ var solution = a[0],+ delta = a[1];+ ClipperLib.Clear(solution);+ this.FixOrientations();+ this.DoOffset(delta);+ //now clean up 'corners' ...+ var clpr = new ClipperLib.Clipper(0);+ clpr.AddPaths(this.m_destPolys, ClipperLib.PolyType.ptSubject, true);+ if (delta > 0)+ {+ clpr.Execute(ClipperLib.ClipType.ctUnion, solution, ClipperLib.PolyFillType.pftPositive, ClipperLib.PolyFillType.pftPositive);+ }+ else+ {+ var r = ClipperLib.Clipper.GetBounds(this.m_destPolys);+ var outer = new ClipperLib.Path();+ outer.push(new ClipperLib.IntPoint2(r.left - 10, r.bottom + 10));+ outer.push(new ClipperLib.IntPoint2(r.right + 10, r.bottom + 10));+ outer.push(new ClipperLib.IntPoint2(r.right + 10, r.top - 10));+ outer.push(new ClipperLib.IntPoint2(r.left - 10, r.top - 10));+ clpr.AddPath(outer, ClipperLib.PolyType.ptSubject, true);+ clpr.ReverseSolution = true;+ clpr.Execute(ClipperLib.ClipType.ctUnion, solution, ClipperLib.PolyFillType.pftNegative, ClipperLib.PolyFillType.pftNegative);+ if (solution.length > 0)+ solution.splice(0, 1);+ }+ //console.log(JSON.stringify(solution));+ }+ else // function (polytree, delta)+ {+ var solution = a[0],+ delta = a[1];+ solution.Clear();+ this.FixOrientations();+ this.DoOffset(delta);+ //now clean up 'corners' ...+ var clpr = new ClipperLib.Clipper(0);+ clpr.AddPaths(this.m_destPolys, ClipperLib.PolyType.ptSubject, true);+ if (delta > 0)+ {+ clpr.Execute(ClipperLib.ClipType.ctUnion, solution, ClipperLib.PolyFillType.pftPositive, ClipperLib.PolyFillType.pftPositive);+ }+ else+ {+ var r = ClipperLib.Clipper.GetBounds(this.m_destPolys);+ var outer = new ClipperLib.Path();+ outer.push(new ClipperLib.IntPoint2(r.left - 10, r.bottom + 10));+ outer.push(new ClipperLib.IntPoint2(r.right + 10, r.bottom + 10));+ outer.push(new ClipperLib.IntPoint2(r.right + 10, r.top - 10));+ outer.push(new ClipperLib.IntPoint2(r.left - 10, r.top - 10));+ clpr.AddPath(outer, ClipperLib.PolyType.ptSubject, true);+ clpr.ReverseSolution = true;+ clpr.Execute(ClipperLib.ClipType.ctUnion, solution, ClipperLib.PolyFillType.pftNegative, ClipperLib.PolyFillType.pftNegative);+ //remove the outer PolyNode rectangle ...+ if (solution.ChildCount() === 1 && solution.Childs()[0].ChildCount() > 0)+ {+ var outerNode = solution.Childs()[0];+ //solution.Childs.set_Capacity(outerNode.ChildCount);+ solution.Childs()[0] = outerNode.Childs()[0];+ solution.Childs()[0].m_Parent = solution;+ for (var i = 1; i < outerNode.ChildCount(); i++)+ solution.AddChild(outerNode.Childs()[i]);+ }+ else+ solution.Clear();+ }+ }+ };++ ClipperLib.ClipperOffset.prototype.OffsetPoint = function (j, k, jointype)+ {+ //cross product ...+ this.m_sinA = (this.m_normals[k].X * this.m_normals[j].Y - this.m_normals[j].X * this.m_normals[k].Y);++ if (Math.abs(this.m_sinA * this.m_delta) < 1.0)+ {+ //dot product ...+ var cosA = (this.m_normals[k].X * this.m_normals[j].X + this.m_normals[j].Y * this.m_normals[k].Y);+ if (cosA > 0) // angle ==> 0 degrees+ {+ this.m_destPoly.push(new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_normals[k].X * this.m_delta),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_normals[k].Y * this.m_delta)));+ return k;+ }+ //else angle ==> 180 degrees+ }+ else if (this.m_sinA > 1)+ this.m_sinA = 1.0;+ else if (this.m_sinA < -1)+ this.m_sinA = -1.0;+ if (this.m_sinA * this.m_delta < 0)+ {+ this.m_destPoly.push(new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_normals[k].X * this.m_delta),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_normals[k].Y * this.m_delta)));+ this.m_destPoly.push(new ClipperLib.IntPoint1(this.m_srcPoly[j]));+ this.m_destPoly.push(new ClipperLib.IntPoint2(ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_normals[j].X * this.m_delta),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_normals[j].Y * this.m_delta)));+ }+ else+ switch (jointype)+ {+ case ClipperLib.JoinType.jtMiter:+ {+ var r = 1 + (this.m_normals[j].X * this.m_normals[k].X + this.m_normals[j].Y * this.m_normals[k].Y);+ if (r >= this.m_miterLim)+ this.DoMiter(j, k, r);+ else+ this.DoSquare(j, k);+ break;+ }+ case ClipperLib.JoinType.jtSquare:+ this.DoSquare(j, k);+ break;+ case ClipperLib.JoinType.jtRound:+ this.DoRound(j, k);+ break;+ }+ k = j;+ return k;+ };++ ClipperLib.ClipperOffset.prototype.DoSquare = function (j, k)+ {+ var dx = Math.tan(Math.atan2(this.m_sinA,+ this.m_normals[k].X * this.m_normals[j].X + this.m_normals[k].Y * this.m_normals[j].Y) / 4);+ this.m_destPoly.push(new ClipperLib.IntPoint2(+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_delta * (this.m_normals[k].X - this.m_normals[k].Y * dx)),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_delta * (this.m_normals[k].Y + this.m_normals[k].X * dx))));+ this.m_destPoly.push(new ClipperLib.IntPoint2(+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_delta * (this.m_normals[j].X + this.m_normals[j].Y * dx)),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_delta * (this.m_normals[j].Y - this.m_normals[j].X * dx))));+ };++ ClipperLib.ClipperOffset.prototype.DoMiter = function (j, k, r)+ {+ var q = this.m_delta / r;+ this.m_destPoly.push(new ClipperLib.IntPoint2(+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + (this.m_normals[k].X + this.m_normals[j].X) * q),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + (this.m_normals[k].Y + this.m_normals[j].Y) * q)));+ };++ ClipperLib.ClipperOffset.prototype.DoRound = function (j, k)+ {+ var a = Math.atan2(this.m_sinA,+ this.m_normals[k].X * this.m_normals[j].X + this.m_normals[k].Y * this.m_normals[j].Y);++ var steps = Math.max(ClipperLib.Cast_Int32(ClipperLib.ClipperOffset.Round(this.m_StepsPerRad * Math.abs(a))), 1);++ var X = this.m_normals[k].X,+ Y = this.m_normals[k].Y,+ X2;+ for (var i = 0; i < steps; ++i)+ {+ this.m_destPoly.push(new ClipperLib.IntPoint2(+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + X * this.m_delta),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + Y * this.m_delta)));+ X2 = X;+ X = X * this.m_cos - this.m_sin * Y;+ Y = X2 * this.m_sin + Y * this.m_cos;+ }+ this.m_destPoly.push(new ClipperLib.IntPoint2(+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].X + this.m_normals[j].X * this.m_delta),+ ClipperLib.ClipperOffset.Round(this.m_srcPoly[j].Y + this.m_normals[j].Y * this.m_delta)));+ };++ ClipperLib.Error = function (message)+ {+ try+ {+ throw new Error(message);+ }+ catch (err)+ {+ alert(err.message);+ }+ };++ // ---------------------------------------------++ // JS extension by Timo 2013+ ClipperLib.JS = {};++ ClipperLib.JS.AreaOfPolygon = function (poly, scale)+ {+ if (!scale) scale = 1;+ return ClipperLib.Clipper.Area(poly) / (scale * scale);+ };++ ClipperLib.JS.AreaOfPolygons = function (poly, scale)+ {+ if (!scale) scale = 1;+ var area = 0;+ for (var i = 0; i < poly.length; i++)+ {+ area += ClipperLib.Clipper.Area(poly[i]);+ }+ return area / (scale * scale);+ };++ ClipperLib.JS.BoundsOfPath = function (path, scale)+ {+ return ClipperLib.JS.BoundsOfPaths([path], scale);+ };++ ClipperLib.JS.BoundsOfPaths = function (paths, scale)+ {+ if (!scale) scale = 1;+ var bounds = ClipperLib.Clipper.GetBounds(paths);+ bounds.left /= scale;+ bounds.bottom /= scale;+ bounds.right /= scale;+ bounds.top /= scale;+ return bounds;+ };++ // Clean() joins vertices that are too near each other+ // and causes distortion to offsetted polygons without cleaning+ ClipperLib.JS.Clean = function (polygon, delta)+ {+ if (!(polygon instanceof Array)) return [];+ var isPolygons = polygon[0] instanceof Array;+ var polygon = ClipperLib.JS.Clone(polygon);+ if (typeof delta !== "number" || delta === null)+ {+ ClipperLib.Error("Delta is not a number in Clean().");+ return polygon;+ }+ if (polygon.length === 0 || (polygon.length === 1 && polygon[0].length === 0) || delta < 0) return polygon;+ if (!isPolygons) polygon = [polygon];+ var k_length = polygon.length;+ var len, poly, result, d, p, j, i;+ var results = [];+ for (var k = 0; k < k_length; k++)+ {+ poly = polygon[k];+ len = poly.length;+ if (len === 0) continue;+ else if (len < 3)+ {+ result = poly;+ results.push(result);+ continue;+ }+ result = poly;+ d = delta * delta;+ //d = Math.floor(c_delta * c_delta);+ p = poly[0];+ j = 1;+ for (i = 1; i < len; i++)+ {+ if ((poly[i].X - p.X) * (poly[i].X - p.X) ++ (poly[i].Y - p.Y) * (poly[i].Y - p.Y) <= d)+ continue;+ result[j] = poly[i];+ p = poly[i];+ j++;+ }+ p = poly[j - 1];+ if ((poly[0].X - p.X) * (poly[0].X - p.X) ++ (poly[0].Y - p.Y) * (poly[0].Y - p.Y) <= d)+ j--;+ if (j < len)+ result.splice(j, len - j);+ if (result.length) results.push(result);+ }+ if (!isPolygons && results.length) results = results[0];+ else if (!isPolygons && results.length === 0) results = [];+ else if (isPolygons && results.length === 0) results = [+ []+ ];+ return results;+ }+ // Make deep copy of Polygons or Polygon+ // so that also IntPoint objects are cloned and not only referenced+ // This should be the fastest way+ ClipperLib.JS.Clone = function (polygon)+ {+ if (!(polygon instanceof Array)) return [];+ if (polygon.length === 0) return [];+ else if (polygon.length === 1 && polygon[0].length === 0) return [+ []+ ];+ var isPolygons = polygon[0] instanceof Array;+ if (!isPolygons) polygon = [polygon];+ var len = polygon.length,+ plen, i, j, result;+ var results = new Array(len);+ for (i = 0; i < len; i++)+ {+ plen = polygon[i].length;+ result = new Array(plen);+ for (j = 0; j < plen; j++)+ {+ result[j] = {+ X: polygon[i][j].X,+ Y: polygon[i][j].Y+ };++ }+ results[i] = result;+ }+ if (!isPolygons) results = results[0];+ return results;+ };++ // Removes points that doesn't affect much to the visual appearance.+ // If middle point is at or under certain distance (tolerance) of the line segment between+ // start and end point, the middle point is removed.+ ClipperLib.JS.Lighten = function (polygon, tolerance)+ {+ if (!(polygon instanceof Array)) return [];+ if (typeof tolerance !== "number" || tolerance === null)+ {+ ClipperLib.Error("Tolerance is not a number in Lighten().")+ return ClipperLib.JS.Clone(polygon);+ }+ if (polygon.length === 0 || (polygon.length === 1 && polygon[0].length === 0) || tolerance < 0)+ {+ return ClipperLib.JS.Clone(polygon);+ }+ var isPolygons = polygon[0] instanceof Array;+ if (!isPolygons) polygon = [polygon];+ var i, j, poly, k, poly2, plen, A, B, P, d, rem, addlast;+ var bxax, byay, l, ax, ay;+ var len = polygon.length;+ var toleranceSq = tolerance * tolerance;+ var results = [];+ for (i = 0; i < len; i++)+ {+ poly = polygon[i];+ plen = poly.length;+ if (plen === 0) continue;+ for (k = 0; k < 1000000; k++) // could be forever loop, but wiser to restrict max repeat count+ {+ poly2 = [];+ plen = poly.length;+ // the first have to added to the end, if first and last are not the same+ // this way we ensure that also the actual last point can be removed if needed+ if (poly[plen - 1].X !== poly[0].X || poly[plen - 1].Y !== poly[0].Y)+ {+ addlast = 1;+ poly.push(+ {+ X: poly[0].X,+ Y: poly[0].Y+ });+ plen = poly.length;+ }+ else addlast = 0;+ rem = []; // Indexes of removed points+ for (j = 0; j < plen - 2; j++)+ {+ A = poly[j]; // Start point of line segment+ P = poly[j + 1]; // Middle point. This is the one to be removed.+ B = poly[j + 2]; // End point of line segment+ ax = A.X;+ ay = A.Y;+ bxax = B.X - ax;+ byay = B.Y - ay;+ if (bxax !== 0 || byay !== 0) // To avoid Nan, when A==P && P==B. And to avoid peaks (A==B && A!=P), which have lenght, but not area.+ {+ l = ((P.X - ax) * bxax + (P.Y - ay) * byay) / (bxax * bxax + byay * byay);+ if (l > 1)+ {+ ax = B.X;+ ay = B.Y;+ }+ else if (l > 0)+ {+ ax += bxax * l;+ ay += byay * l;+ }+ }+ bxax = P.X - ax;+ byay = P.Y - ay;+ d = bxax * bxax + byay * byay;+ if (d <= toleranceSq)+ {+ rem[j + 1] = 1;+ j++; // when removed, transfer the pointer to the next one+ }+ }+ // add all unremoved points to poly2+ poly2.push(+ {+ X: poly[0].X,+ Y: poly[0].Y+ });+ for (j = 1; j < plen - 1; j++)+ if (!rem[j]) poly2.push(+ {+ X: poly[j].X,+ Y: poly[j].Y+ });+ poly2.push(+ {+ X: poly[plen - 1].X,+ Y: poly[plen - 1].Y+ });+ // if the first point was added to the end, remove it+ if (addlast) poly.pop();+ // break, if there was not anymore removed points+ if (!rem.length) break;+ // else continue looping using poly2, to check if there are points to remove+ else poly = poly2;+ }+ plen = poly2.length;+ // remove duplicate from end, if needed+ if (poly2[plen - 1].X === poly2[0].X && poly2[plen - 1].Y === poly2[0].Y)+ {+ poly2.pop();+ }+ if (poly2.length > 2) // to avoid two-point-polygons+ results.push(poly2);+ }+ if (!isPolygons)+ {+ results = results[0];+ }+ if (typeof (results) === "undefined")+ {+ results = [];+ }+ return results;+ }++ ClipperLib.JS.PerimeterOfPath = function (path, closed, scale)+ {+ if (typeof (path) === "undefined") return 0;+ var sqrt = Math.sqrt;+ var perimeter = 0.0;+ var p1, p2, p1x = 0.0,+ p1y = 0.0,+ p2x = 0.0,+ p2y = 0.0;+ var j = path.length;+ if (j < 2) return 0;+ if (closed)+ {+ path[j] = path[0];+ j++;+ }+ while (--j)+ {+ p1 = path[j];+ p1x = p1.X;+ p1y = p1.Y;+ p2 = path[j - 1];+ p2x = p2.X;+ p2y = p2.Y;+ perimeter += sqrt((p1x - p2x) * (p1x - p2x) + (p1y - p2y) * (p1y - p2y));+ }+ if (closed) path.pop();+ return perimeter / scale;+ };++ ClipperLib.JS.PerimeterOfPaths = function (paths, closed, scale)+ {+ if (!scale) scale = 1;+ var perimeter = 0;+ for (var i = 0; i < paths.length; i++)+ {+ perimeter += ClipperLib.JS.PerimeterOfPath(paths[i], closed, scale);+ }+ return perimeter;+ };++ ClipperLib.JS.ScaleDownPath = function (path, scale)+ {+ var i, p;+ if (!scale) scale = 1;+ i = path.length;+ while (i--)+ {+ p = path[i];+ p.X = p.X / scale;+ p.Y = p.Y / scale;+ }+ };++ ClipperLib.JS.ScaleDownPaths = function (paths, scale)+ {+ var i, j, p;+ if (!scale) scale = 1;+ i = paths.length;+ while (i--)+ {+ j = paths[i].length;+ while (j--)+ {+ p = paths[i][j];+ p.X = p.X / scale;+ p.Y = p.Y / scale;+ }+ }+ };++ ClipperLib.JS.ScaleUpPath = function (path, scale)+ {+ var i, p, round = Math.round;+ if (!scale) scale = 1;+ i = path.length;+ while (i--)+ {+ p = path[i];+ p.X = round(p.X * scale);+ p.Y = round(p.Y * scale);+ }+ };++ ClipperLib.JS.ScaleUpPaths = function (paths, scale)+ {+ var i, j, p, round = Math.round;+ if (!scale) scale = 1;+ i = paths.length;+ while (i--)+ {+ j = paths[i].length;+ while (j--)+ {+ p = paths[i][j];+ p.X = round(p.X * scale);+ p.Y = round(p.Y * scale);+ }+ }+ };++ /**+ * @constructor+ */+ ClipperLib.ExPolygons = function ()+ {+ return [];+ }+ /**+ * @constructor+ */+ ClipperLib.ExPolygon = function ()+ {+ this.outer = null;+ this.holes = null;+ };++ ClipperLib.JS.AddOuterPolyNodeToExPolygons = function (polynode, expolygons)+ {+ var ep = new ClipperLib.ExPolygon();+ ep.outer = polynode.Contour();+ var childs = polynode.Childs();+ var ilen = childs.length;+ ep.holes = new Array(ilen);+ var node, n, i, j, childs2, jlen;+ for (i = 0; i < ilen; i++)+ {+ node = childs[i];+ ep.holes[i] = node.Contour();+ //Add outer polygons contained by (nested within) holes ...+ for (j = 0, childs2 = node.Childs(), jlen = childs2.length; j < jlen; j++)+ {+ n = childs2[j];+ ClipperLib.JS.AddOuterPolyNodeToExPolygons(n, expolygons);+ }+ }+ expolygons.push(ep);+ };++ ClipperLib.JS.ExPolygonsToPaths = function (expolygons)+ {+ var a, i, alen, ilen;+ var paths = new ClipperLib.Paths();+ for (a = 0, alen = expolygons.length; a < alen; a++)+ {+ paths.push(expolygons[a].outer);+ for (i = 0, ilen = expolygons[a].holes.length; i < ilen; i++)+ {+ paths.push(expolygons[a].holes[i]);+ }+ }+ return paths;+ }+ ClipperLib.JS.PolyTreeToExPolygons = function (polytree)+ {+ var expolygons = new ClipperLib.ExPolygons();+ var node, i, childs, ilen;+ for (i = 0, childs = polytree.Childs(), ilen = childs.length; i < ilen; i++)+ {+ node = childs[i];+ ClipperLib.JS.AddOuterPolyNodeToExPolygons(node, expolygons);+ }+ return expolygons;+ };++})();diff --git a/store/agents/drone-pilot/template/tools/build.mjs b/store/agents/drone-pilot/template/tools/build.mjsnew file mode 100644index 000000000..421dbeb7f--- /dev/null+++ b/store/agents/drone-pilot/template/tools/build.mjs@@ -0,0 +1,31 @@+#!/usr/bin/env node+import {readFile,writeFile,mkdir,realpath,access} from 'node:fs/promises';+import {resolve,join,sep,dirname} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import {createHash} from 'node:crypto';+import {validateProject} from '../studio/project.mjs';+import {verifyFlightSource} from '../studio/log.mjs';+export async function readProject(workspace){+ const root=await realpath(workspace),source=await realpath(join(root,'flight/project.json'));+ if(!source.startsWith(root+sep)||!source.startsWith(join(root,'flight')+sep))throw new Error('Keep project source inside flight/.');+ const project=validateProject(JSON.parse(await readFile(source,'utf8')));delete project.revision;await verifyFlightSource(project);return project;+}+export async function toolsDirectory(){+ const candidates=[process.env.DRONE_DSH_DIR&&join(process.env.DRONE_DSH_DIR,'toolchain'),fileURLToPath(new URL('../../toolchain/',import.meta.url))].filter(Boolean);+ for(const path of candidates){try{await access(join(path,'node_modules/esbuild/lib/main.js'));return path;}catch{}}+ throw new Error('Vector build tools are missing. Run Drone Pilot setup, then use DRONE_DSH_DIR for an installed workspace.');+}+export async function buildFlight(workspace,{check=false,project:provided}={}){+ const root=resolve(workspace),project=provided?validateProject(provided):await readProject(root);delete project.revision;await verifyFlightSource(project);project.revision=createHash('sha256').update(JSON.stringify(project)).digest('hex');+ const tools=await toolsDirectory(),{build}=await import(pathToFileURL(join(tools,'node_modules/esbuild/lib/main.js')).href);+ const bundle=await build({entryPoints:[join(root,'studio/app.js')],bundle:true,write:false,format:'iife',minify:true,target:'es2022',legalComments:'eof',nodePaths:[join(tools,'node_modules')]});+ const [shell,css,icon,boost,jsbn]=await Promise.all(['shell.html','style.css','icon.svg','vendor/LICENSE-BOOST.txt','vendor/LICENSE-JSBN.txt'].map(n=>readFile(join(root,'studio',n),'utf8')));+ const licenses='Clipper 6.4.2 / JavaScript port 6.4.2.2\nCopyright Angus Johnson 2010–2017; Timo Kähkönen 2012–2017.\nUnmodified clipper-lib 6.4.2 from https://github.com/junmer/clipper-lib\n\n'+boost+'\n\nJSBN subset within Clipper:\n'+jsbn;+ const html=shell.replace('/* STUDIO_CSS */',()=>css).replace('<!-- VECTOR_ICON -->',()=>icon).replace('<!-- FAVICON -->',()=>`<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">`).replace('VECTOR_DATA',()=>JSON.stringify({project,licenses}).replace(/</g,'\\u003c')).replace('/* VECTOR_APP */',()=>bundle.outputFiles[0].text.replace(/<\/script/gi,'<\\/script'));+ if(provided)return {html,project};+ const target=join(root,'flight/index.html');+ if(check){if(await readFile(target,'utf8')!==html)throw new Error('Flight studio is stale. Run node tools/build.mjs.');}+ else{await writeFile(target,html);await mkdir(join(root,'.harness'),{recursive:true});await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'flight/index.html',summary:project.title+' · editable survey built; geometry, browser and delivery review pending',findings:[{severity:'info',kind:'review_pending',message:'A build does not establish a usable survey or verified flight. Review the actual inputs, outputs and model limitations.'}]},null,2)+'\n');}+ return {title:project.title,revision:project.revision,areas:project.areas.length};+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(JSON.stringify(await buildFlight(resolve(dirname(fileURLToPath(import.meta.url)),'..'),{check:process.argv.includes('--check')})));diff --git a/store/agents/drone-pilot/template/tools/check.mjs b/store/agents/drone-pilot/template/tools/check.mjsindex a7c2f66eb..db4fb99a3 100644--- a/store/agents/drone-pilot/template/tools/check.mjs+++ b/store/agents/drone-pilot/template/tools/check.mjs@@ -1,75 +1,15 @@-const CONFIG = {"id":"drone-pilot","artifact":"flight/index.html"};-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.-import { readFile, mkdir, writeFile } from "node:fs/promises";-import { createHash } from "node:crypto";-import vm from "node:vm";-import { resolve, dirname } from "node:path";--const args = process.argv.slice(2),- i = args.indexOf("--seeds");-const count = i === -1 ? 32 : Number(args[i + 1]);-if (!Number.isInteger(count) || count < 1 || count > 1000)- throw new Error("--seeds must be an integer from 1 to 1000");-const artifact = resolve(CONFIG.artifact);-const html = await readFile(artifact, "utf8");-const script = html.match(- /<script id="harness-model">([\s\S]*?)<\/script>/,-)?.[1];-if (!script)- throw new Error(- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',- );-const expressions = {- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,-};-const expression = expressions[CONFIG.id];-const digest = (value) =>- createHash("sha256").update(JSON.stringify(value)).digest("hex");-const results = [];-for (let seed = 0; seed < count; seed++) {- const run = () =>- vm.runInNewContext(- `${script}\n${expression}`,- { SEED: String(seed) },- { timeout: 10000 },- );- try {- const first = run(),- second = run(),- signature = digest(first.state),- repeat = digest(second.state);- results.push({- seed,- ok: first.valid && signature === repeat,- signature,- metrics: first.metrics,- });- } catch (error) {- results.push({ seed, ok: false, error: error.message });- }+#!/usr/bin/env node+import {mkdir,writeFile} from 'node:fs/promises';+import {join,resolve,dirname} from 'node:path';+import {fileURLToPath} from 'node:url';+import {readProject} from './build.mjs';+import {planProject} from '../studio/project.mjs';+import {segmentWithin} from '../studio/geo.mjs';+import {report} from '../studio/formats.mjs';+export async function checkFlight(workspace){+ const plan=planProject(await readProject(workspace));+ for(const sortie of plan.sorties){if(sortie.seconds>plan.budgetSeconds+.001)throw new Error('A sortie exceeds its configured time budget.');for(let i=1;i<sortie.path.length;i++)if(!segmentWithin(plan.region,sortie.path[i-1],sortie.path[i]))throw new Error('A route crosses outside the flight region.');}+ const result={...report(plan),geometryChecks:'passed',scope:'Finite geometry, timing and source-data checks. Browser operation, exported-file review and any real flight remain separate evidence.'};+ await mkdir(join(workspace,'.harness'),{recursive:true});await writeFile(join(workspace,'.harness/survey-check.json'),JSON.stringify(result,null,2)+'\n');return result;}-const passed = results.filter((r) => r.ok).length;-const report = {- spec: 1,- harness: CONFIG.id,- artifact: CONFIG.artifact,- checkedAt: new Date().toISOString(),- modelChecks: { passed, total: count },- scope:- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",- results,-};-const out = resolve(".harness/model-check.json");-await mkdir(dirname(out), { recursive: true });-await writeFile(out, JSON.stringify(report, null, 2) + "\n");-console.log(- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,-);-console.log(report.scope);-if (passed !== count) process.exitCode = 1;+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(JSON.stringify(await checkFlight(resolve(dirname(fileURLToPath(import.meta.url)),'..'))));diff --git a/store/agents/drone-pilot/template/tools/export.mjs b/store/agents/drone-pilot/template/tools/export.mjsnew file mode 100644index 000000000..e29ac83dc--- /dev/null+++ b/store/agents/drone-pilot/template/tools/export.mjs@@ -0,0 +1,17 @@+#!/usr/bin/env node+import {mkdir,writeFile,readFile} from 'node:fs/promises';+import {join,resolve,dirname} from 'node:path';+import {fileURLToPath} from 'node:url';+import {readProject,buildFlight} from './build.mjs';+import {planProject,ASSUMPTIONS} from '../studio/project.mjs';+import {geoJSON,photoCSV,routeCSV,flightCSV,kml,report,reportHTML,mapSVG,slug} from '../studio/formats.mjs';+import {zipFiles} from '../studio/archive.mjs';+export async function exportFlight(workspace,output=join(workspace,'delivery')){+ await buildFlight(workspace);const p=await readProject(workspace),plan=planProject(p),html=await readFile(join(workspace,'flight/index.html'),'utf8');+ const payload=JSON.parse(html.match(/<script id="vector-data" type="application\/json">([\s\S]*?)<\/script>/)[1]);+ const files=[[slug(p.title)+'.vector.json',JSON.stringify(p,null,2)],['planner.html',html],['survey.geojson',JSON.stringify(geoJSON(plan),null,2)],['overlay.kml',kml(plan)],['site-map.svg',mapSVG(plan)],['planned-photos.csv',photoCSV(plan)],['planned-route.csv',routeCSV(plan)],['report.json',JSON.stringify(report(plan),null,2)],['report.html',reportHTML(plan)],['LICENSES.txt',payload.licenses],['README.md',`# ${p.title}\n\n${p.brief}\n\nOpen planner.html to edit offline. Keep the .vector.json source. Load survey.geojson in GIS or overlay.kml in a map viewer; KML is ground-clamped. CSV coordinates are longitude/latitude degrees, with explicit height above takeoff and nominal timing. Files are for planning and review, not aircraft upload. Print report.html to PDF.\n\n${ASSUMPTIONS}\n\nOriginal recorded CSV, if supplied, is retained unchanged with SHA-256 and explicit column/unit mapping. Event footprints do not prove image existence or quality.\n`]];+ if(p.log)files.push(['recorded-source.csv',p.log.raw],['recorded-normalized.csv',flightCSV(plan)]);+ await mkdir(output,{recursive:true});for(const [name,body]of files)await writeFile(join(output,name),body);await writeFile(join(output,slug(p.title)+'-field-kit.zip'),new Uint8Array(await zipFiles(files).arrayBuffer()));+ return {title:p.title,output,files:files.map(([name])=>name),photos:plan.photos.length,sorties:plan.sorties.length,coverage:plan.coverage};+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');console.log(JSON.stringify(await exportFlight(root,process.argv[2]?resolve(process.argv[2]):undefined)));}diff --git a/store/agents/drone-pilot/test/ACCEPTANCE.md b/store/agents/drone-pilot/test/ACCEPTANCE.mdnew file mode 100644index 000000000..e763b0fa1--- /dev/null+++ b/store/agents/drone-pilot/test/ACCEPTANCE.md@@ -0,0 +1,75 @@+# Vector acceptance — 2026-09-20++This release replaces the starter canyon with an editable field-survey planner and recorded-data+workflow. Old canyon code and the original logo/icon remain in the repository. Store listing is+restored for this rebuild. No real flight, customer trial or installed-agent prompt completion is+claimed by these authored fixtures.++## Local evidence++- `node --test test/*.test.mjs`: geometry, camera/capture budgets, three site shapes, split runs,+ explicit infeasibility, coordinate limits, undo, CSV quoting/units/time/missing data, original+ source consistency, package setup/doctor, source saves/conflicts/history and picker boundaries.+- `test/browser.mjs`: actual Chrome edits (vertex drag, locked geometry, undo/redo, camera settings,+ sampled direction comparison and individual capture inspection), save, concurrent agent/browser+ drafts, supplied GeoJSON, drawn exclusion, explicit CSV mapping, recorded-sample inspector,+ UTF-8 BOM and SHA-256 preservation, kit download, offline reopening/editing and 390px layout.+- `test/acceptance.mjs`: all six delivered offline planners reopened in Chrome with no page errors.+ Three original briefs and three targeted revisions; the approved geometry hashes remain equal.+- `test/verify-delivery.py`: independent GEOS/Shapely 2.0.7 boundary insets/exclusions, complete route+ containment, route distance, home returns, footprint union coverage; stdlib readers validate+ exported GeoJSON geometry, CSV column/order/values, KML, ZIP contents and retained original CSV.+ Geometry containment tolerance is 3 mm for Clipper/GEOS offset and rounding differences.+- Normal setup and doctor passed on this Mac. Harness's source conformance check passed.+ All 416 CLI Store/conformance tests passed after restoring required credits for this package+ and Voxel Worlds. Shared model/viewer checks passed. Generated artifacts, branding and catalog+ validate. CI also runs the package/browser/six-delivery/independent-reader checks on Linux.+- Printable reports were rendered by Chrome to A4 and visually reviewed via Poppler page images.+ The report contains a real SVG map, calculations, assumptions, source provenance and page labels.+ Mobile navigation, report pagination and cross-runtime coordinate comparison bugs found during+ review were corrected.++| Authored brief | Captures before → after | Sorties before → after | Targeted revision | Preserved geometry |+| --- | ---: | ---: | --- | --- |+| Alder Orchard | 336 → 406 | 2 → 2 | Lower height, rotate runs, expand margin | Irrigation pond |+| Works Yard | 341 → 350 | 4 → 4 | Move equipment exclusion, reorient runs | Storage compound |+| Estuary Plots | 316 → 324 | 3 → 6 | Extend east plot, shorten usable time | West plot and reed bed |++All six have 100% ideal geometric footprint coverage of the supplied target, independently+recomputed. This is not a percentage of verified photographs, mapping quality or actual flight+coverage. The after-stage CSVs are explicitly synthetic test fixtures with intentional gaps,+missing capture state and a capture missing heading. One fixture's connected recorded segment+crosses the inset flight region; the report exposes that instead of concealing it.++Reproduce from the repository root:++```sh+sh store/agents/drone-pilot/toolchain/setup.sh+node --test store/agents/drone-pilot/test/*.test.mjs+node store/agents/drone-pilot/test/browser.mjs+node store/agents/drone-pilot/test/acceptance.mjs+python3 -m venv /tmp/vector-reader+/tmp/vector-reader/bin/pip install shapely==2.0.7 numpy==1.26.4+/tmp/vector-reader/bin/python store/agents/drone-pilot/test/verify-delivery.py work/experience-evidence/vector-acceptance+node store/agents/drone-pilot/test/showcase.mjs work/experience-evidence/vector-acceptance+```++The actual local release outputs are under `/private/tmp/vector-browser-release/` and+`/private/tmp/vector-acceptance-published/`; earlier intermediate runs remain separate. They are+not committed as artificial user data. The Store screenshots are captured from the real studio.++## Scope and remaining evidence++This is small-site level-ground/nadir planning, using supplied measurements and nominal time.+No terrain, obstacle, airspace, aircraft-dynamics, wind or navigation-error model is validated.+There is no photogrammetric reconstruction, executable mission, vehicle connection or command.+KML is ground-clamped; CSV heights are above takeoff. Split antimeridian sites before planning.++Shapely/CSV/XML import is independent software evidence, not a native QGIS/Google Earth or ground-+station trial. Chrome on this Mac and CI's browser are covered; other browsers, actual phones,+large input performance and real customer/installed-agent tasks remain unmeasured. The studio+supports manual CSV mapping; it does not claim automatic support for every vendor's binary log.++A 10-micrometer tolerance in normalized local positions handles native/browser Math.sin/cos+rounding. Original CSV bytes (valid UTF-8, including BOM), hash, events, time and row provenance+are retained. This numeric tolerance is not a claim of geographic measurement accuracy.diff --git a/store/agents/drone-pilot/test/acceptance.mjs b/store/agents/drone-pilot/test/acceptance.mjsnew file mode 100644index 000000000..382fcfc3c--- /dev/null+++ b/store/agents/drone-pilot/test/acceptance.mjs@@ -0,0 +1,38 @@+import {mkdir,mkdtemp,cp,writeFile,readFile} from 'node:fs/promises';+import {join,resolve} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import {createHash} from 'node:crypto';+import assert from 'node:assert/strict';+import {orchard,yard,estuary,recordedCSV,logMapping} from './fixtures.mjs';+import {planProject,clone} from '../template/studio/project.mjs';+import {importFlight} from '../template/studio/log.mjs';+import {exportFlight} from '../template/tools/export.mjs';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+const root=resolve(process.env.DRONE_ACCEPTANCE_ROOT||'work/experience-evidence/vector-acceptance');await mkdir(root,{recursive:true});+const browser=await chromium.launch({executablePath:await browserPath(),headless:true}),results=[];+process.env.DRONE_DSH_DIR=fileURLToPath(new URL('../',import.meta.url));+const hash=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');+try{+ for(const create of [orchard,yard,estuary]){+ const before=create(),after=clone(before);let revision;+ if(create===orchard){after.settings.angle=25;after.settings.height=50;after.settings.margin=8;revision='Lower capture height and rotate runs; increase margin while preserving the approved pond.';}+ if(create===yard){after.areas.find(a=>a.id==='plant').ring=after.areas.find(a=>a.id==='plant').ring.map(([x,y])=>[x+10,y+8]);after.settings.angle=0;revision='Move equipment exclusion and reorient capture runs; retain the locked storage compound.';}+ if(create===estuary){after.settings.usableMinutes=7;after.areas.find(a=>a.id==='east').ring[2]=[435,105];revision='Extend the east plot and shorten usable time; preserve west plot and reed bed.';}+ const approved=before.areas.filter(a=>a.locked).map(a=>({id:a.id,sha256:hash(a)}));+ for(const item of approved)assert.equal(hash(after.areas.find(a=>a.id===item.id)),item.sha256);+ const deliveries=[];+ for(const [stage,p]of [['before',before],['after',after]]){+ const directory=join(root,p.id,stage),workspace=join(directory,'workspace'),output=join(directory,'delivery');await mkdir(directory,{recursive:true});await cp(fileURLToPath(new URL('../template/',import.meta.url)),workspace,{recursive:true});+ if(stage==='after'){const planned=planProject(p);p.log=await importFlight(recordedCSV(planned),'synthetic-acceptance-flight.csv',logMapping,p.origin);}+ await writeFile(join(workspace,'flight/project.json'),JSON.stringify(p,null,2)+'\n');const delivery=await exportFlight(workspace,output),plan=planProject(p);+ await writeFile(join(directory,'geometry.json'),JSON.stringify({project:p,region:plan.region,target:plan.target,covered:plan.covered,gaps:plan.gaps,photos:plan.photos,sorties:plan.sorties,camera:plan.camera,area:plan.area,coverage:plan.coverage}));+ const page=await browser.newPage({viewport:{width:1536,height:980}}),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.context().setOffline(true);await page.goto(pathToFileURL(join(output,'planner.html')).href);await page.waitForFunction(()=>window.vector?.plan);assert.equal(await page.evaluate(()=>vector.plan.photos.length),delivery.photos);await page.screenshot({path:join(directory,'studio.png')});+ if(stage==='after'){await page.locator('#evidence-tab').click();await page.locator('#show-coverage').check();await page.screenshot({path:join(directory,'evidence.png')});}+ await page.goto(pathToFileURL(join(output,'report.html')).href);await page.screenshot({path:join(directory,'report.png'),fullPage:true});await page.pdf({path:join(directory,'report.pdf'),format:'A4',printBackground:true});assert.deepEqual(errors,[]);await page.close();+ deliveries.push({...delivery,stage,geometry:join(directory,'geometry.json'),screenshot:join(directory,'studio.png'),report:join(directory,'report.pdf')});+ }+ results.push({title:before.title,revision,approved,deliveries});+ }+ await writeFile(join(root,'acceptance.json'),JSON.stringify({scope:'Three authored geometry briefs and revisions. Logs are synthetic test fixtures, not flown missions or customer trials.',results},null,2));console.log(JSON.stringify({root,results}));+}finally{await browser.close();}diff --git a/store/agents/drone-pilot/test/browser.mjs b/store/agents/drone-pilot/test/browser.mjsnew file mode 100644index 000000000..084134ae7--- /dev/null+++ b/store/agents/drone-pilot/test/browser.mjs@@ -0,0 +1,45 @@+import {mkdtemp,cp,mkdir,writeFile,readFile} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import assert from 'node:assert/strict';+import {createHash} from 'node:crypto';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+import {createFlightViewer} from '../viewer/viewer.mjs';+import {buildFlight} from '../template/tools/build.mjs';+import {yard,siteGeoJSON,recordedCSV,logMapping} from './fixtures.mjs';+import {planProject} from '../template/studio/project.mjs';+const root=process.env.DRONE_QA_ROOT||await mkdtemp(join(tmpdir(),'vector-browser-')),workspace=join(root,'workspace');await mkdir(root,{recursive:true});await cp(fileURLToPath(new URL('../template/',import.meta.url)),workspace,{recursive:true});+process.env.DRONE_DSH_DIR=fileURLToPath(new URL('../',import.meta.url));await buildFlight(workspace);const server=await createFlightViewer(workspace);await new Promise(r=>server.listen(0,'127.0.0.1',r));+const url='http://127.0.0.1:'+server.address().port,browser=await chromium.launch({executablePath:await browserPath(),headless:true});const context=await browser.newContext({viewport:{width:1536,height:980},acceptDownloads:true}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));+const shot=async name=>{await page.screenshot({path:join(root,name+'.png')});};+async function downloaded(selector,name){const promise=page.waitForEvent('download');await page.locator(selector).click();const d=await promise,path=join(root,name||d.suggestedFilename());await d.saveAs(path);return path;}+const editedField=async(key,value)=>{const el=page.locator('[data-field="'+key+'"]');await el.fill(String(value));await el.press('Tab');};+try{+ await page.goto(url);await page.waitForFunction(()=>window.vector?.connected);assert.equal(await page.evaluate(()=>vector.plan.photos.length),336);await shot('01-studio');+ const approved=await page.evaluate(()=>JSON.stringify(vector.project.areas.find(a=>a.id==='pond')));+ await page.locator('[data-area="pond"]').click();assert.equal(await page.locator('[data-handle]').count(),0);await page.locator('[data-area="orchard"]').click();+ const vertex=await page.evaluate(()=>vector.screenPoint([420,0])),target=await page.evaluate(()=>vector.screenPoint([455,0]));await page.mouse.move(vertex.x,vertex.y);await page.mouse.down();await page.mouse.move(target.x,target.y,{steps:8});await page.mouse.up();await page.waitForFunction(()=>vector.project.areas[0].ring[1][0]>450);assert.equal(await page.evaluate(()=>JSON.stringify(vector.project.areas.find(a=>a.id==='pond'))),approved);+ await page.locator('#undo').click();assert.equal(await page.evaluate(()=>vector.project.areas[0].ring[1][0]),420);await page.locator('#redo').click();+ await editedField('height',65);assert.ok(await page.evaluate(()=>vector.plan.camera.gsdX)>1.7);+ await page.locator('#compare-angles').click();await page.locator('[data-angle="45"]').waitFor();await page.locator('[data-angle="45"]').click();assert.equal(await page.evaluate(()=>vector.project.settings.angle),45);assert.equal(await page.evaluate(()=>vector.project.settings.height),65);+ await page.locator('[data-sortie="1"]').click();await page.locator('#inspect-photo').fill('5');await page.locator('#inspect-photo').dispatchEvent('input');assert.match(await page.locator('#photo-details').textContent(),/Photo/);await shot('02-revised');+ await editedField('speed',30);await page.locator('#plan-error').waitFor({state:'visible'});assert.match(await page.locator('#plan-error').textContent(),/camera cannot capture/);assert.equal(await page.locator('#deliver').isDisabled(),true);await page.locator('#undo').click();assert.ok(await page.evaluate(()=>vector.plan));+ await page.locator('#save-source').click();await page.waitForFunction(()=>!vector.dirty);const saved=JSON.parse(await readFile(join(workspace,'flight/project.json'),'utf8'));assert.equal(saved.settings.height,65);+ await editedField('height',70);const external=structuredClone(saved);external.title='Agent revised orchard';await writeFile(join(workspace,'flight/project.json'),JSON.stringify(external));await buildFlight(workspace);await page.locator('#source-notice').waitFor({state:'visible'});+ const draft=await downloaded('#draft-keep','conflict-draft.vector.json');assert.equal(JSON.parse(await readFile(draft,'utf8')).settings.height,70);await downloaded('#source-load','before-source-restore.vector.json');await page.waitForFunction(()=>vector.project.title==='Agent revised orchard');assert.equal(await page.evaluate(()=>vector.project.settings.height),65);+ const site=join(root,'supplied-yard.geojson');await writeFile(site,JSON.stringify(siteGeoJSON(yard())));await page.locator('#import-geo').click();await page.locator('#geo-file').setInputFiles(site);await page.waitForFunction(()=>vector.project.title==='supplied-yard');assert.equal(await page.evaluate(()=>vector.project.areas.filter(a=>a.kind==='exclusion').length),2);assert.ok(await page.evaluate(()=>vector.plan));+ await page.locator('[data-tool="exclusion"]').click();for(const p of [[170,25],[192,25],[192,45],[170,45]]){const pos=await page.evaluate(p=>vector.screenPoint(p),p);await page.mouse.click(pos.x,pos.y);}await page.locator('#finish-draw').click();assert.equal(await page.evaluate(()=>vector.project.areas.length),4);await page.locator('#undo').click();assert.equal(await page.evaluate(()=>vector.project.areas.length),3);+ await page.locator('#save-source').click();await page.waitForFunction(()=>!vector.dirty);+ const project=await page.evaluate(()=>vector.project),flight=join(root,'synthetic-flight.csv');await writeFile(flight,'\uFEFF'+recordedCSV(planProject(project)));+ await page.locator('#evidence-tab').click();await page.locator('#log-file').setInputFiles(flight);await page.locator('#log-dialog').waitFor({state:'visible'});+ for(const [key,value] of Object.entries(logMapping)){const el=page.locator('[data-map="'+key+'"]');if(key==='homeElevation')await el.fill(String(value));else await el.selectOption(value);}+ await page.locator('#apply-log').click();await page.waitForFunction(()=>vector.evidence?.captureEvents>0);assert.equal(await page.evaluate(()=>vector.evidence.discontinuities),1);assert.equal(await page.evaluate(()=>vector.evidence.unmodeledCaptures),1);await page.locator('#inspect-log').fill('12');await page.locator('#inspect-log').dispatchEvent('input');assert.match(await page.locator('#sample-details').textContent(),/Row 14/);await page.locator('#show-coverage').check();await shot('03-recorded-evidence');+ await page.locator('#save-source').click();await page.waitForFunction(()=>!vector.dirty);+ assert.equal(await page.evaluate(()=>vector.project.log.sha256),createHash('sha256').update(await readFile(flight)).digest('hex'),'UTF-8 BOM and original source bytes survive browser import');+ await page.locator('#deliver').click();const kit=await downloaded('#export-kit','field-kit.zip'),geo=await downloaded('#export-geo','survey.geojson'),report=await downloaded('#export-report','report.html');await page.locator('#export-dialog [data-close]').click();+ const offlineFile=join(root,'planner.html');await writeFile(offlineFile,await page.evaluate(()=>vector.portable()));const offline=await context.newPage();offline.on('pageerror',e=>errors.push(e.message));await context.setOffline(true);await offline.goto(pathToFileURL(offlineFile).href);await offline.waitForFunction(()=>window.vector?.evidence);assert.equal(await offline.evaluate(()=>vector.project.log.name),'synthetic-flight.csv');await offline.locator('[data-field="height"]').fill('60');await offline.locator('[data-field="height"]').press('Tab');assert.equal(await offline.evaluate(()=>vector.project.settings.height),60);await offline.screenshot({path:join(root,'04-offline.png')});await context.setOffline(false);+ const mobile=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true}),phone=await mobile.newPage();await phone.goto(url);await phone.waitForFunction(()=>window.vector);await phone.screenshot({path:join(root,'05-mobile.png')});assert.equal(await phone.evaluate(()=>document.documentElement.scrollWidth<=390&&[...document.querySelectorAll("header nav button")].filter(b=>!b.hidden).every(b=>b.getBoundingClientRect().right<=390)),true);await mobile.close();+ assert.deepEqual(errors,[]);const result={root,workspace,kit,geo,report,browserErrors:errors,checks:['drag vertex and preserve locked exclusion','undo/redo','camera geometry and infeasible cadence','compare sampled directions','inspect individual planned captures','save source with history','retain both sides of an agent/browser conflict','import a supplied multi-layer GeoJSON site','draw a new exclusion','explicit CSV mapping and units','inspect recorded samples and missing data','export complete kit','reopen/edit offline planner','mobile layout without horizontal overflow']};await writeFile(join(root,'report.json'),JSON.stringify(result,null,2));console.log(JSON.stringify(result));+}catch(error){await page.screenshot({path:join(root,'failure.png')}).catch(()=>{});console.error('Browser status:',await page.locator('#status').textContent().catch(()=>''),'errors:',errors);throw error;}finally{await browser.close();server.closeAllConnections();await new Promise(r=>server.close(r));}diff --git a/store/agents/drone-pilot/test/fixtures.mjs b/store/agents/drone-pilot/test/fixtures.mjsnew file mode 100644index 000000000..431c51cf0--- /dev/null+++ b/store/agents/drone-pilot/test/fixtures.mjs@@ -0,0 +1,28 @@+import { toLonLat } from '../template/studio/geo.mjs';+export function orchard() {+ return { schema: 'vector/2', id: 'alder-orchard', title: 'Alder Orchard', brief: 'Example geometry, not a surveyed or authorized site. Document the orchard blocks, avoid the irrigation pond and keep a return allowance in each sortie. Replace the boundary and camera with measured values before doing your own planning.', origin: [-122.802, 38.466], home: [20,20], areas: [+ { id: 'orchard', name: 'Orchard blocks', kind: 'boundary', locked: false, ring: [[0,0],[420,0],[420,260],[280,300],[0,300]] },+ { id: 'pond', name: 'Irrigation pond', kind: 'exclusion', locked: true, ring: [[200,100],[265,95],[285,150],[240,175],[200,150]] }+ ], camera: { name: 'Example camera — enter your measured specs', sensorWidth: 13.2, sensorHeight: 8.8, focalLength: 8.8, imageWidth: 5472, imageHeight: 3648, minInterval: 1 }, settings: { height: 55, speed: 6, angle: 0, frontOverlap: .75, sideOverlap: .7, margin: 6, usableMinutes: 14, reservePercent: 20, climbSpeed: 3, descentSpeed: 2, turnSeconds: 3 } };+}+export function yard() {+ const p = orchard(); Object.assign(p, { id: 'works-yard', title: 'Works Yard', brief: 'Synthetic construction-site planning brief. Resolve the L-shaped work area and two equipment exclusions at a finer ground sampling distance. Capture requirements and camera geometry are editable examples.', origin: [151.09,-33.9], home: [12,12] });+ p.areas = [ { id: 'site', name: 'L-shaped works', kind: 'boundary', locked: false, ring: [[0,0],[260,0],[260,90],[145,90],[145,215],[0,215]] }, { id: 'stores', name: 'Storage compound', kind: 'exclusion', locked: true, ring: [[38,40],[82,40],[82,77],[38,77]] }, { id: 'plant', name: 'Equipment area', kind: 'exclusion', locked: false, ring: [[90,125],[120,125],[120,167],[90,167]] } ];+ Object.assign(p.settings, { height: 30, speed: 3, angle: 90, margin: 4, usableMinutes: 9 }); return p;+}+export function estuary() {+ const p = orchard(); Object.assign(p, { id: 'estuary-plots', title: 'Estuary Plots', brief: 'Synthetic restoration-site brief. Compare two connected plots, a diagonal survey direction and a large central exclusion. This is level-ground planning geometry; no terrain, water level or permissions have been supplied.', origin: [-9.18,38.69], home: [20,30] });+ p.areas = [ { id: 'west', name: 'West restoration plot', kind: 'boundary', locked: true, ring: [[0,0],[160,0],[220,70],[195,180],[90,235],[0,180]] }, { id: 'east', name: 'East restoration plot', kind: 'boundary', locked: false, ring: [[175,70],[350,35],[415,95],[390,245],[250,255],[180,180]] }, { id: 'reed', name: 'Reed bed', kind: 'exclusion', locked: true, ring: [[95,90],[125,55],[170,85],[155,130],[110,140]] } ];+ Object.assign(p.settings, { height: 45, speed: 4.5, angle: 32, margin: 5, usableMinutes: 10 }); return p;+}+export function siteGeoJSON(p) {+ return { type: 'FeatureCollection', features: p.areas.map(area => ({ type: 'Feature', properties: { name: area.name, kind: area.kind }, geometry: { type: 'Polygon', coordinates: [[...area.ring,area.ring[0]].map(point => toLonLat(p.origin,point))] } })) };+}+export function recordedCSV(plan) {+ // Deliberately synthetic evidence fixture, including a gap and missing camera data.+ const shots = plan.sorties[0].photos.filter((_,i) => i % 3 === 0).slice(0,32);+ return 'time_s,latitude,longitude,height_ft,heading_deg,battery_pct,capture\n' + shots.map((shot,i) => {+ const [lon,lat] = toLonLat(plan.project.origin,shot.point); return [i * 4 + (i > 10 ? 25 : 0), lat.toFixed(9), lon.toFixed(9), (plan.project.settings.height / .3048).toFixed(5), i === 3 ? '' : (90 - shot.heading + 360) % 360, (98 - i * .8).toFixed(1), i === 7 ? '' : i % 4 ? '1' : '0'].join(',');+ }).join('\n');+}+export const logMapping = { time:'time_s',timeUnit:'seconds',latitude:'latitude',longitude:'longitude',altitude:'height_ft',altitudeUnit:'feet',altitudeReference:'takeoff',homeElevation:0,heading:'heading_deg',battery:'battery_pct',capture:'capture' };diff --git a/store/agents/drone-pilot/test/geo.test.mjs b/store/agents/drone-pilot/test/geo.test.mjsnew file mode 100644index 000000000..26687af75--- /dev/null+++ b/store/agents/drone-pilot/test/geo.test.mjs@@ -0,0 +1,36 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import {toLocal,toLonLat,validateRing,regionArea,flightRegion,pointIn,segmentWithin,navigatorFor,transects,length,parseGeoJSON,union} from '../template/studio/geo.mjs';+const box=(x,y,w,h)=>[[x,y],[x+w,y],[x+w,y+h],[x,y+h]];+test('WGS 84 coordinates retain meter scale and round-trip near the equator, high latitudes and dateline',()=>{+ assert.ok(Math.abs(toLocal([0,0],[.001,0])[0]-111.31949079)<.0001);+ assert.ok(Math.abs(toLocal([0,0],[0,.001])[1]-110.57427582)<.0001);+ for(const origin of [[0,0],[-122.4,37.8],[179.999,51],[20,-70]])for(const point of [[0,0],[200,300],[-1200,600]]){+ const back=toLocal(origin,toLonLat(origin,point));assert.ok(Math.hypot(...back.map((n,i)=>n-point[i]))<.0001);+ }+ assert.throws(()=>toLocal([0,0],[180,0]),/5 km/);+});+test('insetting the boundary and expanding exclusions computes the actual remaining flight area',()=>{+ const region=flightRegion([box(0,0,100,100)],[box(40,40,20,20)],5);+ assert.equal(regionArea(region),7200);assert.equal(pointIn(region,[10,10]),true);assert.equal(pointIn(region,[2,2]),false);assert.equal(pointIn(region,[37,50]),false);+ assert.equal(segmentWithin(region,[10,50],[90,50]),false);assert.equal(segmentWithin(region,[10,10],[90,10]),true);+ assert.equal(regionArea(union([box(0,0,100,100),box(50,0,100,100)])),15000);+});+test('transits go around exclusions and never jump between disconnected flight areas',()=>{+ const region=flightRegion([box(0,0,100,100)],[box(40,40,20,20)],5),route=navigatorFor(region)([10,50],[90,50]);+ assert.ok(route.length>2);assert.ok(length(route)>80);for(let i=1;i<route.length;i++)assert.ok(segmentWithin(region,route[i-1],route[i]));+ const disconnected=flightRegion([box(0,0,20,20),box(40,0,20,20)],[],1);assert.equal(navigatorFor(disconnected)([10,10],[50,10]),null);+});+test('survey lines handle rotation and split correctly around a concave boundary and a hole',()=>{+ const boundary=validateRing([[0,0],[160,0],[160,100],[100,100],[100,60],[60,60],[60,100],[0,100]]),region=flightRegion([boundary],[box(15,15,20,20)],2);+ for(const angle of [0,37,90,171]){const rows=transects(region,12,angle);assert.ok(rows.length>5);for(const row of rows)assert.ok(segmentWithin(region,row.a,row.b),JSON.stringify(row));}+ assert.throws(()=>validateRing([[0,0],[100,100],[100,0],[0,100]]),/vertices|crosses/);+ assert.throws(()=>transects(region,.01,0),/0.5 m/);+});+test('GeoJSON import preserves user geometry and holes in the local meter frame',()=>{+ const origin=[106.6,10.8],outer=box(0,0,200,160),hole=box(50,50,30,20),coordinateRing=r=>[...r,r[0]].map(p=>toLonLat(origin,p));+ const source={type:'Feature',properties:{name:'Supplied site'},geometry:{type:'Polygon',coordinates:[coordinateRing(outer),coordinateRing(hole)]}},result=parseGeoJSON(source,origin);+ assert.equal(result.areas[0].name,'Supplied site');assert.equal(result.areas[0].holes.length,1);assert.ok(Math.abs(regionArea([result.areas[0].boundary])-32000)<.01);+ assert.throws(()=>parseGeoJSON({...source,crs:{name:'EPSG:3857'}}),/custom CRS/);+ assert.throws(()=>parseGeoJSON({type:'LineString',coordinates:[[0,0],[1,1]]}),/polygon/);+});diff --git a/store/agents/drone-pilot/test/log.test.mjs b/store/agents/drone-pilot/test/log.test.mjsnew file mode 100644index 000000000..8750c97e5--- /dev/null+++ b/store/agents/drone-pilot/test/log.test.mjs@@ -0,0 +1,37 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { parseCSV, importFlight, analyzeFlight, verifyFlightSource } from '../template/studio/log.mjs';+import { planProject, validateProject } from '../template/studio/project.mjs';+import { orchard, recordedCSV, logMapping } from './fixtures.mjs';++test('CSV respects quoting, CRLF, BOM and rejects malformed or duplicate columns', () => {+ assert.deepEqual(parseCSV('\uFEFFname,value\r\n"A, B","line\nnext"\r\n"quote""value",2\r\n').rows,[['A, B','line\nnext'],['quote"value','2']]);+ assert.throws(() => parseCSV('a,a\n1,2\n3,4'),/unique/); assert.throws(() => parseCSV('a,b\n"oops,1'),/unclosed/); assert.throws(() => parseCSV('a,b\n1,2,3\n1,2'),/same columns/);+});+test('explicit units, capture events, missing heading and gaps remain distinct in evidence', async () => {+ const plan = planProject(orchard()), raw = recordedCSV(plan), log = await importFlight(raw,'synthetic.csv',logMapping,plan.project.origin);+ assert.equal(log.raw,raw); assert.match(log.sha256,/^[a-f0-9]{64}$/); assert.ok(Math.abs(log.records[0].altitude-55)<.00001);+ const evidence = analyzeFlight(plan,log); assert.equal(evidence.discontinuities,1); assert.equal(evidence.paths.length,2); assert.equal(evidence.unknownCaptureSamples,1); assert.equal(evidence.unmodeledCaptures,1);+ assert.ok(evidence.coverage > 0 && evidence.coverage < plan.coverage); assert.ok(evidence.measuredDistance > 100); assert.ok(evidence.startBattery > evidence.endBattery);+ assert.doesNotThrow(() => validateProject({...plan.project,log}));+});+test('missing coordinates break the track; absent event/heading data never becomes observed coverage', async () => {+ const plan = planProject(orchard()), raw = 't,lat,lon\n0,38.466,-122.802\n1,,\n2,38.4661,-122.8019\n3,38.4662,-122.8018';+ const log = await importFlight(raw,'gaps.csv',{time:'t',timeUnit:'seconds',latitude:'lat',longitude:'lon'},plan.project.origin), evidence=analyzeFlight(plan,log);+ assert.equal(evidence.missingCoordinates,1); assert.equal(evidence.discontinuities,1); assert.equal(evidence.captureEvents,0); assert.equal(evidence.coverage,null); assert.equal(evidence.unknownCaptureSamples,3);+});+test('time interpretation and datum conversion are explicit, repeated or ambiguous time is rejected', async () => {+ const p = orchard(), raw='t,lat,lon,alt\n2026-08-12T10:00:00+02:00,38.466,-122.802,123\n2026-08-12T10:00:05+02:00,38.4661,-122.8019,125';+ const mapping={time:'t',timeUnit:'iso',latitude:'lat',longitude:'lon',altitude:'alt',altitudeUnit:'meters',altitudeReference:'amsl',homeElevation:100};+ const log=await importFlight(raw,'utc.csv',mapping,p.origin); assert.equal(log.startTime,'2026-08-12T08:00:00.000Z'); assert.equal(log.records[1].time,5); assert.equal(log.records[1].altitude,25);+ await assert.rejects(() => importFlight(raw.replaceAll('+02:00',''),'ambiguous.csv',mapping,p.origin),/timezone/);+ await assert.rejects(() => importFlight(raw.replace('10:00:05','10:00:00'),'repeated.csv',mapping,p.origin),/increasing/);+ await assert.rejects(() => importFlight(raw,'unknown.csv',{...mapping,homeElevation:undefined},p.origin),/takeoff elevation/);+ await assert.rejects(() => importFlight(raw.replaceAll('2026-08-12','2026-02-30'),'invalid-date.csv',mapping,p.origin),/calendar date/);+});+test('retained flight source tolerates browser math rounding but rejects edited evidence',async()=>{+ const p=orchard();p.log=await importFlight(recordedCSV(planProject(p)),'synthetic.csv',logMapping,p.origin);+ p.log.records[0].point[0]+=1e-9;await verifyFlightSource(p);+ p.log.records[0].point[0]+=1;await assert.rejects(()=>verifyFlightSource(p),/Recorded samples differ/);+ p.log=await importFlight(p.log.raw,p.log.name,p.log.mapping,p.origin);p.log.records[0].capture=true;await assert.rejects(()=>verifyFlightSource(p),/Recorded samples differ/);+});diff --git a/store/agents/drone-pilot/test/project.test.mjs b/store/agents/drone-pilot/test/project.test.mjsnew file mode 100644index 000000000..d901d8440--- /dev/null+++ b/store/agents/drone-pilot/test/project.test.mjs@@ -0,0 +1,45 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { planProject, cameraGeometry, validateProject, history, clone } from '../template/studio/project.mjs';+import { segmentWithin, distance, regionArea } from '../template/studio/geo.mjs';+import { orchard, yard, estuary } from './fixtures.mjs';++test('camera dimensions determine footprint, GSD and overlap; no nominal values are invented', () => {+ const p = orchard(), c = cameraGeometry(p);+ assert.equal(c.width,82.5); assert.equal(c.along,55); assert.equal(c.photoSpacing,13.75); assert.ok(Math.abs(c.gsdX - 1.5076754385964912) < 1e-9);+ p.settings.height *= 2; assert.equal(cameraGeometry(p).gsdX,c.gsdX * 2);+});+for (const create of [orchard,yard,estuary]) test(create.name + ': connected return routes, captures and bounded sorties cover the supplied geometry', () => {+ const plan = planProject(create()), s = plan.project.settings;+ assert.ok(plan.photos.length > 30); assert.ok(plan.sorties.length > 1); assert.ok(plan.coverage > .96);+ assert.equal(plan.photos.length,plan.sorties.reduce((n,s) => n + s.photos.length,0));+ assert.ok(Math.abs(regionArea(plan.covered) + regionArea(plan.gaps) - plan.area) < .1);+ for (const sortie of plan.sorties) {+ assert.ok(sortie.seconds <= plan.budgetSeconds + 1e-7); assert.ok(distance(sortie.path[0],plan.project.home) < .001); assert.ok(distance(sortie.path.at(-1),plan.project.home) < .001);+ for (let i = 1; i < sortie.path.length; i++) assert.ok(segmentWithin(plan.region,sortie.path[i-1],sortie.path[i]));+ for (let i = 1; i < sortie.photos.length; i++) assert.ok(sortie.photos[i].time - sortie.photos[i-1].time >= plan.project.camera.minInterval - 1e-7);+ const expected = sortie.distance / s.speed + s.height / s.climbSpeed + s.height / s.descentSpeed + sortie.legs.filter(l => l.kind === 'settle').reduce((n,l) => n+l.seconds,0);+ assert.ok(Math.abs(expected-sortie.seconds) < 1e-7);+ }+});+test('single survey runs can split across batteries without dropping photos', () => {+ const p = orchard(); p.home = [170,180]; p.settings.usableMinutes = 3; p.settings.reservePercent = 10;+ const plan = planProject(p); assert.ok(plan.sorties.length > 6); assert.equal(new Set(plan.photos.map(p => p.id)).size,plan.photos.length);+ assert.ok(plan.runs.some(run => new Set(run.photos.map(p => p.sortie)).size > 1));+});+test('infeasible capture cadence, takeoff, connectivity and time fail explicitly', () => {+ const a = orchard(); a.camera.minInterval = 20; assert.throws(() => planProject(a),/camera cannot capture/);+ const b = orchard(); b.home = [210,120]; assert.throws(() => planProject(b),/takeoff inside/);+ const c = orchard(); c.areas.push({id:'detached',name:'Detached',kind:'boundary',locked:false,ring:[[600,0],[700,0],[700,100],[600,100]]}); assert.throws(() => planProject(c),/disconnected/);+ const d = orchard(); d.settings.usableMinutes=1; assert.throws(() => planProject(d),/time budget/);+});+test('targeted revisions preserve locked geometry and history restores the complete source', () => {+ const p = orchard(), approved = JSON.stringify(p.areas[1]), h = history(p), next = clone(p);+ next.settings.angle=24; next.areas[0].ring[1][0]+=20; h.push(next);+ assert.equal(JSON.stringify(h.value.areas[1]),approved); assert.deepEqual(h.undo(),p); assert.deepEqual(h.redo(),next);+ next.areas[1].id=next.areas[0].id; assert.throws(() => validateProject(next),/unique/);+});+test('geographic export limits reject polar overflow and unsplit antimeridian geometry explicitly',()=>{+ const p=orchard();p.origin=[0,85];assert.throws(()=>validateProject(p),/85/);+ p.origin=[179.999,0];assert.throws(()=>validateProject(p),/180° meridian/);+});diff --git a/store/agents/drone-pilot/test/showcase.mjs b/store/agents/drone-pilot/test/showcase.mjsnew file mode 100644index 000000000..e3558caf9--- /dev/null+++ b/store/agents/drone-pilot/test/showcase.mjs@@ -0,0 +1,15 @@+import {mkdir,readFile} from 'node:fs/promises';+import {resolve,join} from 'node:path';+import {pathToFileURL} from 'node:url';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+const root=resolve(process.argv[2]||'work/experience-evidence/vector-acceptance'),output=resolve('store/showcase/drone-pilot');await mkdir(output,{recursive:true});+const browser=await chromium.launch({executablePath:await browserPath(),headless:true});+try{+ for(const [site,stage,name,mode]of [['alder-orchard','before','starter','capture'],['works-yard','before','works-yard','plan'],['estuary-plots','after','estuary-evidence','evidence']]){+ const page=await browser.newPage({viewport:{width:1536,height:980}});await page.goto(pathToFileURL(join(root,site,stage,'delivery/planner.html')).href);await page.waitForFunction(()=>window.vector?.plan);+ if(mode==='capture')await page.locator('[data-sortie="1"]').click();+ if(mode==='evidence'){await page.locator('#evidence-tab').click();await page.locator('#show-coverage').check();}+ await page.screenshot({path:join(output,name+'.jpg'),type:'jpeg',quality:90});await page.close();+ }+}finally{await browser.close();}diff --git a/store/agents/drone-pilot/test/toolchain.test.mjs b/store/agents/drone-pilot/test/toolchain.test.mjsindex fd40bfb5b..4b4f0b9b9 100644--- a/store/agents/drone-pilot/test/toolchain.test.mjs+++ b/store/agents/drone-pilot/test/toolchain.test.mjs@@ -28,11 +28,13 @@ test('every script the manifest names is in the folder and executable', () => {}})-test('setup installs nothing and succeeds quietly', () => {- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })+test('setup uses pinned local dependencies and resolves Node without asking for a system install', () => {+ const packages=JSON.parse(readFileSync(join(here,'toolchain/package.json'),'utf8'));+ assert.deepEqual(packages.dependencies,{'clipper-lib':'6.4.2','esbuild':'0.27.2','playwright-core':'1.63.0'});+ assert.match(readFileSync(join(here,'toolchain/install.sh'),'utf8'),/harness_node 20/);})-test('doctor says ok when sh is on PATH', () => {+test('doctor verifies the actual Node, build tools and local browser', () => {assert.equal(run(manifest.toolchain.doctor).code, 0)})@@ -43,8 +45,8 @@ test('init lays out a workspace and seeds a not-ready verdict', () => {assert.equal(readFileSync(join(ws, '.harness-initialized'), 'utf8'), `initialized by ${manifest.id}\n`)})-test('the manifest names a viewer package and an HTML artifact', () => {- assert.equal(manifest.viewer.use, 'autonomous/web-viewer')+test('the manifest names its source-saving viewer and an HTML artifact', () => {+ assert.equal(manifest.viewer.command, 'toolchain/viewer.sh')assert.deepEqual(manifest.viewer.artifactExtensions, ['.html'])})@@ -60,7 +62,8 @@ test('seed-verdict reflects whether a flight exists', () => {})-test('the manifest routes the actual nested artifact through the shared viewer', () => {- assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/?file=${artifact}')+test('the manifest opens the field studio and provides its installed tools to the agent', () => {+ assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/')+ assert.deepEqual(manifest.agent.env,{DRONE_DSH_DIR:'${dsh}'})assert.ok(manifest.workspace.marker.endsWith('/index.html'))})diff --git a/store/agents/drone-pilot/test/verify-delivery.py b/store/agents/drone-pilot/test/verify-delivery.pynew file mode 100644index 000000000..dcf2499b1--- /dev/null+++ b/store/agents/drone-pilot/test/verify-delivery.py@@ -0,0 +1,94 @@+"""Independent GEOS geometry, stdlib CSV/XML and archive verification.++Run with Shapely 2.0.7 and NumPy 1.26.4. No application geometry code is imported.+"""+import csv+import hashlib+import io+import json+import math+import sys+import zipfile+from pathlib import Path+from xml.etree import ElementTree as ET+from shapely.geometry import Polygon, Point, LineString, shape+from shapely.ops import unary_union++root = Path(sys.argv[1])+acceptance = json.loads((root / 'acceptance.json').read_text())+checks = []+for brief in acceptance['results']:+ for delivery in brief['deliveries']:+ directory = Path(delivery['output'])+ data = json.loads(Path(delivery['geometry']).read_text())+ project, settings = data['project'], data['project']['settings']+ boundaries = unary_union([Polygon(a['ring']) for a in project['areas'] if a['kind'] == 'boundary'])+ exclusions = unary_union([Polygon(a['ring']) for a in project['areas'] if a['kind'] == 'exclusion'])+ target = boundaries.difference(exclusions)+ region = boundaries.buffer(-settings['margin'], join_style=2, mitre_limit=2).difference(exclusions.buffer(settings['margin'], join_style=2, mitre_limit=2))+ assert region.is_valid and target.is_valid+ assert abs(target.area - data['area']) < .02+ # Clipper millimeter rounding and GEOS offset implementation can differ by+ # up to a millimeter near corners. The 3 mm tolerance is stated, not hidden.+ allowed = region.buffer(.003)+ for sortie in data['sorties']:+ route = LineString(sortie['path'])+ assert allowed.covers(route), ('route leaves region', brief['title'], delivery['stage'], sortie['id'])+ assert abs(route.length - sortie['distance']) < 1e-6+ assert Point(sortie['path'][0]).distance(Point(project['home'])) < 1e-8+ assert Point(sortie['path'][-1]).distance(Point(project['home'])) < 1e-8+ assert sortie['seconds'] <= settings['usableMinutes'] * 60 * (1 - settings['reservePercent'] / 100) + .001+ # Recompute all ideal footprints using the actual camera and run headings.+ camera = project['camera']+ width = settings['height'] * camera['sensorWidth'] / camera['focalLength']+ along = settings['height'] * camera['sensorHeight'] / camera['focalLength']+ footprints = []+ for photo in data['photos']:+ a = math.radians(photo['heading'])+ u, v = (math.cos(a), math.sin(a)), (-math.sin(a), math.cos(a))+ footprints.append(Polygon([(photo['point'][0] + u[0] * x * along / 2 + v[0] * y * width / 2,+ photo['point'][1] + u[1] * x * along / 2 + v[1] * y * width / 2)+ for x, y in [(-1,-1),(1,-1),(1,1),(-1,1)]]))+ coverage = target.intersection(unary_union(footprints)).area / target.area+ assert abs(coverage - data['coverage']) < .0001+ geo = json.loads((directory / 'survey.geojson').read_text())+ assert geo['type'] == 'FeatureCollection'+ for feature in geo['features']:+ geom = shape(feature['geometry'])+ assert geom.is_valid, (feature['properties']['name'], 'invalid exported GeoJSON')+ if not geom.is_empty:+ x0,y0,x1,y1 = geom.bounds+ assert -180 <= x0 <= x1 <= 180 and -85 <= y0 <= y1 <= 85+ photo_rows = list(csv.DictReader((directory / 'planned-photos.csv').open()))+ assert len(photo_rows) == len(data['photos'])+ by_id = {f['properties']['photo']: f for f in geo['features'] if f['properties']['kind'] == 'planned-photo'}+ for row in photo_rows:+ point = by_id[int(row['photo'])]['geometry']['coordinates']+ assert point == [float(row['longitude_deg']),float(row['latitude_deg'])]+ assert float(row['height_above_takeoff_m']) == settings['height']+ kml = ET.parse(directory / 'overlay.kml')+ ns = {'k':'http://www.opengis.net/kml/2.2'}+ lines = kml.findall('.//k:LineString',ns)+ assert len(lines) == len(data['sorties'])+ for line, sortie in zip(lines,data['sorties']):+ assert line.find('k:altitudeMode',ns).text == 'clampToGround'+ coords = [tuple(map(float,s.split(','))) for s in line.find('k:coordinates',ns).text.split()]+ assert len(coords) == len(sortie['path']) and all(c[2] == 0 for c in coords)+ archives = list(directory.glob('*-field-kit.zip'))+ assert len(archives) == 1+ with zipfile.ZipFile(archives[0]) as kit:+ assert kit.testzip() is None+ for name in delivery['files']:+ assert kit.read(name) == (directory / name).read_bytes()+ assert 'Tom Wu' in kit.read('LICENSES.txt').decode()+ if project.get('log'):+ raw = kit.read('recorded-source.csv')+ assert raw.decode() == project['log']['raw']+ assert hashlib.sha256(raw).hexdigest() == project['log']['sha256']+ normalized = list(csv.DictReader(io.StringIO(kit.read('recorded-normalized.csv').decode())))+ assert len(normalized) == len(project['log']['records'])+ assert sum(row['capture_event'] == '1' for row in normalized) == sum(row['capture'] is True for row in project['log']['records'])+ checks.append({'title':brief['title'],'stage':delivery['stage'],'routes':len(data['sorties']),'photos':len(data['photos']),'coverage':coverage,'geometryToleranceM':.003})+result = {'reader':'GEOS through Shapely 2.0.7; Python CSV, XML and ZIP','checks':checks,'limits':'This verifies supplied geometry and files. No native GIS/ground-station import, real flight, airspace, terrain or customer trial is claimed.'}+(root / 'independent-verification.json').write_text(json.dumps(result,indent=2)+'\n')+print(json.dumps(result))diff --git a/store/agents/drone-pilot/test/viewer.test.mjs b/store/agents/drone-pilot/test/viewer.test.mjsnew file mode 100644index 000000000..196e5507b--- /dev/null+++ b/store/agents/drone-pilot/test/viewer.test.mjs@@ -0,0 +1,44 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { once } from 'node:events';+import { get } from 'node:http';+import { mkdtemp,cp,readFile,writeFile,rm,mkdir,readdir,symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createFlightViewer } from '../viewer/viewer.mjs';+process.env.DRONE_DSH_DIR=fileURLToPath(new URL('../',import.meta.url));+const template=fileURLToPath(new URL('../template',import.meta.url));+async function fixture(fn){const dir=await mkdtemp(join(tmpdir(),'vector-viewer-')),ws=join(dir,'workspace'),home=join(dir,'home');await cp(template,ws,{recursive:true});await mkdir(join(home,'Downloads'),{recursive:true});const server=await createFlightViewer(ws,{home});server.listen(0,'127.0.0.1');await once(server,'listening');const base='http://127.0.0.1:'+server.address().port;try{await fn({ws,home,base});}finally{server.closeAllConnections();await new Promise(r=>server.close(r));await rm(dir,{recursive:true,force:true});}}+test('workspace save roundtrips real browser data, rebuilds output and rejects stale revisions',()=>fixture(async({ws,base})=>{+ const before=(await(await fetch(base+'/api/project')).json()).project,edited=structuredClone(before);edited.title='New survey title';+ const put=p=>fetch(base+'/api/project',{method:'PUT',headers:{origin:base,'content-type':'application/json','if-match':before.revision},body:JSON.stringify(p)});+ const response=await put(edited);assert.equal(response.status,200);const after=(await response.json()).project;assert.notEqual(after.revision,before.revision);+ assert.equal(JSON.parse(await readFile(join(ws,'flight/project.json'))).title,'New survey title');assert.match(await readFile(join(ws,'flight/index.html'),'utf8'),/New survey title/);+ const history=await readdir(join(ws,'.harness/history'));assert.equal(history.length,1);assert.equal(JSON.parse(await readFile(join(ws,'.harness/history',history[0]))).title,'Alder Orchard');+ const stale=await put(before);assert.equal(stale.status,409);assert.equal((await stale.json()).project.title,'New survey title');+}));+test('invalid project cannot overwrite the workspace and cross-origin writes are refused',()=>fixture(async({ws,base})=>{+ const before=await readFile(join(ws,'flight/project.json'),'utf8');+ for(const origin of ['https://foreign.example',undefined]){const r=await fetch(base+'/api/project',{method:'PUT',headers:{'content-type':'application/json',...(origin?{origin}:{})},body:'{}'});assert.equal(r.status,403);}+ const invalid=await fetch(base+'/api/project',{method:'PUT',headers:{origin:base,'content-type':'application/json'},body:'{}'});assert.equal(invalid.status,400);+ assert.equal(await readFile(join(ws,'flight/project.json'),'utf8'),before);+ const rejectedHost=await new Promise((resolve,reject)=>{get(base+'/api/project',{headers:{host:'foreign.example'}},response=>{response.resume();resolve(response.statusCode);}).on('error',reject);});+ assert.equal(rejectedHost,403);+ assert.equal((await fetch(base+'/files/.harness/verdict.json')).status,404);+}));+test('a failed build leaves source and previous preview intact; infeasible drafts can still be saved',()=>fixture(async({ws,base})=>{+ const before=(await(await fetch(base+'/api/project')).json()).project,source=await readFile(join(ws,'flight/project.json'),'utf8'),preview=await readFile(join(ws,'flight/index.html'),'utf8'),app=await readFile(join(ws,'studio/app.js'),'utf8');+ const put=p=>fetch(base+'/api/project',{method:'PUT',headers:{origin:base,'content-type':'application/json','if-match':before.revision},body:JSON.stringify(p)});+ await writeFile(join(ws,'studio/app.js'),'this is invalid JavaScript !');const bad=await put({...before,title:'Should not save'});assert.equal(bad.status,400);assert.equal(await readFile(join(ws,'flight/project.json'),'utf8'),source);assert.equal(await readFile(join(ws,'flight/index.html'),'utf8'),preview);+ await writeFile(join(ws,'studio/app.js'),app);const p=structuredClone(before);p.home=[-100,-100];assert.equal((await put(p)).status,200,'infeasible planning geometry remains editable and saveable');+}));+test('native picker opens only an explicitly selected visible home project',()=>fixture(async({ws,home,base})=>{+ const project=(await(await fetch(base+'/api/project')).json()).project,chosen=join(home,'Downloads','A survey.vector.json');await writeFile(chosen,JSON.stringify(project));+ const files=(await(await fetch(base+'/api/files')).json()).files;assert.equal(files.length,1);assert.equal(files[0].name,'A survey.vector.json');+ const open=path=>fetch(base+'/api/open',{method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify({path})});+ assert.equal((await open('"~/Downloads/A survey.vector.json"')).status,200);+ const secret=join(home,'.hidden');await mkdir(secret);await writeFile(join(secret,'private.vector.json'),JSON.stringify(project));assert.equal((await open(join(secret,'private.vector.json'))).status,400);+ await writeFile(join(ws,'outside.vector.json'),JSON.stringify(project));await symlink(join(ws,'outside.vector.json'),join(home,'Downloads','link.vector.json'));assert.equal((await open(join(home,'Downloads','link.vector.json'))).status,400);+ assert.equal(JSON.parse(await readFile(join(ws,'flight/project.json'))).title,'Alder Orchard','opening a file does not save over the workspace');+}));diff --git a/store/agents/drone-pilot/toolchain/browser.mjs b/store/agents/drone-pilot/toolchain/browser.mjsnew file mode 100644index 000000000..15e49bffa--- /dev/null+++ b/store/agents/drone-pilot/toolchain/browser.mjs@@ -0,0 +1,18 @@+import { access, writeFile, readFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';+const dir = fileURLToPath(new URL('.', import.meta.url));+export async function browserPath({ install = false } = {}) {+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);+ for (const path of candidates) { try { await access(path); return path; } catch {} }+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');+ const path = chromium.executablePath();+ try { await access(path); return path; } catch {}+ if (!install) throw new Error('Browser missing. Run the Drone Pilot setup script.');+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });+ await access(path); return path;+}+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);diff --git a/store/agents/drone-pilot/toolchain/doctor.sh b/store/agents/drone-pilot/toolchain/doctor.shindex b65fc95e4..c52d0a943 100755--- a/store/agents/drone-pilot/toolchain/doctor.sh+++ b/store/agents/drone-pilot/toolchain/doctor.sh@@ -1,3 +1,6 @@-#!/usr/bin/env bash-# Doctor: the flight is just a file served by the shared web-viewer; no extra runtime needed.-exit 0+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+cd "$here"+bash node.sh --input-type=module -e 'if(Number(process.versions.node.split(".")[0])<20)process.exit(1);await import("esbuild");await import("clipper-lib");console.log("ok Node and offline survey build tools")'+bash node.sh browser.mjs --checkdiff --git a/store/agents/drone-pilot/toolchain/init-workspace.sh b/store/agents/drone-pilot/toolchain/init-workspace.shindex 92190e081..1f29c733c 100755--- a/store/agents/drone-pilot/toolchain/init-workspace.sh+++ b/store/agents/drone-pilot/toolchain/init-workspace.sh@@ -1,12 +1,12 @@#!/bin/sh-# Harness copies the template before this runs. Preserve the user's design log on repeat calls.+# Preserve the person's source and design log on repeat initialization.set -euws="${1:-$PWD}"mkdir -p "$ws/flight" "$ws/.harness"if [ ! -f "$ws/flight/DESIGN.md" ]; then- printf '# Design log — Drone Pilot\n\nRecord date, USER or AI, decision, rationale, and whether it remains in the build.\n' > "$ws/flight/DESIGN.md"+ printf '# Survey decisions — Vector\n\nRecord date, USER or AI, supplied evidence, assumptions, decisions and preserved geometry.\n' > "$ws/flight/DESIGN.md"ficat > "$ws/.harness/verdict.json" <<JSON-{"spec":1,"ready":false,"summary":"Vector starter available — describe what you want to create","artifact":"flight/index.html","findings":[{"severity":"info","kind":"review_pending","message":"Starter provided; personalized changes need browser verification."}],"phases":[{"id":"build","name":"Build","state":"active"},{"id":"verify","name":"Verify","state":"pending"}],"updatedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}+{"spec":1,"ready":false,"summary":"Vector field studio — bring a site boundary and capture requirements","artifact":"flight/index.html","findings":[{"severity":"info","kind":"review_pending","message":"The orchard is example geometry. Supply a real boundary and camera, then review geometry, timing, exports and model limits."}],"phases":[{"id":"build","name":"Plan","state":"active"},{"id":"verify","name":"Verify","state":"pending"}]}JSONprintf 'initialized by %s\n' "${HARNESS_DSH:-autonomous/drone-pilot}" > "$ws/.harness-initialized"diff --git a/store/agents/drone-pilot/toolchain/install.sh b/store/agents/drone-pilot/toolchain/install.shnew file mode 100755index 000000000..eb3db98ef--- /dev/null+++ b/store/agents/drone-pilot/toolchain/install.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+cd "$here"+npm ci --ignore-scripts --no-audit --no-fund+node browser.mjs --install+node --input-type=module -e 'await import("esbuild");await import("clipper-lib");console.log("ok offline survey build tools")'diff --git a/store/agents/drone-pilot/toolchain/node.sh b/store/agents/drone-pilot/toolchain/node.shnew file mode 100755index 000000000..a527a9f1d--- /dev/null+++ b/store/agents/drone-pilot/toolchain/node.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+exec node "$@"diff --git a/store/agents/drone-pilot/toolchain/package-lock.json b/store/agents/drone-pilot/toolchain/package-lock.jsonnew file mode 100644index 000000000..3bda90eb7--- /dev/null+++ b/store/agents/drone-pilot/toolchain/package-lock.json@@ -0,0 +1,490 @@+{+ "name": "vector-survey-tools",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "vector-survey-tools",+ "dependencies": {+ "clipper-lib": "6.4.2",+ "esbuild": "0.27.2",+ "playwright-core": "1.63.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/clipper-lib": {+ "version": "6.4.2",+ "resolved": "https://registry.npmjs.org/clipper-lib/-/clipper-lib-6.4.2.tgz",+ "integrity": "sha512-knglhjQX5ihNj/XCIs6zCHrTemdvHY3LPZP9XB2nq2/3igyYMFueFXtfp84baJvEE+f8pO1ZS4UVeEgmLnAprQ==",+ "license": "BSL"+ },+ "node_modules/esbuild": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.2",+ "@esbuild/android-arm": "0.27.2",+ "@esbuild/android-arm64": "0.27.2",+ "@esbuild/android-x64": "0.27.2",+ "@esbuild/darwin-arm64": "0.27.2",+ "@esbuild/darwin-x64": "0.27.2",+ "@esbuild/freebsd-arm64": "0.27.2",+ "@esbuild/freebsd-x64": "0.27.2",+ "@esbuild/linux-arm": "0.27.2",+ "@esbuild/linux-arm64": "0.27.2",+ "@esbuild/linux-ia32": "0.27.2",+ "@esbuild/linux-loong64": "0.27.2",+ "@esbuild/linux-mips64el": "0.27.2",+ "@esbuild/linux-ppc64": "0.27.2",+ "@esbuild/linux-riscv64": "0.27.2",+ "@esbuild/linux-s390x": "0.27.2",+ "@esbuild/linux-x64": "0.27.2",+ "@esbuild/netbsd-arm64": "0.27.2",+ "@esbuild/netbsd-x64": "0.27.2",+ "@esbuild/openbsd-arm64": "0.27.2",+ "@esbuild/openbsd-x64": "0.27.2",+ "@esbuild/openharmony-arm64": "0.27.2",+ "@esbuild/sunos-x64": "0.27.2",+ "@esbuild/win32-arm64": "0.27.2",+ "@esbuild/win32-ia32": "0.27.2",+ "@esbuild/win32-x64": "0.27.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ }+ }+}diff --git a/store/agents/drone-pilot/toolchain/package.json b/store/agents/drone-pilot/toolchain/package.jsonnew file mode 100644index 000000000..92e14002a--- /dev/null+++ b/store/agents/drone-pilot/toolchain/package.json@@ -0,0 +1,10 @@+{+ "name": "vector-survey-tools",+ "private": true,+ "type": "module",+ "dependencies": {+ "clipper-lib": "6.4.2",+ "esbuild": "0.27.2",+ "playwright-core": "1.63.0"+ }+}diff --git a/store/agents/drone-pilot/toolchain/runtimes.sh b/store/agents/drone-pilot/toolchain/runtimes.shnew file mode 100755index 000000000..7223c78dc--- /dev/null+++ b/store/agents/drone-pilot/toolchain/runtimes.sh@@ -0,0 +1,192 @@+# shellcheck shell=bash+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never+# asked of the person who pressed Get.+#+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"+# has failed its install. So:+#+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release+# fetched into ~/.harness/runtime+# harness_venv DIR 3.12 [MIN [BELOW]]+# DIR is a venv on CPython 3.12, which uv downloads when the machine+# has none. A venv already there on a Python in [MIN, BELOW) is kept.+# harness_pip DIR PKG… install into that venv, through uv+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has+# no wheel for (pycairo on macOS)+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages+#+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache+# where it always does, which a venv does not depend on).+#+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package+# carries an identical copy (a package installs alone, so it cannot reach this one);+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.++HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"+export UV_PYTHON_INSTALL_DIR+HARNESS_UV_VERSION=0.12.15+HARNESS_MICROMAMBA_VERSION=2.9.0-0++_harness_platform() {+ case "$(uname -s)-$(uname -m)" in+ Darwin-arm64) echo darwin-arm64 ;;+ Darwin-x86_64) echo darwin-x64 ;;+ Linux-x86_64) echo linux-x64 ;;+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;+ *) return 1 ;;+ esac+}++_harness_sha256() {+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1+ else sha256sum "$1" | cut -d' ' -f1; fi+}++# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.+_harness_fetch() {+ local part="$2.part.$$"+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1+ fi+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1+ fi+ mv -f "$part" "$2"+}++_harness_node_at_least() {+ command -v node >/dev/null 2>&1 || return 1+ node -e '+ const [a, b = 0] = process.argv[1].split(".").map(Number)+ const [x, y] = process.versions.node.split(".").map(Number)+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)+ ' "$1" >/dev/null 2>&1+}++harness_node() {+ local min="${1:-18}" recorded saved="$PATH" own=0+ _harness_node_at_least "$min" && own=1+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true+ _harness_node_at_least "$min" && return 0+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"+ return 1+ fi+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"+ return 1+}++harness_uv() {+ local dir asset sum tmp+ command -v uv >/dev/null 2>&1 && return 0+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do+ [ -n "${HOME:-}" ] || break+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi+ done+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"+ if [ ! -x "$dir/uv" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;+ esac+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then+ rm -rf "$tmp"; return 1+ fi+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true+ rm -rf "$tmp"+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }+ fi+ PATH="$dir:$PATH"; export PATH+}++# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.+harness_venv() {+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"+ local min="${3:-$2}" below="${4:-}"+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '+import sys+at = lambda s: tuple(int(p) for p in s.split("."))+v = sys.version_info[:2]+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)+' "$min" "$below" 2>/dev/null; then+ echo "ok $("$dir/bin/python" --version) in $dir"+ return 0+ fi+ harness_uv || return 1+ echo " python $want in $dir (uv downloads it when this machine has none)"+ rm -rf "$dir"+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }+ echo "ok $("$dir/bin/python" --version) in $dir"+}++harness_pip() {+ local dir="${1:?harness_pip needs a venv}"+ shift+ harness_uv || return 1+ # uv's own error comes first; the miss line is last, so it is the line the store shows.+ uv pip install --quiet --python "$dir/bin/python" "$@" \+ || { echo "miss could not install $* into $dir"; return 1; }+}++harness_micromamba() {+ local dir asset sum+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"+ if [ ! -x "$dir/micromamba" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;+ esac+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }+ fi+ HARNESS_MICROMAMBA="$dir/micromamba"+ export HARNESS_MICROMAMBA+}++# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.+harness_conda_env() {+ local dir="${1:?harness_conda_env needs a directory}"+ shift+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac+ harness_micromamba || return 1+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \+ && [ -d "$dir/conda-meta" ] \+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }+}diff --git a/store/agents/drone-pilot/toolchain/setup.sh b/store/agents/drone-pilot/toolchain/setup.shindex 7cf64d63a..7ccd3d7a1 100755--- a/store/agents/drone-pilot/toolchain/setup.sh+++ b/store/agents/drone-pilot/toolchain/setup.sh@@ -1,3 +1,4 @@-#!/usr/bin/env bash-# Drone Pilot has no toolchain: everything is inline HTML + canvas physics. Nothing to install.-exit 0+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/install.sh"diff --git a/store/agents/drone-pilot/toolchain/viewer.sh b/store/agents/drone-pilot/toolchain/viewer.shnew file mode 100755index 000000000..c2afe7493--- /dev/null+++ b/store/agents/drone-pilot/toolchain/viewer.sh@@ -0,0 +1,4 @@+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/node.sh" "$here/../viewer/viewer.mjs"diff --git a/store/agents/drone-pilot/viewer/viewer.mjs b/store/agents/drone-pilot/viewer/viewer.mjsnew file mode 100644index 000000000..d8afec8e4--- /dev/null+++ b/store/agents/drone-pilot/viewer/viewer.mjs@@ -0,0 +1,79 @@+// Local workspace bridge: explicit project saves, optimistic revision checks, recoverable history.+import { createServer } from 'node:http';+import { readFile,writeFile,mkdir,rename,realpath,readdir,stat } from 'node:fs/promises';+import { homedir } from 'node:os';+import { resolve,join,dirname,basename,relative,sep,extname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createHash,randomUUID } from 'node:crypto';+import { readProject,buildFlight } from '../template/tools/build.mjs';+import { validateProject } from '../template/studio/project.mjs';+const hash=p=>createHash('sha256').update(JSON.stringify(p)).digest('hex');+export async function createFlightViewer(workspace,{home=homedir()}={}){+ const root=await realpath(workspace),homeRoot=await realpath(home);let saving=false;+ async function current(){const project=await readProject(root);delete project.revision;project.revision=hash(project);return project;}+ async function picked(raw){+ let name=String(raw??'').trim();if((name.startsWith('"')&&name.endsWith('"'))||(name.startsWith("'")&&name.endsWith("'")))name=name.slice(1,-1);+ if(name.startsWith('file://'))name=fileURLToPath(name);else name=name.replace(/\\ /g,' ');+ if(name==='~')name=homeRoot;else if(name.startsWith('~/'))name=join(homeRoot,name.slice(2));+ const actual=await realpath(resolve(name)),rel=relative(homeRoot,actual);+ if(rel.startsWith('..')||rel.split(sep).some(s=>s.startsWith('.')||s==='Library')||!actual.startsWith(homeRoot+sep))throw new Error('Choose a project inside your home folder, outside hidden folders and Library.');+ if(!actual.toLowerCase().endsWith('.vector.json'))throw new Error('Choose a saved .vector.json project.');+ const info=await stat(actual);if(!info.isFile()||info.size>8000000)throw new Error('Choose a project file smaller than 8 MB.');+ return validateProject(JSON.parse(await readFile(actual,'utf8')));+ }+ async function recent(){+ const files=[];+ for(const folder of ['Downloads','Desktop','Documents']){+ const path=join(homeRoot,folder);let list=[];try{list=await readdir(path,{withFileTypes:true});}catch{continue;}+ for(const entry of list.slice(0,3000)){if(!entry.isFile()||entry.name.startsWith('.')||!entry.name.toLowerCase().endsWith('.vector.json'))continue;const file=join(path,entry.name),info=await stat(file).catch(()=>null);if(info&&info.size<=8000000)files.push({name:entry.name,path:file,folder:'~/'+folder,mtime:info.mtimeMs});}+ }return files.sort((a,b)=>b.mtime-a.mtime).slice(0,30);+ }+ const server=createServer(async(req,res)=>{+ res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');+ const send=(code,body,type='application/json')=>{res.writeHead(code,{'content-type':type});res.end(type==='application/json'?JSON.stringify(body):body);};+ if(!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host??''))return send(403,{error:'Loopback only.'});+ const origin='http://'+req.headers.host;+ if((req.headers.origin&&req.headers.origin!==origin)||req.headers['sec-fetch-site']==='cross-site')return send(403,{error:'Same-origin requests only.'});+ let path;try{path=decodeURIComponent(new URL(req.url,origin).pathname);}catch{return send(400,{error:'Invalid path.'});}+ const mutation=['PUT','POST'].includes(req.method);+ if(mutation&&(req.headers.origin!==origin||!String(req.headers['content-type']).startsWith('application/json')))return send(403,{error:'Use the local studio to save or open a project.'});+ async function body(){let size=0;const chunks=[];for await(const chunk of req){size+=chunk.length;if(size>8000000)throw new Error('Request exceeds 8 MB.');chunks.push(chunk);}return JSON.parse(Buffer.concat(chunks));}+ try{+ if(path==='/api/project'&&req.method==='GET')return send(200,{project:await current()});+ if(path==='/api/project'&&req.method==='PUT'){+ if(saving)return send(409,{project:await current(),error:'Another save is in progress.'});+ const project=validateProject(await body());delete project.revision;saving=true;+ try{+ const before=await current();if(req.headers['if-match']!==before.revision)return send(409,{project:before,error:'The source changed. Keep both versions until you choose.'});+ const built=await buildFlight(root,{project});+ const latest=await current();if(latest.revision!==before.revision)return send(409,{project:latest,error:'The source changed during the build. Keep both versions until you choose.'});+ const history=join(root,'.harness/history');await mkdir(history,{recursive:true});+ await writeFile(join(history,new Date().toISOString().replace(/[:.]/g,'-')+'-'+randomUUID()+'.vector.json'),JSON.stringify(before));+ const target=join(root,'flight/project.json'),temporary=target+'.'+randomUUID()+'.tmp';+ await writeFile(temporary,JSON.stringify(project,null,2)+'\n');+ const preview=join(root,'flight/index.html'),previewTemporary=preview+'.'+randomUUID()+'.tmp';await writeFile(previewTemporary,built.html);+ await rename(temporary,target);await rename(previewTemporary,preview);+ await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'flight/index.html',summary:'Source saved; survey and delivery review pending'}));+ return send(200,{project:await current()});+ }finally{saving=false;}+ }+ if(path==='/api/files'&&req.method==='GET')return send(200,{files:await recent()});+ if(path==='/api/open'&&req.method==='POST')return send(200,{project:await picked((await body()).path)});+ if(req.method!=='GET'&&req.method!=='HEAD')return send(405,{error:'Method not allowed.'});+ if(path==='/'){const html=await readFile(join(root,'flight/index.html'));return send(200,req.method==='HEAD'?'':html,'text/html; charset=utf-8');}+ if(!path.startsWith('/files/'))return send(404,{error:'Not found.'});+ const name=path.slice(7);if(name.split(/[\\/]/).some(s=>s.startsWith('.')||s==='node_modules'))return send(404,{error:'Not found.'});+ const file=await realpath(join(root,name));if(!file.startsWith(root+sep)||relative(root,file).split(sep).some(s=>s.startsWith('.')))return send(404,{error:'Not found.'});+ const info=await stat(file);if(!info.isFile()||info.size>48000000)return send(413,{error:'File unavailable or too large.'});+ const mime={'.html':'text/html; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.pdf':'application/pdf','.json':'application/json','.ttf':'font/ttf'}[extname(file)]??'application/octet-stream';+ return send(200,req.method==='HEAD'?'':await readFile(file),mime==='application/json'?'application/json; charset=utf-8':mime);+ }catch(error){return send(400,{error:error.code==='ENOENT'?'That file is not available.':error.message});}+ });+ return server;+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){+ if(!process.env.HARNESS_WORKSPACE)throw new Error('HARNESS_WORKSPACE is required.');+ const port=Number(process.env.HARNESS_VIEWER_PORT);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('HARNESS_VIEWER_PORT must be valid.');+ const server=await createFlightViewer(process.env.HARNESS_WORKSPACE);server.listen(port,'127.0.0.1',()=>console.log(`[vector] http://127.0.0.1:${port}/`));+ for(const signal of ['SIGINT','SIGTERM'])process.once(signal,()=>{server.closeAllConnections();server.close();});+}diff --git a/store/agents/voxel-worlds/README.md b/store/agents/voxel-worlds/README.mdindex 1a25b2a66..f88eb6163 100644--- a/store/agents/voxel-worlds/README.md+++ b/store/agents/voxel-worlds/README.md@@ -49,3 +49,9 @@ for the tests actually performed and remaining validation.The original [logo and icon](brand/) are retained in the Store, studio and favicon. Three.js andruntime provenance are recorded in [PROVENANCE.md](PROVENANCE.md).++## Credit and stewardship++Original implementation and visual identity by OpenHarness contributors, maintained by+Autonomous under the [MIT license](LICENSE). Dependency notices and source references are in+[PROVENANCE.md](PROVENANCE.md). Report issues in the OpenHarness repository.diff --git a/store/showcase/drone-pilot/estuary-evidence.jpg b/store/showcase/drone-pilot/estuary-evidence.jpgnew file mode 100644index 000000000..9fe5eef94Binary files /dev/null and b/store/showcase/drone-pilot/estuary-evidence.jpg differdiff --git a/store/showcase/drone-pilot/starter.jpg b/store/showcase/drone-pilot/starter.jpgindex 0b2fad9fc..c2c8c860f 100644Binary files a/store/showcase/drone-pilot/starter.jpg and b/store/showcase/drone-pilot/starter.jpg differdiff --git a/store/showcase/drone-pilot/works-yard.jpg b/store/showcase/drone-pilot/works-yard.jpgnew file mode 100644index 000000000..13ab993c1Binary files /dev/null and b/store/showcase/drone-pilot/works-yard.jpg differdiff --git a/store/tools/build-experiences.mjs b/store/tools/build-experiences.mjsindex 9a2a618ca..88aa65c52 100644--- a/store/tools/build-experiences.mjs+++ b/store/tools/build-experiences.mjs@@ -7,6 +7,7 @@ import { buildArt } from "../agents/generative-art/template/tools/build.mjs";import { buildMusic } from "../agents/music-studio/template/tools/build.mjs";import { buildBrand } from "../agents/creative-direction/template/tools/build.mjs";import { buildWorld } from "../agents/voxel-worlds/template/tools/build.mjs";+import { buildFlight } from "../agents/drone-pilot/template/tools/build.mjs";const source = new URL("./experiences/", import.meta.url);export const experiences = [{@@ -62,7 +63,7 @@ export async function build({ check = false } = {}) {]);let drift = false;for (const exp of experiences) {- if (["generative-art", "music-studio", "creative-direction", "voxel-worlds"].includes(exp.id)) {+ if (["generative-art", "music-studio", "creative-direction", "voxel-worlds", "drone-pilot"].includes(exp.id)) {try {const packageRoot = new URL(`../agents/${exp.id}/`, import.meta.url);const icon = await readFile(new URL('brand/icon.svg', packageRoot), 'utf8');@@ -70,7 +71,7 @@ export async function build({ check = false } = {}) {if (check) {if (await readFile(studioIcon, 'utf8') !== icon) throw new Error(`${exp.id}: packaged studio icon is out of date.`);} else await writeFile(studioIcon, icon);- const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld }[exp.id];+ const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld, 'drone-pilot': buildFlight }[exp.id];await builder(fileURLToPath(new URL(`../agents/${exp.id}/template/`, import.meta.url)), { check });} catch (error) {if (!check) throw error;diff --git a/store/tools/experience-tests/browser.mjs b/store/tools/experience-tests/browser.mjsindex 4fc716816..ab88fc488 100644--- a/store/tools/experience-tests/browser.mjs+++ b/store/tools/experience-tests/browser.mjs@@ -109,6 +109,11 @@ async function shellRegression() {}async function one(exp) {+ if (exp.id === 'drone-pilot') {+ const result = execFileSync(process.execPath, [join(repo, 'store/agents/drone-pilot/test/browser.mjs')], { env: { ...process.env, DRONE_QA_ROOT: join(output, 'vector-browser') }, encoding: 'utf8', timeout: 180000 });+ results.push({name:'drone-pilot-studio',ok:true,output:result.trim()});+ return;+ }if (exp.id === 'voxel-worlds') {const result = execFileSync(process.execPath, [join(repo, 'store/agents/voxel-worlds/test/browser.mjs')], { env: { ...process.env, VOXEL_QA_ROOT: join(output, 'tidelands-browser') }, encoding: 'utf8', timeout: 180000 });results.push({ id: exp.id, ...JSON.parse(result.trim()) });diff --git a/work/DRONE-REBUILD.md b/work/DRONE-REBUILD.mdnew file mode 100644index 000000000..b86e0b2b3--- /dev/null+++ b/work/DRONE-REBUILD.md@@ -0,0 +1,29 @@+# Drone Pilot — field-survey rebuild++The implementation is complete and locally reviewed; publication is the next step. The old+canyon implementation remains under `store/tools/experiences/drone-pilot.*`. The rebuilt package+restores listing only for an editable planning/data/delivery workflow.++Vector accepts actual GeoJSON or drawn georeferenced boundaries, exclusions, takeoff and camera+measurements. It computes nominal footprints, capture cadence, connected routes and time-budgeted+sorties with returns. Users can edit and lock geometry, compare sampled directions, inspect+individual captures, undo, save source with conflict/history protection, and retain a portable kit.+Recorded CSV import requires explicit columns, units and time interpretation; preserves source+bytes/hash and missing-data boundaries; and estimates footprints only from supplied event flags,+height and heading. No vehicle connection, mission upload, terrain/airspace verification or+photogrammetry is claimed.++See [the acceptance record](../store/agents/drone-pilot/test/ACCEPTANCE.md). Key local evidence:+`/private/tmp/vector-browser-release/`, `/private/tmp/vector-acceptance-published/` and+`/private/tmp/vector-pdf-published/`. Three distinct sites and targeted revisions, six independent+GEOS/CSV/XML/ZIP checks, real Chrome UI and offline exports. Printed reports visually reviewed.+Tests exposed and fixed floating-point source-save mismatch, mobile navigation overflow and PDF+page splitting. Original UTF-8 CSV bytes (including BOM) are preserved and verified.++The required credit section was restored in Voxel Worlds while running the full Store tests;+no Voxel runtime change is included here. Source conformance and all 416 CLI Store/check tests pass.+Existing branding remains, with new actual Store screenshots. Publishing still needs the PR,+required CI, merge, catalog publication, public byte checks and normal install verification.++Next after Drone publication: Game Master, then Lab Bench. Keep each unlisted until its own+useful workflow and outputs are verified. User has authorized sequential rebuild and publication.diff --git a/work/FIVE-REBUILDS.md b/work/FIVE-REBUILDS.mdindex 6484466d1..a6e8694cf 100644--- a/work/FIVE-REBUILDS.md+++ b/work/FIVE-REBUILDS.md@@ -7,10 +7,10 @@ so the user can test it, then move to the next. Do not claim a subjective “wow1. **Creative Direction — published (#141).** A business brief and suppliedmaterials become an editable identity, coordinated launch assets, a responsive website and aportable brand guide. See [tested deliverables and remaining evidence](FORME-REBUILD.md).-2. **Voxel Worlds — rebuilt; publication in progress.** Named object editing, sculpting, source saves,+2. **Voxel Worlds — published (#146), normal Store install verified on this Mac.** Named object editing, sculpting, source saves,physical walking, VOX import and independent GLB/VOX/offline delivery. See[the acceptance evidence](../store/agents/voxel-worlds/test/ACCEPTANCE.md).-3. **Drone Pilot — pending.** Useful planning/analysis with actual inputs and explicit simulation+3. **Drone Pilot — in progress.** [Survey planning and post-flight evidence](DRONE-REBUILD.md), with actual inputs and explicit simulationboundaries. No claim that a simulation authorizes or validates a real flight.4. **Game Master — pending.** Create and revise original playable games, then deliver working builds.5. **Lab Bench — pending.** Analyze the person's observations with reproducible methods and outputs.diff --git a/work/SUPERPOWERS.md b/work/SUPERPOWERS.mdindex 7239f4114..c09bb7871 100644--- a/work/SUPERPOWERS.md+++ b/work/SUPERPOWERS.md@@ -12,7 +12,8 @@ trials with real user briefs are still outstanding; listing does not claim those**Next user direction:** improve the other five sequentially. Creative Direction has now beenrebuilt and relisted; see [FORME-REBUILD.md](FORME-REBUILD.md) and the-[sequential plan](FIVE-REBUILDS.md). Voxel Worlds is next. The original withdrawal table below+[sequential plan](FIVE-REBUILDS.md). Voxel Worlds is also rebuilt and published (#146);+Drone Pilot is in progress. The original withdrawal table belowis retained as history, not a description of the rebuilt Forme product.## Original review of our seven@@ -28,7 +29,7 @@ is retained as history, not a description of the rebuilt Forme product.| Lab Bench | Inspect one synthetic experiment | Cannot do useful analysis on the person's own observations | Withdraw; stop parallel development |All seven initially received `listed:false`. Art and Music have since been rebuilt and relisted-for user testing, followed by Creative Direction. The other four remain unlisted. Source, logos,+for user testing, followed by Creative Direction and Voxel Worlds. The other three remain unlisted. Source, logos,tests and workspaces stay intact.The shared web viewer remains available: it is infrastructure used by other harnesses.Other sessions' harnesses are outside this withdrawal.