From 6b64bfcb2f147297be8f3ae5ea6b467426c2f414 Mon Sep 17 00:00:00 2001 From: Stephen Frederick Date: Thu, 12 Nov 2026 18:49:40 -0500 Subject: [PATCH] Warn of a footprint that crosses a setback, with checkIntent and a drawing file's export intent `checkIntent(drawing, intent)` checks a drawing against what it is meant to hold to, given as data beside the drawing. Its first check is setbacks: ```ts const intent: Intent = { setbacks: [{ property: "lot", footprints: ["house"], distance: [25, 7.5, 20, 7.5] }], }; checkIntent(drawing, intent); ``` A setback names a property line and its footprints by their ids, as closed polylines of model space. `distance` is one setback for every side, or one for each side in the order of the property line's points. The check warns of: - `footprint-in-setback`: a footprint nearer a side than that side's setback, with `side`, `required` and `provided`. The distance is measured in drawing units, from the side itself, corner to corner, to the footprint's outline, and `bounds` is the box around the nearest points, larger on every side by the setback. - `footprint-off-property`: a footprint that is not wholly inside its property line, including one whose side leaves the lot and comes back through two of its corners, and one with a corner of the lot inside it. - `intent-unchecked`: a part of the intent that could not be checked, and why: an id that names no closed polyline, a field the intent does not have, distances that do not match the sides, or more points than the check takes. Distances are measured from the points as the drawing holds them, before the writers round them, and from the property line's first corner. The comparison allows for the error of the arithmetic only: 2^-44 of the largest coordinate, and never more than 0.0000005. Up to 100,000,000 drawing units from the origin, a footprint drawn on its setback line passes at any angle. A shortfall is reported when it is bigger than the tolerance plus twice the spacing of doubles at that distance, which is about 0.000000015 at 100,000,000. A property line or a footprint must be a simple outline, whose sides meet only at its corners. That is worked out exactly for the doubles the drawing holds, so a sharp corner is a corner. One that crosses or touches itself, such as a lot drawn around a hole, is reported as not checked. A point that repeats the one before it, or a last point that repeats the first, is the same corner. Each warning about a setback gives `item`, its path in the intent, such as `setbacks[0]`. Each outline is read once, and a call does at most 4,000,000 steps of work. No outline of more than 200,000 points is read, and a round lot of about 60,000 points with a four-corner footprint takes the whole budget. What goes past the budget is one warning for each setback, naming what was not checked and what took the most of the work. A call gives at most 200 warnings and then one that says it stopped. It never changes what `lint` reports or what `toDXF` writes, and it never throws on plain data. A drawing file may export `intent` beside its drawing. `tsdraft render` and `tsdraft dev` check it on each build and list the warnings in `diagnostics` after those of `inspectText`, without changing the exit code, and `timings.intent` gives the time the check took. A copy of tsdraft that has no `checkIntent`, or whose `checkIntent` throws, gives one `intent-unchecked` warning that says so. The example sheet's lot and residence now have the ids `lot` and `residence`, and the example exports the setbacks its residence keeps out of. https://github.com/Surfside-Software/tsdraft/blob/main/docs/intent.md describes it. Co-authored-by: Claude Opus 5.5 --- AGENTS.md | 20 + CHANGELOG.md | 21 + GUIDE.md | 24 +- README.md | 2 + cli/AGENTS.md | 5 + cli/src/state.ts | 35 +- cli/src/worker.ts | 56 ++- cli/test/fixtures/setback.ts | 14 + cli/test/render.test.ts | 76 ++++ docs/command.md | 21 +- docs/intent.md | 125 ++++++ examples/README.md | 9 + examples/site-plan.ts | 31 +- src/index.ts | 8 + src/inspect.ts | 6 +- src/intent.ts | 839 +++++++++++++++++++++++++++++++++++ test/intent.test.ts | 558 +++++++++++++++++++++++ 17 files changed, 1836 insertions(+), 14 deletions(-) create mode 100644 cli/test/fixtures/setback.ts create mode 100644 docs/intent.md create mode 100644 src/intent.ts create mode 100644 test/intent.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1345c54..d9ef137 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -128,6 +128,26 @@ inserts with `eachDrawn`. It must stay bounded: boxes are worked out once and found through a grid, and every box the grid looks at and every point a check reads count against one limit, which ends the checks with `text-check-capped` when it is reached. +- `checkIntent` in `src/intent.ts` checks a drawing against the intent given beside it: so + far, setbacks. It is not `lint` either, and its rules and type are its own. It finds + entities of model space by id, with `idKey`, and reads no layer's state. It takes any value + as the intent and never throws: a field it does not know, an id that names nothing or a + count that does not match is an `intent-unchecked` warning, never a pass with nothing said. + Unlike `lint`, it measures the points as the drawing holds them, not as written: rounding + the points and then the distance makes a footprint on its setback line warn, and hides a + real shortfall. It measures from the property line's first corner, and compares with one + tolerance, `toleranceOf`, for the arithmetic alone, never wider than the writers' rounding + moves a coordinate. A test of two outlines must hold when no side meets another exactly, + as on a turned lot: `contained` cuts a footprint's side at every corner of the lot within + the tolerance of it, and a corner of the lot inside the footprint puts it off the lot. It + takes only simple outlines, judged with `turn`, which is exact for the doubles held, and + refuses one that crosses or touches itself, such as a lot + with a hole. Each outline is read once and paid for before it is read, the search for its + sides that meet uses `grid` from `src/inspect.ts`, every point looked at counts against one + limit, what goes past it is one warning for each setback, and the warnings stop at a + number of their own. A warning names the part of the intent it is about + by `item`, a path such as `setbacks[0]`, so a later check of intent gets a field of + `Intent` of its own and adds no field to the warning. - AutoCAD sizes dashes on the paper in a viewport, so `toSVG` scales a pattern by the linetype scale over the viewport's scale there. `toSVG` draws a layout with `elements`, the walk it draws model space with, under a `Look` that says how wide and what color a pen is. diff --git a/CHANGELOG.md b/CHANGELOG.md index a8c9273..ef569d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ ## Unreleased +- `checkIntent(drawing, intent)` checks a drawing against what it is meant to hold to, given + as data beside it, and returns warnings. Its one check is setbacks: `intent.setbacks` names + a property line and its footprints by their ids, as closed polylines of model space, with + one setback for every side or one for each side in the order of the property line's points. + `footprint-in-setback` warns of a footprint nearer a side than its setback, with the `side`, + the `required` setback and the distance `provided`, measured in drawing units from the side + itself to the footprint's outline, from the points as the drawing holds them and with a + tolerance for the arithmetic alone. `footprint-off-property` warns of a footprint not wholly + inside its property line, and `intent-unchecked` says what part of the intent could not be + checked and why, such as an id that names nothing, a field it does not know or an outline + that crosses or touches itself, worked out exactly for the doubles held, so a lot with a + hole is not checked. A point that repeats the one before it is the same corner. Each warning + about a setback gives `item`, its path in the intent, such as `setbacks[0]`. The work and + the number of warnings are bounded. It never changes what `lint` reports or what `toDXF` + writes. [docs/intent.md](docs/intent.md) describes it. +- `tsdraft render` and `tsdraft dev` check a drawing file's export `intent` on each build and + put the warnings in `diagnostics` after those of `inspectText`, with `item`, `side`, + `required` and `provided` where they apply. They never change the exit code, and + `timings.intent` gives the time the check took. `schema` stays 3. The example sheet exports + the setbacks of its residence, and its lot and residence have the ids `lot` and + `residence`. - The dimension style `Standard`, which every R2018 DXF holds, names the text style `Standard`. It named none, and AutoCAD draws no text for a dimension in a style with no text style: once `Standard` was made current, a dimension a drafter drew in it with diff --git a/GUIDE.md b/GUIDE.md index 3cd3979..37e4758 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -76,6 +76,8 @@ and `_`, each used once in a drawing. A diagnostic about the entity carries the empty, fix each one, errors first. A warning whose rule starts with `text-` is about a text as it plots: it lies over another text, it runs past the border, cell or room it starts in, or it runs off the paper. See [Fitting text](#fitting-text-with-measuretext). + A `footprint-` warning says a building crosses a setback: see + [Checking intent](#checking-intent). 4. Look at the PNG at `outputs.png`, and at each sheet's in `outputs.layouts`. The JSON says whether the drawing breaks a rule. Only the picture shows whether it is the drawing you meant. When `outputs.png` is `null`, `outputs.pngError` says why, and `outputs.svg` is the @@ -156,7 +158,8 @@ until it is stopped, so start it in the background. where to read the fields of a title block. - `outputs.svg` and `outputs.png` are model space. `outputs.layouts` has a picture of each sheet as it plots. -- `diagnostics` is what `lint` found, and after it the warnings about text as it plots. An +- `diagnostics` is what `lint` found, and after it the warnings about text as it plots and + about [intent](#checking-intent). An error stops `toDXF` from writing the file. A warning does not. A `text-` warning has `bounds`, the box of the text on its picture, and `other`, the text it lies over or the closed polyline it runs past. For a text inside a block, `entity` is the insert, and @@ -247,6 +250,25 @@ keeping `drafting.ts` in a `lib` folder beside it. Change two import strings to Its parameters come first and every position is worked out from them. Its columns and line breaks are laid out with `measureText`. Its symbols are blocks, and so is its title block. +## Checking intent + +Export `intent` beside the drawing, and each build checks that every footprint keeps out of +its setbacks. It names closed polylines of model space by their ids: + +```ts +export const intent: Intent = { + setbacks: [{ property: "lot", footprints: ["house"], distance: [25, 7.5, 20, 7.5] }], +}; +``` + +`distance` is in drawing units: one setback for every side, or one for each side in the order +of the property line's points. For a `rect` drawn from the lot's front left corner, that is the +front, the right side, the rear and the left side. A `footprint-in-setback` warning gives the +`side`, its `required` setback and the distance `provided`. `intent-unchecked` means part of +the intent was not checked, and says why, such as an outline that crosses itself. +[docs/intent.md](https://github.com/Surfside-Software/tsdraft/blob/main/docs/intent.md) has +the rest. + ## Dimensions Define a dimension style, then dimension between two points: diff --git a/README.md b/README.md index 3216666..303a884 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,8 @@ lint(drawing, { version: "R12" }); // check a drawing against another version text plots with `measureText`, the warnings of `inspectText` about text that overlaps or leaves its border, what tsdraft escapes in text, and what AutoCAD does with it after a save. +- [Checks of intent](docs/intent.md) covers `checkIntent`, which warns of a + footprint that crosses a setback, and the `intent` a drawing file exports. - [The `tsdraft` command](docs/command.md) covers `render`, `dev`, the JSON they give, and what happens without the PNG renderer. diff --git a/cli/AGENTS.md b/cli/AGENTS.md index f1ba617..30a9920 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -43,6 +43,11 @@ a build or change the exit code, so a throw there gives no warnings. Each warning brings its own `bounds`, in its picture's coordinates: do not box it again with `aboutEntity`, which would give the box of a whole insert. +- When the drawing file exports `intent`, the worker runs the library's `checkIntent` after + `inspectText`, and puts its warnings last, under the same terms: no failed build, no change + to the exit code, and each warning's own `bounds`. When the copy of tsdraft the drawing + loaded has no `checkIntent`, or its `checkIntent` throws, the build gets one + `intent-unchecked` warning that says so, so an intent is never passed over without a word. - `render --view` draws one rectangle with `toSVG`'s `view`, with no margin, as `outputs.view`, and writes no other picture. `tsdraft dev` has no view: its server keeps only SVG strings and a worker ends after one build. A `Builder` passes the view to the diff --git a/cli/src/state.ts b/cli/src/state.ts index 9deff4c..c3d9aa8 100644 --- a/cli/src/state.ts +++ b/cli/src/state.ts @@ -1,6 +1,14 @@ // The JSON that `tsdraft render` prints and `tsdraft dev` serves as /state.json. Agents program // against it, so a change here is a change to the interface. -import type { Diagnostic, DxfVersion, Entity, PaperUnit, TextWarning, Units } from "tsdraft"; +import type { + Diagnostic, + DxfVersion, + Entity, + IntentWarning, + PaperUnit, + TextWarning, + Units, +} from "tsdraft"; /** The result of one build of a drawing file. */ export interface BuildState { @@ -46,8 +54,9 @@ export interface BuildState { readonly drawing: DrawingSummary | null; /** * What `lint` reports for the drawing, errors first, and after it what `inspectText` warns of - * in the text as it plots: a rule that starts with `text-`. When the file threw a - * `DrawingError`, as `toDXF` and the builder do, its diagnostics, without `kind` and + * in the text as it plots: a rule that starts with `text-`. Then, when the file has an export + * `intent`, what `checkIntent` warns of where the drawing does not hold to it. When the file + * threw a `DrawingError`, as `toDXF` and the builder do, its diagnostics, without `kind` and * `bounds`. When the build failed because the drawing could not be drawn even without what * `lint` reported, what `lint` reported, without `kind` and `bounds`. Otherwise empty when * the build failed. @@ -160,13 +169,29 @@ export interface PngFont { * plots, turned and justified, and of both texts when two overlap, in the coordinates of its * picture: pass it to `render --view`. `other` names the other text of an overlap, or the * closed polyline the text runs past, the same way. + * + * A warning of `checkIntent` has the rule `footprint-in-setback`, `footprint-off-property` or + * `intent-unchecked`, and `item`, the path in the export `intent` of what it is about, such as + * `setbacks[0]`, where lint's `item` is a path in the drawing. Its `entity` is the footprint, + * or the entity an id names, in model space, with that entity's `kind`, `layer`, `id` and + * `call`, and `other` is the property line. A footprint warning has + * `bounds` in drawing units: for `footprint-in-setback`, the box of the two points of the side + * and the footprint nearest each other, larger on every side by the setback, and for + * `footprint-off-property` the footprint's box. `footprint-in-setback` also gives `side`, + * `required` and `provided`. */ export interface BuildDiagnostic extends Omit { - readonly rule: Diagnostic["rule"] | TextWarning["rule"]; + readonly rule: Diagnostic["rule"] | TextWarning["rule"] | IntentWarning["rule"]; readonly kind?: Entity["kind"]; /** The box around the entity, in drawing units, worked out as `extents` is. */ readonly bounds?: Box; readonly other?: TextWarning["other"]; + /** The side of the property line, counted from 0 in the order of its points. */ + readonly side?: number; + /** The setback of that side, in drawing units. */ + readonly required?: number; + /** The least distance from that side to the footprint, in drawing units, as measured. */ + readonly provided?: number; } export interface Box { @@ -182,6 +207,8 @@ export interface Timings { readonly lint?: number; /** Looking at the text as it plots, for the warnings whose rule starts with `text-`. */ readonly inspect?: number; + /** Checking the drawing against the file's export `intent`, when it has one. */ + readonly intent?: number; readonly svg?: number; /** Rasterizing the PNG, when one was asked for. Not counted in `ms`. */ readonly png?: number; diff --git a/cli/src/worker.ts b/cli/src/worker.ts index 2c6b47f..2338940 100644 --- a/cli/src/worker.ts +++ b/cli/src/worker.ts @@ -22,6 +22,8 @@ import type { DimensionStyle, Drawing, Entity, + Intent, + IntentWarning, Layout, LinearDimension, PaperInfo, @@ -105,6 +107,7 @@ export interface WorkerResult { readonly load?: number; readonly lint?: number; readonly inspect?: number; + readonly intent?: number; readonly svg?: number; }; readonly drawing: DrawingSummary | null; @@ -155,6 +158,8 @@ interface Library { drawing: Drawing, options?: { drawNoPlot?: boolean; xrefs?: Readonly> }, ) => TextWarning[]; + /** Where the drawing does not hold to its intent. A copy of tsdraft from before it has none. */ + readonly checkIntent?: (drawing: Drawing, intent: Intent) => IntentWarning[]; /** What a viewport shows, and the papers. A copy of tsdraft from before layouts has neither. */ readonly viewportView?: (viewport: Viewport, paperUnits: PaperUnit, units: Units) => ViewportView; readonly PAPERS?: Readonly>; @@ -489,7 +494,13 @@ async function warm(library: string | null, deadline: number): Promise { } async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { - const timings: { load?: number; lint?: number; inspect?: number; svg?: number } = {}; + const timings: { + load?: number; + lint?: number; + inspect?: number; + intent?: number; + svg?: number; + } = {}; const fail = (error: BuildError, thrown?: unknown): WorkerResult => ({ ok: false, files: [...readFiles(file), ...missingFile(thrown)], @@ -509,10 +520,12 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise>; + let intent: unknown; try { const module = (await import(pathToFileURL(file).href)) as { default?: unknown; xrefs?: unknown; + intent?: unknown; }; let value = module.default; if (typeof value === "function") value = await (value as () => unknown)(); @@ -520,6 +533,7 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise>; + intent = module.intent; } catch (thrown) { timings.load = now() - t; return fail(describe(thrown, root), thrown); @@ -549,6 +563,11 @@ async function build({ file, root, drawNoPlot, view }: BuildRequest): Promise { + const kind = + warning.entity === undefined ? undefined : drawing.entities?.[warning.entity]?.kind; + return withPath(kind === undefined ? warning : { ...warning, kind }); + }); + } catch (thrown) { + const reason = thrown instanceof Error ? thrown.message : String(thrown); + return [ + { + rule: "intent-unchecked", + severity: "warning", + message: `checkIntent stopped with an error, so the export \`intent\` was not checked: ${reason}`, + }, + ]; + } +} + /** Gives the file of a diagnostic's `call` as a path, as `error.file` is: Node's stack has a URL. */ function withPath>(d: D): D { return d.call ? { ...d, call: { ...d.call, file: toPath(d.call.file) } } : d; diff --git a/cli/test/fixtures/setback.ts b/cli/test/fixtures/setback.ts new file mode 100644 index 0000000..4f35baf --- /dev/null +++ b/cli/test/fixtures/setback.ts @@ -0,0 +1,14 @@ +// A drawing file whose footprint, drawn on line 8, is 15 from the front of its lot, inside the +// front setback of 25 that its export `intent` gives. +import { createDrawing, type Intent } from "tsdraft"; + +const d = createDrawing({ units: "ft" }); + +d.layer("C-PROP", { color: 7 }, () => d.rect([0, 0], 100, 140, { id: "lot" })); +d.layer("C-BLDG", { color: 5 }, () => d.rect([25, 15], 50, 40, { id: "house" })); + +export default d.build(); + +export const intent: Intent = { + setbacks: [{ property: "lot", footprints: ["house"], distance: [25, 7.5, 20, 7.5] }], +}; diff --git a/cli/test/render.test.ts b/cli/test/render.test.ts index 8400870..b7dc068 100644 --- a/cli/test/render.test.ts +++ b/cli/test/render.test.ts @@ -975,6 +975,82 @@ test("render warns of text that plots badly, after lint's diagnostics and with e assert.deepEqual(off!.bounds, { min: [10.8, 8], max: [11.133333, 8.25] }); }); +test("render warns where the drawing breaks the file's export intent, with exit 0", () => { + const out = tempDir(); + const file = join(root, "test/fixtures/setback.ts"); + const { state, status } = render(file, "--out", out); + assert.equal(status, 0); + assert.deepEqual(state.drawing?.counts.errors, 0); + assert.deepEqual(state.drawing?.counts.warnings, 1); + assert.equal(typeof state.timings.intent, "number"); + const [warning] = state.diagnostics; + assert.deepEqual( + { ...warning, message: undefined }, + { + rule: "footprint-in-setback", + severity: "warning", + message: undefined, + item: "setbacks[0]", + entity: 1, + id: "house", + layer: "C-BLDG", + call: { file, line: 8, column: 41 }, + side: 0, + required: 25, + provided: 15, + bounds: { min: [0, -25], max: [50, 40] }, + other: { entity: 0, id: "lot" }, + kind: "polyline", + }, + ); + assert.match(warning!.message, /^Footprint "house" is 15 from side 0 of property line "lot"/); +}); + +test("an intent that the drawing's copy of tsdraft cannot check is warned of, never passed over", () => { + const dir = realpathSync(tempDir()); + writeFileSync(join(dir, "package.json"), '{ "type": "module" }\n'); + const library = join(dir, "node_modules/tsdraft"); + mkdirSync(library, { recursive: true }); + writeFileSync( + join(library, "package.json"), + '{ "name": "tsdraft", "type": "module", "exports": "./index.js" }\n', + ); + /** A stand-in for tsdraft, with the `checkIntent` given or none. */ + const stub = (checkIntent: string) => + writeFileSync( + join(library, "index.js"), + `export const drawing = { format: 0, units: "ft", dxf: "R2018", layers: [], entities: [] }; +export const createDrawing = () => {}; +export const toDXF = () => ""; +export const lint = () => []; +export const toSVG = () => ''; +${checkIntent}`, + ); + writeFileSync( + join(dir, "plan.ts"), + 'import { drawing } from "tsdraft";\nexport default drawing;\nexport const intent = { setbacks: [] };\n', + ); + const warned = () => { + const { state, status } = render(join(dir, "plan.ts")); + assert.equal(status, 0); + return state.diagnostics.map((d) => [d.rule, d.message]); + }; + stub(""); + assert.deepEqual(warned(), [ + [ + "intent-unchecked", + "The copy of tsdraft this drawing imports has no checkIntent, so the export `intent` was not checked. Update it", + ], + ]); + stub('export const checkIntent = () => { throw new Error("no room"); };\n'); + assert.deepEqual(warned(), [ + [ + "intent-unchecked", + "checkIntent stopped with an error, so the export `intent` was not checked: no room", + ], + ]); +}); + test("render --view draws one rectangle of model space or of a layout, and nothing else", () => { const out = tempDir(); const crowded = join(root, "test/fixtures/crowded.ts"); diff --git a/docs/command.md b/docs/command.md index 9922bbb..0513c95 100644 --- a/docs/command.md +++ b/docs/command.md @@ -32,13 +32,16 @@ d.layer("C-PROP", { color: 7, linetype: PHANTOM, lineweight: 0.35 }, () => export default d.build(); ``` +A file may also export `intent`, what the drawing is meant to hold to, such as the setbacks a +footprint keeps out of, which each build checks: see [Checks of intent](intent.md). + Each build runs the file in a new child process, so a crash cannot take the command down and every build sees the code as it is now. A build that runs longer than `--timeout`, 10 s by default, fails. ## Commands -`tsdraft render [--out ] [--width ] [--draw-no-plot]` builds once, runs `lint` -and `inspectText`, writes `.svg` and a `.png` 1600 px wide to `out/` beside the +`tsdraft render [--out ] [--width ] [--draw-no-plot]` builds once, runs `lint`, +`inspectText` and, for a file that exports `intent`, `checkIntent`, writes `.svg` and a `.png` 1600 px wide to `out/` beside the file, and prints one JSON object. With `--view`, it writes one rectangle of the drawing and no other picture: see [A closer look](#a-closer-look). It exits 0 when the drawing built with no lint errors, 2 when `lint` reported errors, and 1 when the build failed before `lint` could report or a picture could not be @@ -183,6 +186,17 @@ entity's. `other` names, the same way, the other text of an overlap or the close the text runs past. A drawing loaded with a copy of tsdraft from before `inspectText` has no such warnings. +After them, for a file that exports `intent`, come the warnings of `checkIntent`: a rule of +`footprint-in-setback`, `footprint-off-property` or `intent-unchecked`, which +[Checks of intent](intent.md) describes. They never change the exit code either, and +`drawing.counts.warnings` counts them. `entity` is the footprint's index in model space, or +that of the entity an id names, with its `kind`, `layer`, `id` and `call`, `other` is the +property line, and `item` is the path in the intent of what the warning is about, such as +`setbacks[0]`, where the `item` of a lint error is a path in the drawing. A footprint warning +has `bounds` in drawing units, and `footprint-in-setback` has `side`, `required` and +`provided`. A copy of tsdraft that has no `checkIntent`, or whose `checkIntent` throws, gives +one `intent-unchecked` warning that says so. + A problem with the shape of a value, such as an entity of an unknown kind or a field of the wrong type, gives `item`, the path of the item that holds the value: `entities[3]`, `blocks[0]`, `blocks[0].attributes[1]`, `layouts[0]`, `layouts[0].viewports[1]`, @@ -398,4 +412,5 @@ another copy of tsdraft are the second number. The bench's generated drawing has 5,000 entities, a fifth of them texts, so it takes longer than the 3,000 above. `timings` in the JSON says where a build's time went: `inspect`, the look at the -text as it plots, takes about as long as `lint` does. +text as it plots, takes about as long as `lint` does, and `intent`, the check of the file's +export `intent`, is there when the file has one. diff --git a/docs/intent.md b/docs/intent.md new file mode 100644 index 0000000..6196d4d --- /dev/null +++ b/docs/intent.md @@ -0,0 +1,125 @@ +# Checks of intent + +`lint` holds a drawing to the rules of its file. It cannot know what the drawing is meant to +show: that a house keeps out of its setbacks is a rule of the site, not of the file. +`checkIntent(drawing, intent)` checks a drawing against such rules, given as data beside it, +and returns warnings. It never changes what `lint` reports or what `toDXF` writes, and it +never throws on plain data. Its one check so far is setbacks. + +## Setbacks + +```ts +import { checkIntent, createDrawing, type Intent } from "tsdraft"; + +const d = createDrawing({ units: "ft" }); +d.layer("C-PROP", { color: 7 }, () => d.rect([0, 0], 100, 140, { id: "lot" })); +d.layer("C-BLDG", { color: 5 }, () => d.rect([25, 15], 50, 40, { id: "house" })); +const drawing = d.build(); + +const intent: Intent = { + setbacks: [{ property: "lot", footprints: ["house"], distance: [25, 7.5, 20, 7.5] }], +}; + +checkIntent(drawing, intent); +// [{ rule: "footprint-in-setback", side: 0, required: 25, provided: 15, id: "house", … }] +``` + +A setback names a property line and the footprints that keep out of it, by their ids. Each is +a closed polyline of model space, as `rect` and `polyline(points, true)` draw them. `distance` +is the setback in drawing units, the units the points are in, whatever `units` the drawing +names: one number for every side, or one for each side in the order of the property line's +points. The first side runs from the first point to the second, and the last from the last +point back to the first. A point that repeats the one before it, and a last point that repeats +the first, are the same corner and make no side. `rect` draws its corners counterclockwise from +the one it is given, so for a lot drawn from its front left corner the sides are the front, the +right side, the rear and the left side. + +| Rule | Warns of | +| ------------------------ | ----------------------------------------------------------------------- | +| `footprint-in-setback` | A footprint nearer a side of its property line than that side's setback | +| `footprint-off-property` | A footprint that is not wholly inside its property line | +| `intent-unchecked` | Part of the intent that could not be checked, and why | + +A footprint's distance from a side is the least distance from the side, from one corner of the +property line to the next, to the footprint's outline. So a footprint past the end of a side, +where the lot turns a corner, is measured to that corner and not to the line the side lies +on. + +Distances are measured from the points as the drawing holds them, before the writers round +them to 6 decimals, and from the property line's first corner, so the arithmetic stays as +small as the lot however far it is from the origin. A footprint keeps a setback when it is no +nearer the side than the setback less a tolerance, and it is on its property line when it is +within the tolerance of it. The tolerance is 2^-44 of the largest coordinate of the property +line and the footprint, and never more than 0.0000005, half a unit of the sixth decimal, which +is as far as the writers' rounding moves a coordinate. So a footprint drawn on its setback line +passes at any angle, a footprint may touch a side whose setback is 0, and a footprint short of +its setback by more than the tolerance and twice the spacing of doubles at its distance from +the origin is warned of, even where the shortfall is below the sixth decimal. A point is held +only to the nearest double, and that spacing is how far apart doubles lie: 2^-26, about +0.000000015, at 100,000,000 drawing units from the origin, which is as far as this holds. +Farther out the spacing grows, and a shortfall a little past the tolerance may pass. + +A footprint is inside its property line when every point of its outline is, so it may touch the +property line or run along it. A footprint whose side runs out of the lot and back through two +of the lot's corners, such as one that fills the corner an L-shaped lot lacks or bridges a +notch, is not inside, and nor is one that has a corner of the lot inside it. A footprint that +is not wholly inside gets `footprint-off-property` and no `footprint-in-setback`. A layer's +state does not matter: a footprint on a layer that is off is checked all the same. + +A property line or a footprint must be simple: its sides meet only where one ends and the next +starts. One whose outline crosses or touches itself, or goes back to a corner it has passed, is +`intent-unchecked`, and so is not checked. So the check takes no lot with a hole, which can be +drawn only as one outline that touches itself. Whether two sides meet is worked out exactly +for the doubles the drawing holds, so a sharp corner whose sides come within a hair of each +other is a corner. + +Both footprint warnings name the footprint by `entity`, its index in model space, with its +`id`, `layer` and `call`, and the property line by `other`. Every warning about a setback gives +`item`, the path of the setback in the intent, such as `setbacks[0]`. `footprint-in-setback` +gives a warning for each side the footprint is too near, with `side`, `required`, the side's +setback, `provided`, the distance measured, unrounded, and `bounds`, the box of the point of +the side and the point of the footprint nearest each other, larger on every side by the +setback. `footprint-off-property` gives the footprint's box as `bounds`. + +`intent-unchecked` says what was not checked and why: a field the intent does not have, an id +that names no closed polyline of model space, an outline that is not simple, a distance that +is not a number of 0 or more, distances that are not one for each side, or more points than the +check takes. The rest of the intent is checked. An id is found whatever its case, as the +drawing compares ids, and an id named twice in one setback is checked once. + +The work is bounded. Each outline is read once, however often the intent names it, and a call +does at most 4,000,000 steps of work. It counts one for each item of a list in the intent; +twenty for each point of an outline as it is read, checked, copied and filed, which keeps the +memory of a call to a few tens of megabytes; one for each side the search for sides that meet +looks at, one for each pair it finds, and 64 for each such pair it works out exactly; nine for +each pair of a footprint's point and its property line's as the two are checked; and two times +the property line's points for each piece beyond the first that its outline cuts a side of the +footprint into. So no outline of more than 200,000 points is read, and a property line is +checked in practice only well below that: one of about 60,000 points, round, takes the whole of +a call with a footprint of four corners. A footprint of many corners, or many footprints, +leaves room for fewer. Whatever of a setback would go past the steps left is one +`intent-unchecked` warning for the setback, which names the first part not checked, counts +the rest, and names what took the most of the work. A call gives at most 200 warnings, then +one more that says it stopped there. + +## In the command + +A drawing file that exports `intent` beside its drawing is checked on each build: + +```ts +export default d.build(); + +export const intent: Intent = { + setbacks: [{ property: "lot", footprints: ["house"], distance: [25, 7.5, 20, 7.5] }], +}; +``` + +`tsdraft render` and `tsdraft dev` put the warnings in `diagnostics` after those of +`inspectText`, each with the `kind` of the entity it names, and `drawing.counts.warnings` +counts them. They never change the exit code. The page lists them with the other diagnostics, +and a click on one finds its footprint in the picture. A drawing loaded with a copy of tsdraft +from before `checkIntent` gets one `intent-unchecked` warning that says so, and so does one +whose copy throws, with the error's message. + +The example sheet, [`examples/site-plan.ts`](../examples/site-plan.ts), exports the setbacks +its residence keeps out of, and has no such warning. diff --git a/examples/README.md b/examples/README.md index b055d17..fd8aaf3 100644 --- a/examples/README.md +++ b/examples/README.md @@ -112,3 +112,12 @@ model space and the SVG of the sheet only when it is run: ```sh node examples/site-plan.ts ``` + +It also exports `intent`: the residence keeps out of the setbacks, 25 feet at +the front, 20 at the rear and 7 1/2 at each side, measured from the lot's +sides in the order `rect` draws them. The lot and the residence have the ids +`lot` and `residence`, by which the intent names them. `tsdraft render` and +`tsdraft dev` check it on each build, and a run of the file prints the result. +Move the residence toward the street and the command warns that it is in the +front setback, with the distance it keeps. [Checks of intent](../docs/intent.md) +has more. diff --git a/examples/site-plan.ts b/examples/site-plan.ts index 11635a6..ed403fe 100644 --- a/examples/site-plan.ts +++ b/examples/site-plan.ts @@ -10,6 +10,10 @@ // column of notes, the view title, the north arrow and the graphic scale. One viewport shows // the plan on it at the scale. // +// The export `intent` says what the plan must hold to: the residence keeps out of the +// setbacks. `tsdraft render` and `tsdraft dev` check it on each build, with `checkIntent`, and +// warn of a footprint that crosses a setback line. +// // Sheet: ARCH D, 36 wide and 24 tall. Scale: 1" = 10', a ratio of 120. // // +----------------------------------------------+ @@ -52,6 +56,7 @@ import { mkdirSync, writeFileSync } from "node:fs"; import { CENTER, + checkIntent, createDrawing, DASHED, fromPaper, @@ -61,6 +66,7 @@ import { toSVG, type Drawing, type DrawingBuilder, + type Intent, type Point, type TextAlign, type TextVerticalAlign, @@ -440,7 +446,7 @@ export function sitePlan(ratio: number = scale.ratio): Sheet { }); // Model space: the site, at its true size in feet. - d.layer("C-PROP", {}, () => d.rect([0, 0], lot.width, lot.depth)); + d.layer("C-PROP", {}, () => d.rect([0, 0], lot.width, lot.depth, { id: "lot" })); d.layer("C-PROP-ADJC", {}, () => { // The adjoining lot lines and the street run to the sides of the view. for (const y of [0, lot.depth]) { @@ -459,7 +465,7 @@ export function sitePlan(ratio: number = scale.ratio): Sheet { const { front, side, rear } = setbacks; d.rect([side, front], lot.width - side * 2, lot.depth - front - rear); }); - d.layer("C-BLDG", {}, () => d.polyline(footprint, true)); + d.layer("C-BLDG", {}, () => d.polyline(footprint, true, { id: "residence" })); d.layer("C-PAVE", {}, () => { // The driveway, flared to the street with a quarter circle on each side. @@ -838,6 +844,21 @@ const example = sitePlan(); const drawing = example.drawing; export default drawing; +/** + * What the plan must hold to: the residence keeps out of the setbacks. The lot's sides run + * counterclockwise from its front left corner, as `rect` draws them: the front, the right side, + * the rear and the left side. + */ +export const intent: Intent = { + setbacks: [ + { + property: "lot", + footprints: ["residence"], + distance: [setbacks.front, setbacks.side, setbacks.rear, setbacks.side], + }, + ], +}; + // Run as a script, the example writes its files. Imported, it only hands over the drawing. if (import.meta.main) { const outDir = new URL("./out/", import.meta.url); @@ -850,4 +871,10 @@ if (import.meta.main) { `Wrote ${drawing.entities.length} entities in model space and ${onSheet} on the sheet, ` + `on ${drawing.layers.length} layers, to examples/out/`, ); + const warnings = checkIntent(drawing, intent); + console.log( + warnings.length === 0 + ? "The residence keeps out of every setback" + : warnings.map((w) => w.message).join("\n"), + ); } diff --git a/src/index.ts b/src/index.ts index 0990ecb..3842d68 100644 --- a/src/index.ts +++ b/src/index.ts @@ -81,6 +81,14 @@ export { type TextRule, type TextWarning, } from "./inspect.ts"; +export { + checkIntent, + type Intent, + type IntentOccurrence, + type IntentRule, + type IntentWarning, + type Setback, +} from "./intent.ts"; export { fromJSON, toJSON } from "./json.ts"; export { layoutHandles, viewportView, type LayoutHandles, type ViewportView } from "./layouts.ts"; export { DrawingError, lint, type Diagnostic, type LintOptions, type LintRule } from "./lint.ts"; diff --git a/src/inspect.ts b/src/inspect.ts index 12aefe9..d20fdda 100644 --- a/src/inspect.ts +++ b/src/inspect.ts @@ -73,7 +73,7 @@ const TOLERANCE = 0.1; */ const MAX_WORK = 16_000_000; -type Box = readonly [minX: number, minY: number, maxX: number, maxY: number]; +export type Box = readonly [minX: number, minY: number, maxX: number, maxY: number]; /** What draws a text or an outline, as `TextOccurrence` names it, with the entity's layer. */ interface Placed { @@ -442,7 +442,7 @@ function boxed(points: readonly Point[], box: Box): boolean { } /** Which side of the line from `a` to `b` the point `p` is on: positive on its left. */ -function side(a: Point, b: Point, p: Point): number { +export function side(a: Point, b: Point, p: Point): number { return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]); } @@ -496,7 +496,7 @@ const SPAN = 1024; * with the index of each box below `below` that may touch a given box, once each. It spends * one for each box it looks at, and stops when `spend` says there is no room left. */ -function grid( +export function grid( boxes: readonly Box[], spend: (cost: number) => boolean, ): (box: Box, found: (index: number) => void, below?: number) => void { diff --git a/src/intent.ts b/src/intent.ts new file mode 100644 index 0000000..d472d47 --- /dev/null +++ b/src/intent.ts @@ -0,0 +1,839 @@ +// What a drawing is meant to hold to, which no rule of a file states: a building that keeps out +// of its setbacks. `lint` holds the rules a file must meet. These are warnings about the design. +import { callOf, type CallSite } from "./callsite.ts"; +import type { Drawing, Point } from "./drawing.ts"; +import { written } from "./format.ts"; +import { grid, side, type Box } from "./inspect.ts"; +import { idKey, shown } from "./rules.ts"; + +/** The checks `checkIntent` makes. */ +export type IntentRule = "footprint-in-setback" | "footprint-off-property" | "intent-unchecked"; + +/** + * A setback: how far each footprint keeps from the sides of a property line. The property line + * and the footprints are closed polylines of model space, named by their ids. + */ +export interface Setback { + /** The id of the property line. */ + readonly property: string; + /** The ids of the footprints that keep out of the setback, one or more. */ + readonly footprints: readonly string[]; + /** + * The setback in drawing units, the units the points are in: one distance for every side of + * the property line, or one for each side in the order of its points. The first side runs + * from the first point to the second, and the last from the last point back to the first. + */ + readonly distance: number | readonly number[]; +} + +/** What a drawing is meant to hold to, which `checkIntent` checks. */ +export interface Intent { + readonly setbacks?: readonly Setback[]; +} + +/** What names an entity of model space. */ +export interface IntentOccurrence { + /** The index of the entity in model space. */ + readonly entity: number; + /** The entity's `id`. */ + readonly id?: string; +} + +/** A warning that a drawing does not hold to its intent, or that part of it was not checked. */ +export interface IntentWarning extends Partial { + readonly rule: IntentRule; + readonly severity: "warning"; + readonly message: string; + /** + * The path in the intent of the part the warning is about, such as `setbacks[0]`. Missing + * for the intent as a whole. + */ + readonly item?: string; + /** The layer the entity names. */ + readonly layer?: string; + /** The side of the property line, counted from 0 as `distance` counts them. */ + readonly side?: number; + /** The setback of that side, in drawing units. */ + readonly required?: number; + /** The least distance from that side to the footprint, in drawing units, as measured. */ + readonly provided?: number; + /** + * In model space, in drawing units. For `footprint-in-setback`, the box of the two points of + * the side and the footprint nearest each other, larger on every side by the setback. For + * `footprint-off-property`, the footprint's box. + */ + readonly bounds?: { readonly min: Point; readonly max: Point }; + /** The property line. */ + readonly other?: IntentOccurrence; + /** The call that drew the entity, when the drawing's builder recorded calls. */ + readonly call?: CallSite; +} + +/** + * The most work one call does, in steps: one for each item of a list in the intent; twenty for + * each point of an outline when it is read, which holds the memory that copying its points and + * filing its sides takes to a few tens of megabytes; one for each box of a side that the search + * for sides that meet looks at, one for each pair it finds, and `EXACT_COST` for each turn of + * three corners it works out in integers; nine for each pair of a footprint's point and its + * property line's when the two are checked; and two more for each piece of a footprint's side + * beyond the first that the property line cuts it into. + */ +const MAX_WORK = 4_000_000; + +/** `MAX_WORK` as a message gives it. */ +const STEPS = "4,000,000"; + +/** What working out a turn of three corners in integers costs, in the steps of `MAX_WORK`. */ +const EXACT_COST = 64; + +/** What reading one point of an outline costs, from what `MAX_WORK` counts. */ +const READ_COST = 20; + +/** The most warnings one call gives. One more then says that the rest was not checked. */ +const MAX_WARNINGS = 200; + +/** + * The tolerance of a comparison, as a share of the largest coordinate of the two outlines: 256 + * times the spacing of doubles that large. + */ +const RELATIVE_TOLERANCE = 2 ** -44; + +/** + * The most a tolerance may be: half a unit of the 6th decimal, which is how far rounding moves a + * coordinate. + */ +const MOST_TOLERANCE = 5e-7; + +const SETBACK_FIELDS = ["property", "footprints", "distance"]; + +/** A closed polyline of model space that an id named. */ +interface Outline extends IntentOccurrence { + readonly id: string; + /** Its corners, with no point that repeats the one before it or the first. */ + readonly points: readonly Point[]; + /** The same corners from the first, which keeps the arithmetic small far from the origin. */ + readonly local: readonly Point[]; +} + +/** + * An entity as reading it found it: an outline, why it is none, or that it could not be read, + * because it is more than the work of a call by itself or because the work left was too little. + */ +type Read = Outline | { readonly why: string } | "alone" | "short"; + +/** What a setback names that the work of the call could not take. */ +interface Unchecked { + readonly what: string; + readonly index: number | undefined; + /** True when it is more than the work of a call by itself. */ + readonly alone: boolean; +} + +/** + * Checks a drawing against what it is meant to hold to, and warns of: + * + * - `footprint-in-setback`: a footprint that comes nearer a side of its property line than that + * side's setback, one warning for each such side. The distance is the least one from the + * side, from one corner of the property line to the next, to the footprint's outline. + * - `footprint-off-property`: a footprint that is not wholly inside its property line. It gets + * no `footprint-in-setback` warning. + * - `intent-unchecked`: part of the intent that could not be checked, and why: a field it does + * not know, an id that names no closed polyline of model space whose sides meet only at its + * corners, a distance that is not a number of 0 or more, distances that do not match the + * property line's sides, or more points than it checks, in one warning for each setback. + * Past 200 warnings it stops, with one more that says so. + * + * Distances are in drawing units, measured from the points as the drawing holds them. A + * footprint keeps a setback when it is no nearer than the setback less a tolerance, and is on + * its property line when it is within the tolerance of it: 2^-44 of the largest coordinate of + * the two outlines, and never more than 0.0000005, half a unit of the sixth decimal the writers + * round to. An id is found as the drawing compares ids, whatever its case. A layer's state does + * not matter. + * + * It never changes what `lint` reports or what `toDXF` writes. It takes any plain data as the + * intent and never throws on it. + */ +export function checkIntent(drawing: Drawing, intent: Intent): IntentWarning[] { + const out: IntentWarning[] = []; + const given: unknown = intent; + const entities: readonly unknown[] = Array.isArray(drawing?.entities) ? drawing.entities : []; + let stopped = false; + const warn = (warning: IntentWarning): void => { + if (out.length < MAX_WARNINGS) out.push(warning); + else stopped = true; + }; + const unchecked = (message: string, item?: string, about: Partial = {}): void => + warn({ + rule: "intent-unchecked", + severity: "warning", + message, + ...(item === undefined ? {} : { item }), + ...about, + }); + let work = 0; + /** The work each part of the intent took, by what it is, such as the outline of a lot. */ + const spentOn = new Map(); + /** Counts the cost of a step for `job`, and says whether there is room left to take it. */ + const spend = (cost: number, job: string): boolean => { + if (work + cost > MAX_WORK) return false; + work += cost; + spentOn.set(job, (spentOn.get(job) ?? 0) + cost); + return true; + }; + /** What took the most of the work, and how much of it. */ + const heaviest = (): string => { + let most: [string, number] = ["nothing", 0]; + for (const entry of spentOn) if (entry[1] > most[1]) most = entry; + return `${most[0]} took ${Math.round((100 * most[1]) / MAX_WORK)}% of them`; + }; + + let ids: Map | undefined; + /** The index of the first entity of model space with the id. */ + const find = (id: string): number | undefined => { + if (!ids) { + ids = new Map(); + for (let i = 0; i < entities.length; i++) { + const own = (entities[i] as { id?: unknown } | null)?.id; + if (typeof own === "string" && !ids.has(idKey(own))) ids.set(idKey(own), i); + } + } + return ids.get(idKey(id)); + }; + /** What names an entity, with its layer and the call that drew it. */ + const about = (index: number): Partial => { + const entity = entities[index] as { id?: unknown; layer?: unknown }; + const call = callOf(entities as object[], index); + return { + entity: index, + ...(typeof entity.id === "string" ? { id: entity.id } : {}), + ...(typeof entity.layer === "string" ? { layer: entity.layer } : {}), + ...(call === undefined ? {} : { call }), + }; + }; + const reads = new Map(); + /** The entity at an index as an outline, read once however often the intent names it. */ + const read = (index: number, job: string): Read => { + let found = reads.get(index); + if (found === undefined) { + const pay = (cost: number) => spend(cost, job); + found = outlineOf(entities[index] as Record, index, pay); + reads.set(index, found); + } + return found; + }; + + /** Checks one setback, the `n`th, with one warning for all of it that is more than it checks. */ + const check = (setback: unknown, n: number): void => { + const item = `setbacks[${n}]`; + const at = `Setback ${n}`; + if (!isRecord(setback)) { + unchecked(`${at} must be an object with property, footprints and distance`, item); + return; + } + for (const key in setback) { + if (stopped) return; + if (!Object.hasOwn(setback, key) || SETBACK_FIELDS.includes(key)) continue; + const message = `${at} has no field ${shown(key)}. Its fields are property, footprints and distance`; + unchecked(message, item); + } + const left: Unchecked[] = []; + measure(setback, item, at, left); + const [first, ...more] = left; + if (!first) return; + const what = + more.length === 0 ? `${first.what} was` : `${first.what} and ${more.length} more were`; + const why = first.alone + ? `By itself it is more than the ${STEPS} steps of work checkIntent does in one call` + : `checkIntent does ${STEPS} steps of work in one call, and ${heaviest()}`; + const named = first.index === undefined ? {} : about(first.index); + unchecked(`${at}: ${what} not checked. ${why}`, item, named); + }; + + /** Checks what one setback names, keeping in `left` what the work of the call could not take. */ + const measure = ( + setback: Record, + item: string, + at: string, + left: Unchecked[], + ): void => { + /** The closed polyline an id names, or undefined with a warning that says why not. */ + const outline = (id: string, what: string): Outline | undefined => { + const index = find(id); + if (index === undefined) { + unchecked( + `${at} names ${what} ${shown(id)}, and no entity of model space has that id`, + item, + ); + return undefined; + } + const job = `the outline of ${what} ${shown(id)}`; + const found = read(index, job); + if (found === "alone" || found === "short") { + left.push({ what: job, index, alone: found === "alone" }); + return undefined; + } + if ("why" in found) { + unchecked(`${at} names ${what} ${shown(id)}${found.why}`, item, about(index)); + return undefined; + } + return found; + }; + + const { property, footprints, distance } = setback; + let lot: Outline | undefined; + if (typeof property === "string") lot = outline(property, "property line"); + else unchecked(`${at}'s property must be the id of a closed polyline`, item); + const allowed = (d: unknown): d is number => + typeof d === "number" && Number.isFinite(d) && d >= 0; + let distances: number | readonly number[] | undefined; + if (allowed(distance)) { + distances = distance; + } else if (Array.isArray(distance) && !spend(distance.length, `the distances of ${at}`)) { + const alone = distance.length > MAX_WORK; + left.push({ what: "its list of distances", index: undefined, alone }); + } else if (Array.isArray(distance) && each(distance, allowed)) { + if (lot && distance.length !== lot.points.length) { + unchecked( + `${at} gives ${distance.length} distances for property line ${shown(lot.id)}, which has ${lot.points.length} sides. Give one distance, or one for each side in the order of its points`, + item, + about(lot.entity), + ); + } else { + distances = distance; + } + } else { + unchecked( + `${at}'s distance must be a number of 0 or more, in drawing units, or an array of one for each side of the property line`, + item, + ); + } + const listed = `${at}'s footprints must be an array of one or more ids of closed polylines`; + if (!Array.isArray(footprints) || footprints.length === 0) { + unchecked(listed, item); + return; + } + if (!spend(footprints.length, `the footprints of ${at}`)) { + const alone = footprints.length > MAX_WORK; + left.push({ what: "its list of footprints", index: undefined, alone }); + return; + } + if (!each(footprints, (id): id is string => typeof id === "string")) { + unchecked(listed, item); + return; + } + // An id named twice is checked once. + const named = new Set(); + const buildings: Outline[] = []; + for (let j = 0; j < footprints.length && !stopped; j++) { + const key = idKey(footprints[j]!); + if (named.has(key)) continue; + named.add(key); + const building = outline(footprints[j]!, "footprint"); + if (building) buildings.push(building); + } + if (!lot || distances === undefined) return; + + const sides = lot.points.length; + const origin = lot.points[0]!; + const stated = distances; + const requiredAt = (i: number): number => (typeof stated === "number" ? stated : stated[i]!); + for (const building of buildings) { + if (stopped) return; + const job = `footprint ${shown(building.id)} held against property line ${shown(lot.id)}`; + const cost = 9 * sides * building.points.length; + if (!spend(cost, job)) { + left.push({ what: job, index: building.entity, alone: cost > MAX_WORK }); + continue; + } + const tolerance = toleranceOf(lot.points, building.points); + const footprint = building.points.map(([x, y]): Point => [x - origin[0], y - origin[1]]); + const found = { item, ...about(building.entity) }; + const other = { entity: lot.entity, id: lot.id }; + const inside = contained(footprint, lot.local, tolerance, (more) => spend(more, job)); + if (inside === undefined) { + left.push({ what: job, index: building.entity, alone: false }); + continue; + } + if (!inside) { + warn({ + rule: "footprint-off-property", + severity: "warning", + message: `Footprint ${shown(building.id)} is not wholly inside property line ${shown(lot.id)}. Move it inside, or name the property line it is on`, + ...found, + bounds: boxOf(building.points, [0, 0], 0), + other, + }); + continue; + } + for (let i = 0; i < sides && !stopped; i++) { + const required = requiredAt(i); + const near = nearest(lot.local[i]!, lot.local[(i + 1) % sides]!, footprint); + const provided = near.distance; + if (provided >= required - tolerance) continue; + const how = provided <= tolerance ? "touches" : `is ${shownShort(provided, required)} from`; + const a = lot.points[i]!; + const b = lot.points[(i + 1) % sides]!; + warn({ + rule: "footprint-in-setback", + severity: "warning", + message: `Footprint ${shown(building.id)} ${how} side ${i} of property line ${shown(lot.id)}, from ${shownPoint(a)} to ${shownPoint(b)}, whose setback is ${required}. Move the footprint back from that side or make it smaller`, + ...found, + side: i, + required, + provided, + bounds: boxOf([near.onSide, near.onOutline], origin, required), + other, + }); + } + } + }; + + const run = (): void => { + if (!isRecord(given)) { + unchecked("The intent must be an object, such as { setbacks: [...] }"); + return; + } + for (const key in given) { + if (stopped) return; + if (!Object.hasOwn(given, key) || key === "setbacks") continue; + unchecked(`The intent has no field ${shown(key)}. Its one field is setbacks`); + } + const setbacks = given.setbacks; + if (setbacks === undefined) return; + if (!Array.isArray(setbacks)) { + unchecked("The intent's setbacks must be an array", "setbacks"); + return; + } + for (let n = 0; n < setbacks.length && !stopped; n++) check(setbacks[n], n); + }; + run(); + if (stopped) { + out.push({ + rule: "intent-unchecked", + severity: "warning", + message: `checkIntent stopped after ${MAX_WARNINGS} warnings, so the rest of the intent was not checked. Act on these and check again`, + }); + } + return out; +} + +/** Whether every item of an array passes, an empty slot included, which `every` skips. */ +function each(list: readonly unknown[], test: (item: unknown) => item is T): list is T[] { + for (let i = 0; i < list.length; i++) if (!test(list[i])) return false; + return true; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * An entity as an outline: a closed polyline whose points are numbers, which has an area and + * whose sides meet only at its corners. A point that repeats the one before it, and a last + * point that repeats the first, are the same corner. Its points are paid for before they are + * read. + */ +function outlineOf( + entity: Record, + index: number, + spend: (cost: number) => boolean, +): Read { + if (entity.kind !== "polyline") { + return { why: `, which is an entity of kind ${shown(entity.kind)}, not a closed polyline` }; + } + if (entity.closed !== true) return { why: ", which is an open polyline, not a closed polyline" }; + const points = entity.points; + if (!Array.isArray(points)) return { why: ", which is a polyline with no points" }; + if (READ_COST * points.length > MAX_WORK) return "alone"; + if (!spend(READ_COST * points.length)) return "short"; + for (let i = 0; i < points.length; i++) { + const p: unknown = points[i]; + if (!Array.isArray(p) || !Number.isFinite(p[0]) || !Number.isFinite(p[1])) { + return { why: ", which has a point that is not two numbers" }; + } + } + const same = (p: Point, q: Point): boolean => p[0] === q[0] && p[1] === q[1]; + const corners: Point[] = []; + for (let i = 0; i < points.length; i++) { + const p = points[i] as Point; + const last = corners.at(-1); + if (!last || !same(p, last)) corners.push(p); + } + while (corners.length > 1 && same(corners[0]!, corners.at(-1)!)) corners.pop(); + const first = corners[0]; + if (!first || corners.length < 3) return { why: ", which has no area" }; + const local = corners.map(([x, y]): Point => [x - first[0], y - first[1]]); + if (twiceArea(local) === 0) return { why: ", which has no area" }; + const simple = isSimple(corners, spend); + if (simple === undefined) return "short"; + if (!simple) { + return { + why: ", whose outline crosses or touches itself. checkIntent takes an outline whose sides meet only where one ends and the next starts, so it takes no lot with a hole", + }; + } + return { entity: index, id: entity.id as string, points: corners, local }; +} + +/** Twice the area of a polygon whose first point is the origin, positive counterclockwise. */ +function twiceArea(points: readonly Point[]): number { + let sum = 0; + for (let i = 1; i + 1 < points.length; i++) { + const a = points[i]!; + const b = points[i + 1]!; + sum += a[0] * b[1] - b[0] * a[1]; + } + return Number.isFinite(sum) ? sum : 0; +} + +/** + * Whether the sides of a polygon meet only where one ends and the next starts. Two sides that + * cross, touch or overlap, a side of no length, and a side that turns back along the one + * before it all make it not simple. Undefined when `spend` has no room for the pairs of sides + * that might meet. + */ +function isSimple(points: readonly Point[], spend: (cost: number) => boolean): boolean | undefined { + const n = points.length; + const ends = (i: number): [Point, Point] => [points[i]!, points[(i + 1) % n]!]; + const boxes: Box[] = []; + for (let i = 0; i < n; i++) { + const [a, b] = ends(i); + if (a[0] === b[0] && a[1] === b[1]) return false; + boxes.push([ + Math.min(a[0], b[0]), + Math.min(a[1], b[1]), + Math.max(a[0], b[0]), + Math.max(a[1], b[1]), + ]); + } + let short = false; + const pay = (cost: number): boolean => { + if (!short && spend(cost)) return true; + short = true; + return false; + }; + const near = grid(boxes, pay); + const exact = (): boolean => pay(EXACT_COST); + let simple = true; + for (let i = 1; i < n && simple && !short; i++) { + const [a, b] = ends(i); + near( + boxes[i]!, + (j) => { + if (!simple || !pay(1)) return; + const [c, d] = ends(j); + // Two sides in a row share a corner, and meet wrongly only where one turns back. + if (j === i - 1) simple = !folds(c, a, b, exact); + else if (i === n - 1 && j === 0) simple = !folds(a, b, d, exact); + else simple = !touch(a, b, c, d, exact); + }, + i, + ); + } + return short ? undefined : simple; +} + +/** Whether the side `s` to `q` turns back along the side `p` to `s` before it. */ +function folds(p: Point, s: Point, q: Point, exact: () => boolean): boolean { + // On one line, it turns back when `p` and `q` lie the same way from `s`. + return ( + turn(p, s, q, exact) === 0 && + Math.sign(p[0] - s[0]) === Math.sign(q[0] - s[0]) && + Math.sign(p[1] - s[1]) === Math.sign(q[1] - s[1]) + ); +} + +/** Whether the segments `a` to `b` and `c` to `d` have a point in common. */ +function touch(a: Point, b: Point, c: Point, d: Point, exact: () => boolean): boolean { + const d1 = turn(c, d, a, exact); + const d2 = turn(c, d, b, exact); + const d3 = turn(a, b, c, exact); + const d4 = turn(a, b, d, exact); + if (d1 * d2 < 0 && d3 * d4 < 0) return true; + return ( + (d1 === 0 && spans(c, d, a)) || + (d2 === 0 && spans(c, d, b)) || + (d3 === 0 && spans(a, b, c)) || + (d4 === 0 && spans(a, b, d)) + ); +} + +/** + * The most the turn of three corners worked out in doubles can be off, as a share of the sum of + * the sizes of its two products: the first error bound of Shewchuk's `orient2d`. + */ +const TURN_ERROR = (3 + 16 * 2 ** -53) * 2 ** -53; + +/** Below this, the two products of a turn may have lost digits to underflow. */ +const TURN_SMALLEST = 2 ** -900; + +/** + * The sign of the turn from `a` to `b` to `c`, exactly for the doubles given: 1 to the left, -1 + * to the right and 0 when the three lie on one line. The doubles decide it when the turn is + * larger than the error they can make, and integers do otherwise, which `exact` pays for. When + * it refuses, the turn is 0. + */ +function turn(a: Point, b: Point, c: Point, exact: () => boolean): number { + const ux = b[0] - a[0]; + const uy = b[1] - a[1]; + const vx = c[0] - a[0]; + const vy = c[1] - a[1]; + // A difference of two doubles has the right sign, and is 0 only when they are equal, so a + // product with a factor of 0 is truly 0, and two products of other signs decide the turn. + const leftSign = Math.sign(ux) * Math.sign(vy); + const rightSign = Math.sign(uy) * Math.sign(vx); + if (leftSign === 0 || rightSign === 0 || leftSign !== rightSign) { + return Math.sign(leftSign - rightSign); + } + const left = ux * vy; + const right = uy * vx; + const size = Math.abs(left) + Math.abs(right); + if (size > TURN_SMALLEST && size < Infinity) { + const turned = left - right; + if (turned > TURN_ERROR * size) return 1; + if (turned < -TURN_ERROR * size) return -1; + } + return exact() ? exactTurn(a, b, c) : 0; +} + +/** + * The turn of three corners worked out in integers, with each double as its mantissa times a + * power of two. + */ +function exactTurn(a: Point, b: Point, c: Point): number { + const parts = [a[0], a[1], b[0], b[1], c[0], c[1]].map(binary); + let low = Infinity; + for (const [mantissa, exponent] of parts) if (mantissa !== 0n && exponent < low) low = exponent; + if (low === Infinity) return 0; + const [ax, ay, bx, by, cx, cy] = parts.map(([mantissa, exponent]) => + mantissa === 0n ? 0n : mantissa << BigInt(exponent - low), + ) as [bigint, bigint, bigint, bigint, bigint, bigint]; + const turned = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); + return turned > 0n ? 1 : turned < 0n ? -1 : 0; +} + +const bits = new BigUint64Array(1); +const float = new Float64Array(bits.buffer); + +/** A finite double as `[m, e]`, an integer and a power of two whose product is the double. */ +function binary(x: number): [bigint, number] { + float[0] = x; + const all = bits[0]!; + const exponent = Number((all >> 52n) & 0x7ffn); + const fraction = all & 0xfffffffffffffn; + const mantissa = exponent === 0 ? fraction : fraction | 0x10000000000000n; + return [all >> 63n ? -mantissa : mantissa, exponent === 0 ? -1074 : exponent - 1075]; +} + +/** Whether `p`, on the line through `a` and `b`, is in the box of the segment between them. */ +function spans(a: Point, b: Point, p: Point): boolean { + return ( + Math.min(a[0], b[0]) <= p[0] && + p[0] <= Math.max(a[0], b[0]) && + Math.min(a[1], b[1]) <= p[1] && + p[1] <= Math.max(a[1], b[1]) + ); +} + +/** The tolerance for two outlines, from the largest of their coordinates. */ +function toleranceOf(a: readonly Point[], b: readonly Point[]): number { + let largest = 1; + for (const points of [a, b]) { + for (const [x, y] of points) largest = Math.max(largest, Math.abs(x), Math.abs(y)); + } + return Math.min(MOST_TOLERANCE, largest * RELATIVE_TOLERANCE); +} + +/** + * A distance short of `required` as a message gives it: to 6 decimals, or in full where those + * would hide the shortfall. + */ +function shownShort(provided: number, required: number): string { + const rounded = written(provided); + return String(rounded < required ? rounded : provided); +} + +function shownPoint(p: Point): string { + return `[${written(p[0])}, ${written(p[1])}]`; +} + +/** The box around points taken from `origin`, larger on every side by `grow`, as written. */ +function boxOf(points: readonly Point[], origin: Point, grow: number): { min: Point; max: Point } { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const [x, y] of points) { + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + return { + min: [written(origin[0] + minX - grow), written(origin[1] + minY - grow)], + max: [written(origin[0] + maxX + grow), written(origin[1] + maxY + grow)], + }; +} + +/** + * Whether the outline `inner` lies wholly in the outline `outer`, where being within + * `tolerance` of `outer` counts as in. Each corner of `inner` must be in, and no corner of + * `outer` may be inside `inner` by more than the tolerance, since `outer`'s outline would then + * pass through it. Each side of `inner` is cut where a side of `outer` crosses it and at each + * corner of `outer` within the tolerance of it, and the middle of each piece must be in. So a + * side that leaves `outer` and comes back through two of its corners is out. Undefined when + * `spend` has no room for the pieces. + */ +function contained( + inner: readonly Point[], + outer: readonly Point[], + tolerance: number, + spend: (cost: number) => boolean, +): boolean | undefined { + for (const p of inner) if (!inOrOn(p, outer, tolerance)) return false; + for (const p of outer) if (insideBy(p, inner, tolerance)) return false; + for (let j = 0; j < inner.length; j++) { + const c = inner[j]!; + const d = inner[(j + 1) % inner.length]!; + const cuts = [0, 1]; + for (let i = 0; i < outer.length; i++) { + const p = outer[i]!; + const t = crossing(c, d, p, outer[(i + 1) % outer.length]!); + if (t !== undefined) cuts.push(t); + if (toSegment(p, c, d) <= tolerance) { + const at = along(p, c, d); + if (at > 0 && at < 1) cuts.push(at); + } + } + // The first piece of each side is paid for with the outlines. + if (cuts.length > 2 && !spend(2 * (cuts.length - 2) * outer.length)) return undefined; + cuts.sort((x, y) => x - y); + for (let k = 1; k < cuts.length; k++) { + if (!(cuts[k]! > cuts[k - 1]!)) continue; + const t = (cuts[k - 1]! + cuts[k]!) / 2; + const middle: Point = [c[0] + t * (d[0] - c[0]), c[1] + t * (d[1] - c[1])]; + if (!inOrOn(middle, outer, tolerance)) return false; + } + } + return true; +} + +/** + * Where, between 0 at `c` and 1 at `d`, the segment `c` to `d` crosses the segment `a` to `b`, + * or undefined when it does not cross it between its ends. + */ +function crossing(c: Point, d: Point, a: Point, b: Point): number | undefined { + const rx = d[0] - c[0]; + const ry = d[1] - c[1]; + const sx = b[0] - a[0]; + const sy = b[1] - a[1]; + const across = rx * sy - ry * sx; + if (across === 0) return undefined; + const qx = a[0] - c[0]; + const qy = a[1] - c[1]; + const t = (qx * sy - qy * sx) / across; + const u = (qx * ry - qy * rx) / across; + return t > 0 && t < 1 && u >= 0 && u <= 1 ? t : undefined; +} + +/** Whether a point is inside a polygon, or within `tolerance` of its outline. */ +function inOrOn(p: Point, polygon: readonly Point[], tolerance: number): boolean { + return enclosed(p, polygon) || nearOutline(p, polygon, tolerance); +} + +/** Whether a point is inside a polygon by more than `tolerance`. */ +function insideBy(p: Point, polygon: readonly Point[], tolerance: number): boolean { + return enclosed(p, polygon) && !nearOutline(p, polygon, tolerance); +} + +/** Whether a point is inside a polygon, by the crossings of a ray from it. */ +function enclosed(p: Point, polygon: readonly Point[]): boolean { + const [x, y] = p; + let odd = false; + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const a = polygon[i]!; + const b = polygon[j]!; + if (a[1] > y !== b[1] > y && x < a[0] + ((y - a[1]) * (b[0] - a[0])) / (b[1] - a[1])) { + odd = !odd; + } + } + return odd; +} + +/** Whether a point is within `tolerance` of a polygon's outline. */ +function nearOutline(p: Point, polygon: readonly Point[], tolerance: number): boolean { + for (let i = 0; i < polygon.length; i++) { + if (toSegment(p, polygon[i]!, polygon[(i + 1) % polygon.length]!) <= tolerance) return true; + } + return false; +} + +/** + * The least distance from the side `a` to `b` to a closed outline, with the point of the side + * and the point of the outline that are that far apart. + */ +function nearest( + a: Point, + b: Point, + outline: readonly Point[], +): { distance: number; onSide: Point; onOutline: Point } { + let distance = Infinity; + let edge = 0; + for (let j = 0; j < outline.length && distance > 0; j++) { + const found = apart(a, b, outline[j]!, outline[(j + 1) % outline.length]!); + if (found < distance) [distance, edge] = [found, j]; + } + const c = outline[edge]!; + const d = outline[(edge + 1) % outline.length]!; + return { distance, ...closest(a, b, c, d) }; +} + +/** Whether the segments `a` to `b` and `c` to `d` cross, each at a point inside the other. */ +function cross(a: Point, b: Point, c: Point, d: Point): boolean { + return side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0; +} + +/** The least distance between the segment `a` to `b` and the segment `c` to `d`. */ +function apart(a: Point, b: Point, c: Point, d: Point): number { + if (cross(a, b, c, d)) return 0; + return Math.min(toSegment(c, a, b), toSegment(d, a, b), toSegment(a, c, d), toSegment(b, c, d)); +} + +/** The point of each segment nearest the other. */ +function closest(a: Point, b: Point, c: Point, d: Point): { onSide: Point; onOutline: Point } { + if (cross(a, b, c, d)) { + const [s, t] = [side(c, d, a), side(c, d, b)]; + const at: Point = [a[0] + (s / (s - t)) * (b[0] - a[0]), a[1] + (s / (s - t)) * (b[1] - a[1])]; + return { onSide: at, onOutline: at }; + } + const pairs: [Point, Point][] = [ + [nearestOn(c, a, b), c], + [nearestOn(d, a, b), d], + [a, nearestOn(a, c, d)], + [b, nearestOn(b, c, d)], + ]; + const length = ([p, q]: [Point, Point]) => Math.hypot(p[0] - q[0], p[1] - q[1]); + const [onSide, onOutline] = pairs.reduce((x, y) => (length(y) < length(x) ? y : x)); + return { onSide, onOutline }; +} + +/** The distance from `p` to the segment `a` to `b`. */ +function toSegment(p: Point, a: Point, b: Point): number { + const t = along(p, a, b); + return Math.hypot(a[0] + t * (b[0] - a[0]) - p[0], a[1] + t * (b[1] - a[1]) - p[1]); +} + +/** The point of the segment `a` to `b` nearest `p`. */ +function nearestOn(p: Point, a: Point, b: Point): Point { + const t = along(p, a, b); + return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; +} + +/** How far along the segment `a` to `b` its point nearest `p` is, from 0 at `a` to 1 at `b`. */ +function along(p: Point, a: Point, b: Point): number { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const length = dx * dx + dy * dy; + return length > 0 + ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length)) + : 0; +} diff --git a/test/intent.test.ts b/test/intent.test.ts new file mode 100644 index 0000000..c8255aa --- /dev/null +++ b/test/intent.test.ts @@ -0,0 +1,558 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { checkIntent, createDrawing, type Drawing, type Intent, type Point } from "../src/index.ts"; +import sheet, { intent as sheetIntent } from "../examples/site-plan.ts"; + +/** Each warning as its rule, the side or the id it names, and the distance it measured. */ +const found = (drawing: Drawing, intent: Intent) => + checkIntent(drawing, intent).map((w) => [ + w.rule, + w.side ?? w.id, + w.provided === undefined ? undefined : Number(w.provided.toFixed(6)), + ]); + +/** A drawing of a lot and footprints, each a closed polyline with its id. */ +function site(outlines: Readonly>): Drawing { + const d = createDrawing(); + for (const [id, points] of Object.entries(outlines)) d.polyline(points, true, { id }); + return d.build(); +} + +/** A rectangle from its lower-left corner to its upper-right, counterclockwise. */ +const rect = (x0: number, y0: number, x1: number, y1: number): Point[] => [ + [x0, y0], + [x1, y0], + [x1, y1], + [x0, y1], +]; + +/** A circle as a polygon of `n` corners. */ +const circle = (r: number, n: number, center: Point = [0, 0]): Point[] => + Array.from({ length: n }, (_, i): Point => [ + center[0] + r * Math.cos((2 * Math.PI * i) / n), + center[1] + r * Math.sin((2 * Math.PI * i) / n), + ]); + +/** Points turned about the origin by `angle` radians, then moved to `origin`. */ +const turned = (points: readonly Point[], angle: number, origin: Point): Point[] => + points.map(([x, y]): Point => [ + origin[0] + x * Math.cos(angle) - y * Math.sin(angle), + origin[1] + x * Math.sin(angle) + y * Math.cos(angle), + ]); + +/** The angles the rounding tests turn a lot by: 199 steps of 0.0137 radians. */ +const ANGLES = Array.from({ length: 199 }, (_, k) => (k + 1) * 0.0137); + +/** The drawing with the entity of an id moved by `by`. */ +function moved(drawing: Drawing, id: string, by: Point): Drawing { + const entities = drawing.entities.map((e) => + e.id === id && e.kind === "polyline" + ? { ...e, points: e.points.map(([x, y]): Point => [x + by[0], y + by[1]]) } + : e, + ); + return { ...drawing, entities }; +} + +test("the example's residence keeps out of its setbacks, and moved into two it is warned of twice", () => { + assert.deepEqual(checkIntent(sheet, sheetIntent), []); + // 12 ft toward the street and 20 ft to the left: 18 ft from the front, 4 ft from the side. + const [front, left] = checkIntent(moved(sheet, "residence", [-20, -12]), sheetIntent); + const residence = sheet.entities.findIndex((e) => e.id === "residence"); + assert.deepEqual( + { ...front, message: undefined, call: undefined }, + { + rule: "footprint-in-setback", + severity: "warning", + message: undefined, + item: "setbacks[0]", + entity: residence, + id: "residence", + layer: "C-BLDG", + call: undefined, + side: 0, + required: 25, + provided: 18, + // The nearest points, at the corner of the garage, and the setback around them. + bounds: { min: [9, -25], max: [59, 43] }, + other: { entity: 0, id: "lot" }, + }, + ); + assert.equal( + front!.message, + 'Footprint "residence" is 18 from side 0 of property line "lot", from [0, 0] to [100, 0], whose setback is 25. Move the footprint back from that side or make it smaller', + ); + assert.deepEqual([left!.side, left!.required, left!.provided], [3, 7.5, 4]); +}); + +test("a setback is measured from the side itself, so a footprint past the end of a side keeps clear of it", () => { + // An L-shaped lot. Side 2 is the top of its right wing and side 3 the inner side of its left. + const lot: Point[] = [ + [0, 0], + [100, 0], + [100, 60], + [50, 60], + [50, 140], + [0, 140], + ]; + // 5 from the line of side 3, but beyond its end, 15.8 from the side. + const clear = rect(55, 10, 90, 45); + // 8 below side 2, and 9.43 from the inner corner, which ends side 3. + const near = rect(55, 10, 90, 52); + const setbacks = [{ property: "lot", footprints: ["clear", "near"], distance: 10 }]; + assert.deepEqual(found(site({ lot, clear, near }), { setbacks }), [ + ["footprint-in-setback", 2, 8], + ["footprint-in-setback", 3, 9.433981], + ]); +}); + +test("a footprint across its property line or outside it is off the property, and one on it touches", () => { + const d = createDrawing(); + d.rect([0, 0], 100, 140, { id: "lot" }); + d.rect([-10, 50], 30, 20, { id: "across" }); + d.rect([200, 0], 10, 10, { id: "outside" }); + d.rect([0, 50], 20, 20, { id: "on" }); + const footprints = ["across", "outside", "on"]; + const drawing = d.build(); + assert.deepEqual(found(drawing, { setbacks: [{ property: "lot", footprints, distance: 5 }] }), [ + ["footprint-off-property", "across", undefined], + ["footprint-off-property", "outside", undefined], + ["footprint-in-setback", 3, 0], + ]); + const [, , on] = checkIntent(drawing, { + setbacks: [{ property: "lot", footprints, distance: 5 }], + }); + assert.match(on!.message, /^Footprint "on" touches side 3 of property line "lot"/); + // A setback of 0 lets a footprint touch the line, and never lets it cross. + assert.deepEqual( + found(drawing, { setbacks: [{ property: "lot", footprints, distance: 0 }] }).map((w) => w[0]), + ["footprint-off-property", "footprint-off-property"], + ); +}); + +test("a footprint whose sides run through the lot's corners is off it where it fills a corner the lot lacks", () => { + const l: Point[] = [ + [0, 0], + [100, 0], + [100, 60], + [50, 60], + [50, 140], + [0, 140], + ]; + // Its long side runs from one corner of the L to another, across the corner the L lacks. + const corner: Point[] = [ + [50, 60], + [100, 60], + [50, 140], + ]; + // The L's upright arm itself, which shares three of its sides and two of its corners. + const arm: Point[] = [ + [0, 0], + [50, 0], + [50, 140], + [0, 140], + ]; + const u: Point[] = [ + [0, 0], + [30, 0], + [30, 30], + [20, 30], + [20, 10], + [10, 10], + [10, 30], + [0, 30], + ]; + // Its top lies along the tops of both arms of the U, and across the gap between them. + const bridge: Point[] = [ + [5, 5], + [25, 5], + [25, 30], + [5, 30], + ]; + const check = (lot: Point[], footprint: Point[], distance: number) => + found(site({ lot, footprint }), { + setbacks: [{ property: "lot", footprints: ["footprint"], distance }], + }); + assert.deepEqual(check(l, corner, 0), [["footprint-off-property", "footprint", undefined]]); + assert.deepEqual(check(l, arm, 0), []); + assert.deepEqual(check(u, bridge, 0), [["footprint-off-property", "footprint", undefined]]); + assert.deepEqual(check(u, bridge, 1), [["footprint-off-property", "footprint", undefined]]); + // A notch off the middle of the bridge, turned, where no side meets another exactly. + const notched: Point[] = [ + [0, 0], + [30, 0], + [30, 30], + [22, 30], + [22, 10], + [20, 10], + [20, 30], + [0, 30], + ]; + for (const origin of [ + [0, 0], + [612345, 512345], + ] as const) { + for (const angle of ANGLES) { + for (const distance of [0, 1]) { + assert.deepEqual( + check(turned(notched, angle, origin), turned(bridge, angle, origin), distance), + [["footprint-off-property", "footprint", undefined]], + `at ${angle} from ${origin}, setback ${distance}`, + ); + } + } + } +}); + +test("a footprint on its setback line passes at any angle up to 1e8 from the origin, and one short of it by a millionth warns", () => { + const offsets = { front: 25, side: 7.5, rear: 20 }; + const distance = [offsets.front, offsets.side, offsets.rear, offsets.side]; + for (const origin of [ + [0, 0], + [612345, 512345], + [1e8, 1e8], + ] as const) { + for (const angle of ANGLES) { + const place = ([x, y]: Point): Point => turned([[x, y]], angle, origin)[0]!; + const footprint = (rear: number): Point[] => + ( + [ + [offsets.side, offsets.front], + [100 - offsets.side, offsets.front], + [100 - offsets.side, 140 - rear], + [offsets.side, 140 - rear], + ] as Point[] + ).map(place); + const lot = ( + [ + [0, 0], + [100, 0], + [100, 140], + [0, 140], + ] as Point[] + ).map(place); + const setbacks = [{ property: "lot", footprints: ["footprint"], distance }]; + const on = found(site({ lot, footprint: footprint(offsets.rear) }), { setbacks }); + assert.deepEqual(on, [], `at ${angle} from ${origin}`); + const short = found(site({ lot, footprint: footprint(offsets.rear - 1e-6) }), { setbacks }); + assert.deepEqual( + short, + [["footprint-in-setback", 2, 19.999999]], + `at ${angle} from ${origin}`, + ); + // At 1e8 a double's spacing is 2^-26: a shortfall past the tolerance and twice that warns. + if (origin[0] !== 1e8) continue; + const past = found(site({ lot, footprint: footprint(offsets.rear - 5.3e-7) }), { setbacks }); + assert.deepEqual( + past.map((w) => w[0]), + ["footprint-in-setback"], + `at ${angle}`, + ); + } + } +}); + +test("a footprint short of its setback by less than the sixth decimal shows warns, with the distance in full", () => { + const lot: Point[] = [ + [0, 0], + [100, 0], + [100, 100], + ]; + const footprint: Point[] = [ + [50, 10], + [60, 10], + [60, 40], + [50, 40], + ]; + // Its corner at [50, 40] is 7.071067811865475 from the long side, as measured. + const drawing = site({ lot, footprint }); + const check = (setback: number) => + checkIntent(drawing, { + setbacks: [{ property: "lot", footprints: ["footprint"], distance: [0, 0, setback] }], + }); + const [short, more] = check(7.071068); + assert.equal(more, undefined); + assert.deepEqual( + [short!.side, short!.required, short!.provided], + [2, 7.071068, 7.071067811865475], + ); + assert.match(short!.message, / is 7\.07106781186547\d* from side 2 /); + assert.deepEqual(check(7.071067), []); +}); + +test("what cannot be checked is warned of with the reason, and the rest is checked", () => { + const d = createDrawing(); + d.rect([0, 0], 100, 140, { id: "lot" }); + d.rect([10, 10], 20, 20, { id: "shed" }); + d.polyline( + [ + [40, 40], + [60, 40], + [60, 60], + ], + false, + { id: "open" }, + ); + d.line([0, 0], [10, 0], { id: "edge" }); + const drawing = d.build(); + const intent = { + setbacks: [ + { property: "lot", footprints: ["shed"], distance: [5, 5, 5] }, + { property: "edge", footprints: ["open", "missing"], distance: -1 }, + { property: "lot", footprints: [], distance: 5 }, + { property: "LOT", footprint: ["shed"], footprints: ["shed", "open"], distance: 15 }, + // An empty slot, which `every` would pass over. + // oxlint-disable-next-line no-sparse-arrays + { property: "lot", footprints: ["shed"], distance: [15, , 15, 15] }, + ], + setback: [], + }; + assert.deepEqual( + checkIntent(drawing, intent as Intent).map((w) => [w.rule, w.item, w.message]), + [ + [ + "intent-unchecked", + undefined, + 'The intent has no field "setback". Its one field is setbacks', + ], + [ + "intent-unchecked", + "setbacks[0]", + 'Setback 0 gives 3 distances for property line "lot", which has 4 sides. Give one distance, or one for each side in the order of its points', + ], + [ + "intent-unchecked", + "setbacks[1]", + 'Setback 1 names property line "edge", which is an entity of kind "line", not a closed polyline', + ], + [ + "intent-unchecked", + "setbacks[1]", + "Setback 1's distance must be a number of 0 or more, in drawing units, or an array of one for each side of the property line", + ], + [ + "intent-unchecked", + "setbacks[1]", + 'Setback 1 names footprint "open", which is an open polyline, not a closed polyline', + ], + [ + "intent-unchecked", + "setbacks[1]", + 'Setback 1 names footprint "missing", and no entity of model space has that id', + ], + [ + "intent-unchecked", + "setbacks[2]", + "Setback 2's footprints must be an array of one or more ids of closed polylines", + ], + [ + "intent-unchecked", + "setbacks[3]", + 'Setback 3 has no field "footprint". Its fields are property, footprints and distance', + ], + [ + "intent-unchecked", + "setbacks[3]", + 'Setback 3 names footprint "open", which is an open polyline, not a closed polyline', + ], + [ + "footprint-in-setback", + "setbacks[3]", + 'Footprint "shed" is 10 from side 0 of property line "lot", from [0, 0] to [100, 0], whose setback is 15. Move the footprint back from that side or make it smaller', + ], + [ + "footprint-in-setback", + "setbacks[3]", + 'Footprint "shed" is 10 from side 3 of property line "lot", from [0, 140] to [0, 0], whose setback is 15. Move the footprint back from that side or make it smaller', + ], + [ + "intent-unchecked", + "setbacks[4]", + "Setback 4's distance must be a number of 0 or more, in drawing units, or an array of one for each side of the property line", + ], + ], + ); + assert.deepEqual(found(drawing, null as unknown as Intent), [ + ["intent-unchecked", undefined, undefined], + ]); +}); + +test("each outline is read once and paid for first, and past 200 warnings the check stops", () => { + const square: Point[] = [ + [-10, -10], + [10, -10], + [10, 10], + [-10, 10], + ]; + const drawing = site({ lot: circle(100, 10_000), house: circle(95, 10_000), small: square }); + // One footprint named 500 times is one footprint, too large to check, and the small one is + // checked. + const footprints = [...Array.from({ length: 500 }, () => "house"), "small"]; + assert.deepEqual(found(drawing, { setbacks: [{ property: "lot", footprints, distance: 10 }] }), [ + ["intent-unchecked", "house", undefined], + ]); + // A setback over and over, each past what is left to check. + const setbacks = Array.from({ length: 2000 }, () => ({ + property: "lot", + footprints: Array.from({ length: 50 }, () => "house"), + distance: 10, + })); + const warnings = checkIntent(drawing, { setbacks }); + assert.equal(warnings.length, 201); + assert.deepEqual( + warnings.slice(0, 2).map((w) => w.item), + ["setbacks[0]", "setbacks[1]"], + ); + assert.match(warnings[200]!.message, /^checkIntent stopped after 200 warnings/); +}); + +test("a lot or a footprint whose outline crosses or touches itself is not checked, and says so", () => { + // A lot around a hole, drawn as one outline that goes in to the hole and back. + const holed: Point[] = [ + [0, 0], + [100, 0], + [100, 100], + [0, 100], + [0, 0], + [40, 40], + [40, 60], + [60, 60], + [60, 40], + [40, 40], + [0, 0], + ]; + const crossed: Point[] = [ + [30, 30], + [50, 50], + [50, 30], + [30, 50], + ]; + // A last point that repeats the first is the same corner, so the square has four sides. + const square: Point[] = [...rect(0, 0, 100, 100), [0, 0]]; + const over = rect(20, 20, 80, 80); + const drawing = site({ holed, crossed, square, over }); + const [hole] = checkIntent(drawing, { + setbacks: [{ property: "holed", footprints: ["over"], distance: 0 }], + }); + assert.equal(hole!.rule, "intent-unchecked"); + assert.match( + hole!.message, + /^Setback 0 names property line "holed", whose outline crosses or touches itself\. /, + ); + assert.deepEqual( + found(drawing, { + setbacks: [{ property: "square", footprints: ["over", "crossed"], distance: [5, 5, 5, 5] }], + }), + [["intent-unchecked", "crossed", undefined]], + ); +}); + +test("a property line's points are read a few times, however many setbacks name it", () => { + const n = 1000; + let reads = 0; + const points = new Proxy(circle(100, n), { + get(target, key, receiver) { + if (typeof key === "string" && /^\d+$/.test(key)) reads++; + return Reflect.get(target, key, receiver) as unknown; + }, + }); + const drawing: Drawing = { + ...createDrawing().build(), + entities: [{ kind: "polyline", layer: "0", id: "lot", closed: true, points }], + }; + const setbacks = Array.from({ length: 199 }, () => ({ + property: "lot", + footprints: ["missing"], + distance: 0, + })); + assert.equal(checkIntent(drawing, { setbacks }).length, 199); + assert.ok(reads <= 3 * n, `${reads} reads of ${n} points`); +}); + +test("what is more than the check takes is one warning for each setback, which leaves room for the rest", () => { + const outlines: Record = { lot: circle(1000, 800) }; + for (let i = 0; i < 2000; i++) { + outlines[`f${i}`] = circle(1, 3, [(i % 40) * 20 - 400, Math.floor(i / 40) * 15 - 400]); + } + const footprints = Object.keys(outlines).filter((id) => id !== "lot"); + const warnings = checkIntent(site(outlines), { + setbacks: [{ property: "lot", footprints, distance: 0 }], + }); + assert.deepEqual( + warnings.map((w) => w.rule), + ["intent-unchecked"], + ); + assert.match( + warnings[0]!.message, + /^Setback 0: footprint "f\d+" held against property line "lot" and \d+ more were not checked\. checkIntent does 4,000,000 steps of work in one call, and .+ took \d+% of them$/, + ); +}); + +test("an intent with more unknown fields than the check warns of stops with a warning that says so", () => { + const fields = Object.fromEntries(Array.from({ length: 201 }, (_, i) => [`field${i}`, 0])); + const warnings = checkIntent(site({ lot: rect(0, 0, 10, 10) }), fields as Intent); + assert.equal(warnings.length, 201); + assert.match(warnings[200]!.message, /^checkIntent stopped after 200 warnings/); +}); + +test("a lot a trillion from the origin has its area, and its setbacks are measured as near it", () => { + const at = 1e12; + const lot = rect(at, at, at + 100, at + 140); + const setbacks = [{ property: "lot", footprints: ["footprint"], distance: [25, 7.5, 20, 7.5] }]; + const on = rect(at + 7.5, at + 25, at + 92.5, at + 120); + assert.deepEqual(found(site({ lot, footprint: on }), { setbacks }), []); + const short = rect(at + 7.5, at + 25, at + 92.5, at + 121); + assert.deepEqual(found(site({ lot, footprint: short }), { setbacks }), [ + ["footprint-in-setback", 2, 19], + ]); +}); + +test("an acute corner whose two sides nearly meet is a corner, judged exactly for the doubles held", () => { + // The turn at [100, 100.1] is 25/2^45: no side touches another, though doubles round it to 0. + const lot: Point[] = [ + [0, 0], + [100, 100.1], + [50, 50.050000000000004], + [0, 100], + ]; + const footprint = rect(1, 60, 10, 70); + const setbacks = [{ property: "lot", footprints: ["footprint"], distance: 0 }]; + assert.deepEqual(found(site({ lot, footprint }), { setbacks }), []); +}); + +test("a point that repeats the one before it is the same corner and makes no side", () => { + const footprint = rect(5, 5, 25, 25); + const setbacks = [{ property: "lot", footprints: ["footprint"], distance: [1, 1, 1, 1] }]; + const repeated: Point[] = [ + [0, 0], + [30, 0], + [30, 0], + [30, 30], + [0, 30], + ]; + assert.deepEqual(found(site({ lot: repeated, footprint }), { setbacks }), []); + const closedTwice: Point[] = [...rect(0, 0, 30, 30), [0, 0], [0, 0]]; + assert.deepEqual(found(site({ lot: closedTwice, footprint }), { setbacks }), []); +}); + +test("what the work of a call could not take names the work, and what took most of it", () => { + const drawing = site({ lot: circle(1000, 150_000), footprint: rect(-1, -1, 1, 1) }); + const setbacks = Array.from({ length: 2 }, () => ({ + property: "lot", + footprints: ["footprint"], + distance: 1, + })); + const warnings = checkIntent(drawing, { setbacks }); + assert.deepEqual( + warnings.map((w) => w.message.replace(/\d+% of/, "N% of")), + [0, 1].map( + (n) => + `Setback ${n}: the outline of property line "lot" and 1 more were not checked. checkIntent does 4,000,000 steps of work in one call, and the outline of property line "lot" took N% of them`, + ), + ); + // An outline larger than all of that says so. + const huge = site({ lot: circle(1000, 250_000), footprint: rect(-1, -1, 1, 1) }); + assert.match( + checkIntent(huge, { setbacks: setbacks.slice(0, 1) })[0]!.message, + /^Setback 0: the outline of property line "lot" was not checked\. By itself it is more than the 4,000,000 steps of work checkIntent does in one call$/, + ); +});