@instruments/quadrat 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -2
- package/dist/analysis/analyze-surface-regions.d.ts +34 -0
- package/dist/analysis/analyze-surface-regions.d.ts.map +1 -0
- package/dist/analysis/analyze-surface-regions.js +47 -0
- package/dist/analysis/decode.d.ts +23 -0
- package/dist/analysis/decode.d.ts.map +1 -0
- package/dist/analysis/decode.js +48 -0
- package/dist/analysis/descriptors.d.ts +112 -0
- package/dist/analysis/descriptors.d.ts.map +1 -0
- package/dist/analysis/descriptors.js +248 -0
- package/dist/analysis/diagnostics.d.ts +45 -0
- package/dist/analysis/diagnostics.d.ts.map +1 -0
- package/dist/analysis/diagnostics.js +34 -0
- package/dist/analysis/index.d.ts +6 -0
- package/dist/analysis/index.d.ts.map +1 -0
- package/dist/analysis/index.js +2 -0
- package/dist/analysis/outline.d.ts +44 -0
- package/dist/analysis/outline.d.ts.map +1 -0
- package/dist/analysis/outline.js +301 -0
- package/dist/analysis/rank-suggestions.d.ts +21 -0
- package/dist/analysis/rank-suggestions.d.ts.map +1 -0
- package/dist/analysis/rank-suggestions.js +150 -0
- package/dist/analysis/repetition.d.ts +31 -0
- package/dist/analysis/repetition.d.ts.map +1 -0
- package/dist/analysis/repetition.js +105 -0
- package/dist/analysis/segmentation.d.ts +26 -0
- package/dist/analysis/segmentation.d.ts.map +1 -0
- package/dist/analysis/segmentation.js +81 -0
- package/dist/analysis/square-geometry.d.ts +34 -0
- package/dist/analysis/square-geometry.d.ts.map +1 -0
- package/dist/analysis/square-geometry.js +91 -0
- package/dist/analysis/surface-candidates.d.ts +45 -0
- package/dist/analysis/surface-candidates.d.ts.map +1 -0
- package/dist/analysis/surface-candidates.js +471 -0
- package/dist/analysis/thresholds.d.ts +189 -0
- package/dist/analysis/thresholds.d.ts.map +1 -0
- package/dist/analysis/thresholds.js +189 -0
- package/dist/analysis/types.d.ts +42 -0
- package/dist/analysis/types.d.ts.map +1 -0
- package/dist/analysis/types.js +2 -0
- package/dist/crops/crop-editor-state.d.ts +88 -0
- package/dist/crops/crop-editor-state.d.ts.map +1 -0
- package/dist/crops/crop-editor-state.js +121 -0
- package/dist/crops/crop-entries.d.ts +47 -0
- package/dist/crops/crop-entries.d.ts.map +1 -0
- package/dist/crops/crop-entries.js +46 -0
- package/dist/crops/crop-export.d.ts +21 -0
- package/dist/crops/crop-export.d.ts.map +1 -0
- package/dist/crops/crop-export.js +38 -0
- package/dist/crops/crop-geometry.d.ts +130 -0
- package/dist/crops/crop-geometry.d.ts.map +1 -0
- package/dist/crops/crop-geometry.js +271 -0
- package/dist/crops/crop-gesture.d.ts +175 -0
- package/dist/crops/crop-gesture.d.ts.map +1 -0
- package/dist/crops/crop-gesture.js +188 -0
- package/dist/crops/index.d.ts +10 -0
- package/dist/crops/index.d.ts.map +1 -0
- package/dist/crops/index.js +5 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/surface-types.d.ts +41 -0
- package/dist/surface-types.d.ts.map +1 -0
- package/dist/surface-types.js +1 -0
- package/dist/worker/index.d.ts +4 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +1 -0
- package/dist/worker/protocol.d.ts +28 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/protocol.js +1 -0
- package/dist/worker/run-analysis.d.ts +21 -0
- package/dist/worker/run-analysis.d.ts.map +1 -0
- package/dist/worker/run-analysis.js +36 -0
- package/dist/worker/surface-worker.d.ts +2 -0
- package/dist/worker/surface-worker.d.ts.map +1 -0
- package/dist/worker/surface-worker.js +36 -0
- package/package.json +123 -3
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @instruments/quadrat
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Client-side surface crop detection and square-crop editing geometry for interior and material photos. Runs in the browser (or on raw RGBA buffers in Node) using color, edges and repetition with no AI model or runtime dependencies.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {
|
|
9
|
+
decodePhoto,
|
|
10
|
+
exportCrop,
|
|
11
|
+
startAnalysis,
|
|
12
|
+
buildEntries,
|
|
13
|
+
} from "@instruments/quadrat";
|
|
14
|
+
|
|
15
|
+
const { bitmap, image } = await decodePhoto(file);
|
|
16
|
+
|
|
17
|
+
const stop = startAnalysis(1, image, {
|
|
18
|
+
onReply: (reply) => {
|
|
19
|
+
const entries = buildEntries(
|
|
20
|
+
reply.suggestions,
|
|
21
|
+
{ width: bitmap.width, height: bitmap.height },
|
|
22
|
+
{},
|
|
23
|
+
[],
|
|
24
|
+
new Set()
|
|
25
|
+
);
|
|
26
|
+
// Export the selected square crop as a Blob for MaterialGraph matching
|
|
27
|
+
// const blob = await exportCrop(bitmap, entries[0].box);
|
|
28
|
+
},
|
|
29
|
+
onFailure: (message) => {
|
|
30
|
+
console.error(message);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Entry points
|
|
36
|
+
|
|
37
|
+
- `@instruments/quadrat`: full browser + pure-analysis API (`decodePhoto`, `startAnalysis`, `analyzeSurfaceRegions`, crop editor & export helpers).
|
|
38
|
+
- `@instruments/quadrat/analysis`: pure analysis functions (`analyzeSurfaceRegions`, `decodePhoto`, `analysisSize`).
|
|
39
|
+
- `@instruments/quadrat/crops`: square-crop editor state, geometry, pointer gestures and canvas export.
|
|
40
|
+
- `@instruments/quadrat/worker`: Web Worker runner (`startAnalysis`) and protocol types.
|
|
41
|
+
- `@instruments/quadrat/worker/surface-worker`: standalone module worker entry.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Diagnostics } from "./diagnostics.js";
|
|
2
|
+
import type { AnalysisImage, SurfaceSuggestion } from "./types.js";
|
|
3
|
+
export type { SurfaceSuggestion } from "./types.js";
|
|
4
|
+
export type { Diagnostics, StageEvent } from "./diagnostics.js";
|
|
5
|
+
/**
|
|
6
|
+
* Proposes visually consistent squares from a downsampled RGBA image, entirely on the client: classical
|
|
7
|
+
* image analysis only, no model, weights or network. Pixels are row-major 8-bit RGBA (four values per pixel);
|
|
8
|
+
* dimensions are analysis pixels (the app shrinks photos to a 320-pixel longest side first, see decode.ts).
|
|
9
|
+
* Results use source percentages, so the caller crops the original image rather than this buffer.
|
|
10
|
+
*
|
|
11
|
+
* The pipeline, one stage per file in analysis/:
|
|
12
|
+
* 1. descriptors: at each of six window sizes, overlapping windows (half a side apart) are summarized by their
|
|
13
|
+
* color distribution, edge directions and edge strength. A window with any non-opaque pixel is skipped.
|
|
14
|
+
* 2. segmentation: neighboring windows with similar summaries are joined into segments, and touching segments
|
|
15
|
+
* whose average summaries are close are also tried as one larger region.
|
|
16
|
+
* 3. surfaceCandidates: for each region the largest square inside its eroded mask is fitted and trimmed at the
|
|
17
|
+
* edges. A square is rejected when it is too small, contains transparent pixels, has windows that disagree
|
|
18
|
+
* with each other or with the whole, or is too dark, clipped or featureless. Survivors score by relative size,
|
|
19
|
+
* consistency and sample quality. `maxCrop` is the untrimmed square, offered only if it passes the same checks.
|
|
20
|
+
* 4. rankSuggestions: overlapping squares are dropped best-first, then squares that a lighting-tolerant
|
|
21
|
+
* comparison says show the same material (keeping the better representative), then squares far smaller
|
|
22
|
+
* than the best, then anything past the suggestion limit.
|
|
23
|
+
* 5. Two finishing touches, each in its own file. repetition runs inside stage 3 and only labels a square
|
|
24
|
+
* (`basis`) as repeating; it never proposes or removes one. outline runs inside stage 4 and draws a smooth
|
|
25
|
+
* outline, only for the final survivors.
|
|
26
|
+
*
|
|
27
|
+
* Every tunable number lives in thresholds.ts. They are trial heuristics: similar objects can merge, and
|
|
28
|
+
* artwork can look like texture. Pass a collector as `diagnostics` to record why each candidate was kept,
|
|
29
|
+
* shrunk or rejected; the result is identical with or without it.
|
|
30
|
+
* Returns an empty list when either side is under `thresholds.input.minimumSide`. Best score comes first.
|
|
31
|
+
* @throws When dimensions are not positive integers or the RGBA buffer size does not match.
|
|
32
|
+
*/
|
|
33
|
+
export declare function analyzeSurfaceRegions(image: AnalysisImage, diagnostics?: Diagnostics): SurfaceSuggestion[];
|
|
34
|
+
//# sourceMappingURL=analyze-surface-regions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analyze-surface-regions.d.ts","sourceRoot":"","sources":["../../src/analysis/analyze-surface-regions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAIpD,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEnE,YAAY,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,aAAa,EACpB,WAAW,CAAC,EAAE,WAAW,GACxB,iBAAiB,EAAE,CAqBrB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { rankSuggestions } from "./rank-suggestions.js";
|
|
2
|
+
import { surfaceCandidates } from "./surface-candidates.js";
|
|
3
|
+
import { thresholds } from "./thresholds.js";
|
|
4
|
+
/**
|
|
5
|
+
* Proposes visually consistent squares from a downsampled RGBA image, entirely on the client: classical
|
|
6
|
+
* image analysis only, no model, weights or network. Pixels are row-major 8-bit RGBA (four values per pixel);
|
|
7
|
+
* dimensions are analysis pixels (the app shrinks photos to a 320-pixel longest side first, see decode.ts).
|
|
8
|
+
* Results use source percentages, so the caller crops the original image rather than this buffer.
|
|
9
|
+
*
|
|
10
|
+
* The pipeline, one stage per file in analysis/:
|
|
11
|
+
* 1. descriptors: at each of six window sizes, overlapping windows (half a side apart) are summarized by their
|
|
12
|
+
* color distribution, edge directions and edge strength. A window with any non-opaque pixel is skipped.
|
|
13
|
+
* 2. segmentation: neighboring windows with similar summaries are joined into segments, and touching segments
|
|
14
|
+
* whose average summaries are close are also tried as one larger region.
|
|
15
|
+
* 3. surfaceCandidates: for each region the largest square inside its eroded mask is fitted and trimmed at the
|
|
16
|
+
* edges. A square is rejected when it is too small, contains transparent pixels, has windows that disagree
|
|
17
|
+
* with each other or with the whole, or is too dark, clipped or featureless. Survivors score by relative size,
|
|
18
|
+
* consistency and sample quality. `maxCrop` is the untrimmed square, offered only if it passes the same checks.
|
|
19
|
+
* 4. rankSuggestions: overlapping squares are dropped best-first, then squares that a lighting-tolerant
|
|
20
|
+
* comparison says show the same material (keeping the better representative), then squares far smaller
|
|
21
|
+
* than the best, then anything past the suggestion limit.
|
|
22
|
+
* 5. Two finishing touches, each in its own file. repetition runs inside stage 3 and only labels a square
|
|
23
|
+
* (`basis`) as repeating; it never proposes or removes one. outline runs inside stage 4 and draws a smooth
|
|
24
|
+
* outline, only for the final survivors.
|
|
25
|
+
*
|
|
26
|
+
* Every tunable number lives in thresholds.ts. They are trial heuristics: similar objects can merge, and
|
|
27
|
+
* artwork can look like texture. Pass a collector as `diagnostics` to record why each candidate was kept,
|
|
28
|
+
* shrunk or rejected; the result is identical with or without it.
|
|
29
|
+
* Returns an empty list when either side is under `thresholds.input.minimumSide`. Best score comes first.
|
|
30
|
+
* @throws When dimensions are not positive integers or the RGBA buffer size does not match.
|
|
31
|
+
*/
|
|
32
|
+
export function analyzeSurfaceRegions(image, diagnostics) {
|
|
33
|
+
const { width, height, data } = image;
|
|
34
|
+
if (!Number.isSafeInteger(width) ||
|
|
35
|
+
!Number.isSafeInteger(height) ||
|
|
36
|
+
width <= 0 ||
|
|
37
|
+
height <= 0 ||
|
|
38
|
+
!(data instanceof Uint8ClampedArray) ||
|
|
39
|
+
data.length !== width * height * 4) {
|
|
40
|
+
throw new Error("Surface analysis needs positive integer dimensions and matching RGBA pixels.");
|
|
41
|
+
}
|
|
42
|
+
if (width < thresholds.input.minimumSide ||
|
|
43
|
+
height < thresholds.input.minimumSide) {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
return rankSuggestions(surfaceCandidates(image, diagnostics), diagnostics);
|
|
47
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { AnalysisImage } from "./types.js";
|
|
2
|
+
/** A decoded photo: the source photo as a full-size bitmap (downloads are cut from it) and the analysis image the detector reads. */
|
|
3
|
+
export interface DecodedPhoto {
|
|
4
|
+
bitmap: ImageBitmap;
|
|
5
|
+
image: AnalysisImage;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Analysis size for a source photo of the given size (pixels): longest side `thresholds.input.analysisSide`,
|
|
9
|
+
* aspect ratio kept, never upscaled, each side at least one pixel. The eval harness calls it too, to check
|
|
10
|
+
* that a saved dump matches what the app would have made.
|
|
11
|
+
*/
|
|
12
|
+
export declare const analysisSize: (width: number, height: number) => {
|
|
13
|
+
height: number;
|
|
14
|
+
width: number;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Decodes a photo exactly as the app does: EXIF orientation applied, then drawn onto a canvas at analysis
|
|
18
|
+
* size with the browser's default smoothing. The caller owns `bitmap` and must `close()` it.
|
|
19
|
+
* A string is fetched as a URL; a failed fetch throws. Also throws if the file cannot be decoded as an
|
|
20
|
+
* image or no canvas is available (the bitmap is closed first in that case).
|
|
21
|
+
*/
|
|
22
|
+
export declare const decodePhoto: (source: Blob | string) => Promise<DecodedPhoto>;
|
|
23
|
+
//# sourceMappingURL=decode.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../../src/analysis/decode.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,qIAAqI;AACrI,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,WAAW,CAAC;IACpB,KAAK,EAAE,aAAa,CAAC;CACtB;AAED;;;;GAIG;AACH,eAAO,MAAM,YAAY,UAChB,MAAM,UACL,MAAM,KACb;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CASjC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,WAAW,WACd,IAAI,GAAG,MAAM,KACpB,OAAO,CAAC,YAAY,CA0BtB,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Turns a photo file into the small pixel copy the detector reads (browser-only; shared by the app and the eval harness).
|
|
2
|
+
import { thresholds } from "./thresholds.js";
|
|
3
|
+
/**
|
|
4
|
+
* Analysis size for a source photo of the given size (pixels): longest side `thresholds.input.analysisSide`,
|
|
5
|
+
* aspect ratio kept, never upscaled, each side at least one pixel. The eval harness calls it too, to check
|
|
6
|
+
* that a saved dump matches what the app would have made.
|
|
7
|
+
*/
|
|
8
|
+
export const analysisSize = (width, height) => {
|
|
9
|
+
const scale = Math.min(1, thresholds.input.analysisSide / Math.max(width, height));
|
|
10
|
+
return {
|
|
11
|
+
height: Math.max(1, Math.round(height * scale)),
|
|
12
|
+
width: Math.max(1, Math.round(width * scale)),
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Decodes a photo exactly as the app does: EXIF orientation applied, then drawn onto a canvas at analysis
|
|
17
|
+
* size with the browser's default smoothing. The caller owns `bitmap` and must `close()` it.
|
|
18
|
+
* A string is fetched as a URL; a failed fetch throws. Also throws if the file cannot be decoded as an
|
|
19
|
+
* image or no canvas is available (the bitmap is closed first in that case).
|
|
20
|
+
*/
|
|
21
|
+
export const decodePhoto = async (source) => {
|
|
22
|
+
let blob;
|
|
23
|
+
if (typeof source === "string") {
|
|
24
|
+
const response = await fetch(source);
|
|
25
|
+
if (!response.ok) {
|
|
26
|
+
throw new Error(`Could not fetch ${source}: ${response.status}`);
|
|
27
|
+
}
|
|
28
|
+
blob = await response.blob();
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
blob = source;
|
|
32
|
+
}
|
|
33
|
+
const bitmap = await createImageBitmap(blob, {
|
|
34
|
+
imageOrientation: "from-image",
|
|
35
|
+
});
|
|
36
|
+
const { height, width } = analysisSize(bitmap.width, bitmap.height);
|
|
37
|
+
const canvas = document.createElement("canvas");
|
|
38
|
+
canvas.width = width;
|
|
39
|
+
canvas.height = height;
|
|
40
|
+
const context = canvas.getContext("2d", { willReadFrequently: true });
|
|
41
|
+
if (context === null) {
|
|
42
|
+
bitmap.close();
|
|
43
|
+
throw new Error("Canvas unavailable");
|
|
44
|
+
}
|
|
45
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
46
|
+
const { data } = context.getImageData(0, 0, width, height);
|
|
47
|
+
return { bitmap, image: { data, height, width } };
|
|
48
|
+
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { AnalysisImage } from "./types.js";
|
|
2
|
+
/** Per-pixel quantities computed once and shared by every window at every scale. */
|
|
3
|
+
export interface PixelFields {
|
|
4
|
+
width: number;
|
|
5
|
+
height: number;
|
|
6
|
+
/** Quantized red, green and blue per pixel, three entries each. */
|
|
7
|
+
colorBins: Uint8Array;
|
|
8
|
+
/** Which edge-direction bin (0 to `orientationBins` - 1) the pixel's gradient falls in. */
|
|
9
|
+
orientationBin: Uint8Array;
|
|
10
|
+
/** Edge strength: gradient size in 8-bit luminance levels per pixel. */
|
|
11
|
+
magnitude: Float32Array;
|
|
12
|
+
/** Brightness, 0-255. */
|
|
13
|
+
luma: Float32Array;
|
|
14
|
+
/** Channel spread (max minus min) per pixel, a cheap chroma measure. */
|
|
15
|
+
chroma: Float32Array;
|
|
16
|
+
/** 1 when the pixel's alpha reaches `thresholds.input.opaqueAlpha`, else 0. */
|
|
17
|
+
opaque: Uint8Array;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* What a window looks like, in three measures: its color distribution, which way its edges run, and how
|
|
21
|
+
* strong they are. A flat color is the same kind of thing with zero energy, so one model covers paint,
|
|
22
|
+
* stone and weave. Shift-tolerant: it ignores where inside the window things sit, so a repeating pattern
|
|
23
|
+
* reads the same wherever the window lands on it.
|
|
24
|
+
*/
|
|
25
|
+
export interface Descriptor {
|
|
26
|
+
/** Cumulative per-channel color histograms, concatenated. L1 distance between them is the Wasserstein-1 color shift. */
|
|
27
|
+
cdf: Float32Array;
|
|
28
|
+
/** Share of the window's total edge strength in each edge-direction bin; sums to 1 (all zeros for a perfectly flat window). */
|
|
29
|
+
orientations: Float32Array;
|
|
30
|
+
/** Mean gradient magnitude, in 8-bit intensity per pixel. */
|
|
31
|
+
energy: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Quantizes color and computes gradient orientation and magnitude for every pixel. Gradients are central
|
|
35
|
+
* differences of brightness, with image borders clamped to the nearest pixel.
|
|
36
|
+
*/
|
|
37
|
+
export declare function pixelFields({ width, height, data, }: AnalysisImage): PixelFields;
|
|
38
|
+
/**
|
|
39
|
+
* Describes the pixel rectangle (analysis pixels), or returns null when any pixel is transparent.
|
|
40
|
+
* Works for any size: windows at each scale, and a whole candidate square.
|
|
41
|
+
*/
|
|
42
|
+
export declare function describeWindow(fields: PixelFields, x0: number, y0: number, w: number, h: number): Descriptor | null;
|
|
43
|
+
/** The three terms of `descriptorDistance`, each already divided by its scale. */
|
|
44
|
+
export interface DescriptorTerms {
|
|
45
|
+
color: number;
|
|
46
|
+
orientation: number;
|
|
47
|
+
energy: number;
|
|
48
|
+
}
|
|
49
|
+
/** Computes the terms `descriptorDistance` combines, so a caller can weigh color apart from structure. */
|
|
50
|
+
export declare const descriptorTerms: (a: Descriptor, b: Descriptor) => DescriptorTerms;
|
|
51
|
+
/**
|
|
52
|
+
* How different two windows look, used for segmentation, region merging and the agreement test inside a square.
|
|
53
|
+
* (Deciding whether two finished crops are one material uses a different, lighting-tolerant
|
|
54
|
+
* `materialDistance` on `Signature`s, below.)
|
|
55
|
+
*
|
|
56
|
+
* Three terms, each divided by its scale in `thresholds.descriptor` so 1 means "one unit apart", then
|
|
57
|
+
* combined as a Euclidean norm: color (how far the histograms must shift to match), edge direction
|
|
58
|
+
* (chi-square between the direction mixes) and edge strength (log ratio of energies).
|
|
59
|
+
* Edge direction counts only as far as both windows have edges clearly above the noise floor to orient.
|
|
60
|
+
*/
|
|
61
|
+
export declare function descriptorDistance(a: Descriptor, b: Descriptor): number;
|
|
62
|
+
/**
|
|
63
|
+
* Brightness-normalized opponent chromaticity (red-green, yellow-blue) of a window's mean color, read back
|
|
64
|
+
* from its histograms, as in `Signature.chroma`: the same paint in sun and shade gives about the same pair.
|
|
65
|
+
*/
|
|
66
|
+
export declare const meanChromaticity: (d: Descriptor) => [number, number];
|
|
67
|
+
/**
|
|
68
|
+
* How useful a square is as a material sample, 0..1: the product of three factors. Penalizes
|
|
69
|
+
* under-exposure (mean luminance near black), blown highlights (windows, glare, mirrors) and squares
|
|
70
|
+
* with neither contrast nor color to search by: the information term is edge energy plus mean channel
|
|
71
|
+
* spread, so a uniform neutral gray scores 0 and is dropped, while a uniformly colored surface (paint,
|
|
72
|
+
* say) can pass. `energy` is the square's own descriptor energy; the rectangle is in analysis pixels.
|
|
73
|
+
*/
|
|
74
|
+
export declare function sampleQuality(fields: PixelFields, x0: number, y0: number, w: number, h: number, energy: number): number;
|
|
75
|
+
/**
|
|
76
|
+
* What a square is made of, with lighting taken out: the same material in sun and in shade has the same
|
|
77
|
+
* chromaticity, edge directions and contrast relative to its brightness, and differs mainly in lightness.
|
|
78
|
+
*/
|
|
79
|
+
export interface Signature {
|
|
80
|
+
/** Mean brightness-normalized opponent chromaticity (red-green, yellow-blue); unitless, roughly -1 to 1. */
|
|
81
|
+
chroma: [number, number];
|
|
82
|
+
/** Log mean luminance; the one lighting-dependent term, so it has the loosest scale in the distance. */
|
|
83
|
+
lightness: number;
|
|
84
|
+
/** Edge strength relative to brightness, so a dim copy of a texture matches the bright one. */
|
|
85
|
+
contrast: number;
|
|
86
|
+
/** The square's edge-direction mix, shared with its `Descriptor`. */
|
|
87
|
+
orientations: Float32Array;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Computes the lighting-tolerant signature of a square (analysis pixels) from the analysis image.
|
|
91
|
+
* `descriptor` is the square's own, already computed; its energy and edge directions are reused.
|
|
92
|
+
*/
|
|
93
|
+
export declare function materialSignature(data: Uint8ClampedArray, width: number, x0: number, y0: number, side: number, descriptor: Descriptor): Signature;
|
|
94
|
+
/** The separate terms of the material distance, each already divided by its scale. */
|
|
95
|
+
export interface MaterialTerms {
|
|
96
|
+
chroma: number;
|
|
97
|
+
contrast: number;
|
|
98
|
+
orientation: number;
|
|
99
|
+
lightness: number;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Compares two squares' signatures one aspect at a time, so a caller (the eval's calibration) can see
|
|
103
|
+
* which aspect separates same-material pairs from different ones. `energyA` and `energyB` are the squares'
|
|
104
|
+
* descriptor energies; they gate the edge-direction term exactly as in `descriptorDistance`.
|
|
105
|
+
*/
|
|
106
|
+
export declare function materialTerms(a: Signature, b: Signature, energyA: number, energyB: number): MaterialTerms;
|
|
107
|
+
/**
|
|
108
|
+
* How different two squares' materials are, ignoring lighting (the Euclidean norm of `materialTerms`):
|
|
109
|
+
* 0 is identical, and ranking calls two crops one material below `thresholds.ranking.duplicateThreshold`.
|
|
110
|
+
*/
|
|
111
|
+
export declare function materialDistance(a: Signature, b: Signature, energyA: number, energyB: number): number;
|
|
112
|
+
//# sourceMappingURL=descriptors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"descriptors.d.ts","sourceRoot":"","sources":["../../src/analysis/descriptors.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// Stage 1 of the pipeline in analyze-surface-regions.ts: measures windows, and compares windows and squares.
|
|
2
|
+
import { thresholds } from "./thresholds.js";
|
|
3
|
+
/**
|
|
4
|
+
* Quantizes color and computes gradient orientation and magnitude for every pixel. Gradients are central
|
|
5
|
+
* differences of brightness, with image borders clamped to the nearest pixel.
|
|
6
|
+
*/
|
|
7
|
+
export function pixelFields({ width, height, data, }) {
|
|
8
|
+
const { colorBins: bins, orientationBins } = thresholds.descriptor;
|
|
9
|
+
const count = width * height;
|
|
10
|
+
const colorBins = new Uint8Array(count * 3);
|
|
11
|
+
const orientationBin = new Uint8Array(count);
|
|
12
|
+
const magnitude = new Float32Array(count);
|
|
13
|
+
const opaque = new Uint8Array(count);
|
|
14
|
+
const luma = new Float32Array(count);
|
|
15
|
+
const chroma = new Float32Array(count);
|
|
16
|
+
for (let i = 0; i < count; i++) {
|
|
17
|
+
const r = data[i * 4];
|
|
18
|
+
const g = data[i * 4 + 1];
|
|
19
|
+
const b = data[i * 4 + 2];
|
|
20
|
+
// Standard perceptual brightness weights (Rec. 601): green counts most, blue least.
|
|
21
|
+
luma[i] = r * 0.299 + g * 0.587 + b * 0.114;
|
|
22
|
+
chroma[i] = Math.max(r, g, b) - Math.min(r, g, b);
|
|
23
|
+
opaque[i] = data[i * 4 + 3] >= thresholds.input.opaqueAlpha ? 1 : 0;
|
|
24
|
+
colorBins[i * 3] = Math.floor((r * bins) / 256);
|
|
25
|
+
colorBins[i * 3 + 1] = Math.floor((g * bins) / 256);
|
|
26
|
+
colorBins[i * 3 + 2] = Math.floor((b * bins) / 256);
|
|
27
|
+
}
|
|
28
|
+
for (let y = 0; y < height; y++) {
|
|
29
|
+
for (let x = 0; x < width; x++) {
|
|
30
|
+
const i = y * width + x;
|
|
31
|
+
const gx = luma[x + 1 < width ? i + 1 : i] - luma[x > 0 ? i - 1 : i];
|
|
32
|
+
const gy = luma[y + 1 < height ? i + width : i] - luma[y > 0 ? i - width : i];
|
|
33
|
+
// gx and gy span two pixels, hence the halving to get levels per pixel.
|
|
34
|
+
magnitude[i] = Math.hypot(gx, gy) / 2;
|
|
35
|
+
// Orientation is axial: an edge and its reverse count as one direction.
|
|
36
|
+
const angle = (Math.atan2(gy, gx) + Math.PI) % Math.PI;
|
|
37
|
+
orientationBin[i] = Math.min(orientationBins - 1, Math.floor((angle * orientationBins) / Math.PI));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
chroma,
|
|
42
|
+
colorBins,
|
|
43
|
+
height,
|
|
44
|
+
luma,
|
|
45
|
+
magnitude,
|
|
46
|
+
opaque,
|
|
47
|
+
orientationBin,
|
|
48
|
+
width,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Describes the pixel rectangle (analysis pixels), or returns null when any pixel is transparent.
|
|
53
|
+
* Works for any size: windows at each scale, and a whole candidate square.
|
|
54
|
+
*/
|
|
55
|
+
export function describeWindow(fields, x0, y0, w, h) {
|
|
56
|
+
const { colorBins: bins, orientationBins } = thresholds.descriptor;
|
|
57
|
+
const cdf = new Float32Array(bins * 3);
|
|
58
|
+
const orientations = new Float32Array(orientationBins);
|
|
59
|
+
let energy = 0;
|
|
60
|
+
for (let y = y0; y < y0 + h; y++) {
|
|
61
|
+
for (let x = x0; x < x0 + w; x++) {
|
|
62
|
+
const i = y * fields.width + x;
|
|
63
|
+
if (!fields.opaque[i]) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
cdf[fields.colorBins[i * 3]]++;
|
|
67
|
+
cdf[bins + fields.colorBins[i * 3 + 1]]++;
|
|
68
|
+
cdf[bins * 2 + fields.colorBins[i * 3 + 2]]++;
|
|
69
|
+
orientations[fields.orientationBin[i]] += fields.magnitude[i];
|
|
70
|
+
energy += fields.magnitude[i];
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const n = w * h;
|
|
74
|
+
// Turn each channel's counts into a running share (0 to 1) of the window's pixels at or below each bin.
|
|
75
|
+
for (let channel = 0; channel < 3; channel++) {
|
|
76
|
+
let running = 0;
|
|
77
|
+
for (let b = 0; b < bins; b++) {
|
|
78
|
+
running += cdf[channel * bins + b] / n;
|
|
79
|
+
cdf[channel * bins + b] = running;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const total = Math.max(1e-6, energy);
|
|
83
|
+
for (let i = 0; i < orientationBins; i++) {
|
|
84
|
+
orientations[i] /= total;
|
|
85
|
+
}
|
|
86
|
+
return { cdf, energy: energy / n, orientations };
|
|
87
|
+
}
|
|
88
|
+
/** Computes the terms `descriptorDistance` combines, so a caller can weigh color apart from structure. */
|
|
89
|
+
export const descriptorTerms = (a, b) => {
|
|
90
|
+
const { colorBins: bins, noiseEnergy, colorScale, orientationScale, energyScale, } = thresholds.descriptor;
|
|
91
|
+
let color = 0;
|
|
92
|
+
for (let i = 0; i < a.cdf.length; i++) {
|
|
93
|
+
color += Math.abs(a.cdf[i] - b.cdf[i]);
|
|
94
|
+
}
|
|
95
|
+
// Summed bin differences become 8-bit levels (each bin is 256 / bins levels wide), averaged over the 3 channels.
|
|
96
|
+
color = (color * (256 / bins)) / 3;
|
|
97
|
+
let chi = 0;
|
|
98
|
+
for (let i = 0; i < a.orientations.length; i++) {
|
|
99
|
+
const sum = a.orientations[i] + b.orientations[i];
|
|
100
|
+
if (sum > 0) {
|
|
101
|
+
chi += (a.orientations[i] - b.orientations[i]) ** 2 / sum;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Edge direction means nothing in a near-flat window: ramps from 0 at the noise floor to 1 at twice it.
|
|
105
|
+
const confidence = Math.max(0, Math.min(1, Math.min(a.energy, b.energy) / noiseEnergy - 1));
|
|
106
|
+
// Adding the noise floor keeps the ratio finite and small when both windows are flat.
|
|
107
|
+
const energy = Math.abs(Math.log((a.energy + noiseEnergy) / (b.energy + noiseEnergy)));
|
|
108
|
+
return {
|
|
109
|
+
color: color / colorScale,
|
|
110
|
+
energy: energy / energyScale,
|
|
111
|
+
// chi / 2 rescales the chi-square sum to 0..1 for two distributions that each sum to 1.
|
|
112
|
+
orientation: ((chi / 2) * confidence) / orientationScale,
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
/**
|
|
116
|
+
* How different two windows look, used for segmentation, region merging and the agreement test inside a square.
|
|
117
|
+
* (Deciding whether two finished crops are one material uses a different, lighting-tolerant
|
|
118
|
+
* `materialDistance` on `Signature`s, below.)
|
|
119
|
+
*
|
|
120
|
+
* Three terms, each divided by its scale in `thresholds.descriptor` so 1 means "one unit apart", then
|
|
121
|
+
* combined as a Euclidean norm: color (how far the histograms must shift to match), edge direction
|
|
122
|
+
* (chi-square between the direction mixes) and edge strength (log ratio of energies).
|
|
123
|
+
* Edge direction counts only as far as both windows have edges clearly above the noise floor to orient.
|
|
124
|
+
*/
|
|
125
|
+
export function descriptorDistance(a, b) {
|
|
126
|
+
const { color, orientation, energy } = descriptorTerms(a, b);
|
|
127
|
+
return Math.hypot(color, orientation, energy);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Brightness-normalized opponent chromaticity (red-green, yellow-blue) of a window's mean color, read back
|
|
131
|
+
* from its histograms, as in `Signature.chroma`: the same paint in sun and shade gives about the same pair.
|
|
132
|
+
*/
|
|
133
|
+
export const meanChromaticity = (d) => {
|
|
134
|
+
const bins = thresholds.descriptor.colorBins;
|
|
135
|
+
const mean = [0, 1, 2].map((channel) => {
|
|
136
|
+
// The mean bin is the sum of the shares above each bin edge; +0.5 moves it to the bin center.
|
|
137
|
+
let above = 0;
|
|
138
|
+
for (let b = 0; b < bins - 1; b += 1) {
|
|
139
|
+
above += 1 - d.cdf[channel * bins + b];
|
|
140
|
+
}
|
|
141
|
+
return ((above + 0.5) * 256) / bins;
|
|
142
|
+
});
|
|
143
|
+
const [r, g, b] = mean;
|
|
144
|
+
const sum = r + g + b + 1;
|
|
145
|
+
return [(r - g) / sum, (r + g - 2 * b) / sum];
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* How useful a square is as a material sample, 0..1: the product of three factors. Penalizes
|
|
149
|
+
* under-exposure (mean luminance near black), blown highlights (windows, glare, mirrors) and squares
|
|
150
|
+
* with neither contrast nor color to search by: the information term is edge energy plus mean channel
|
|
151
|
+
* spread, so a uniform neutral gray scores 0 and is dropped, while a uniformly colored surface (paint,
|
|
152
|
+
* say) can pass. `energy` is the square's own descriptor energy; the rectangle is in analysis pixels.
|
|
153
|
+
*/
|
|
154
|
+
export function sampleQuality(fields, x0, y0, w, h, energy) {
|
|
155
|
+
const q = thresholds.quality;
|
|
156
|
+
let blown = 0;
|
|
157
|
+
let chroma = 0;
|
|
158
|
+
let luma = 0;
|
|
159
|
+
for (let y = y0; y < y0 + h; y++) {
|
|
160
|
+
for (let x = x0; x < x0 + w; x++) {
|
|
161
|
+
const i = y * fields.width + x;
|
|
162
|
+
luma += fields.luma[i];
|
|
163
|
+
chroma += fields.chroma[i];
|
|
164
|
+
if (fields.luma[i] >= q.blownLuma) {
|
|
165
|
+
blown++;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const n = w * h;
|
|
170
|
+
luma /= n;
|
|
171
|
+
chroma /= n;
|
|
172
|
+
const clamp = (v) => Math.max(0, Math.min(1, v));
|
|
173
|
+
// Each factor is 1 when fine and falls linearly to 0 as the problem worsens.
|
|
174
|
+
const exposed = clamp((luma - q.darkFloor) / q.darkSpan);
|
|
175
|
+
const unclipped = 1 - clamp((blown / n - q.blownTolerance) / q.blownSpan);
|
|
176
|
+
const informative = clamp(energy / thresholds.descriptor.noiseEnergy / q.energyShare +
|
|
177
|
+
chroma / q.chromaScale);
|
|
178
|
+
return exposed * unclipped * informative;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Computes the lighting-tolerant signature of a square (analysis pixels) from the analysis image.
|
|
182
|
+
* `descriptor` is the square's own, already computed; its energy and edge directions are reused.
|
|
183
|
+
*/
|
|
184
|
+
export function materialSignature(data, width, x0, y0, side, descriptor) {
|
|
185
|
+
let luma = 0;
|
|
186
|
+
let meanA = 0;
|
|
187
|
+
let meanB = 0;
|
|
188
|
+
let weight = 0;
|
|
189
|
+
for (let y = y0; y < y0 + side; y++) {
|
|
190
|
+
for (let x = x0; x < x0 + side; x++) {
|
|
191
|
+
const i = (y * width + x) * 4;
|
|
192
|
+
const r = data[i];
|
|
193
|
+
const g = data[i + 1];
|
|
194
|
+
const b = data[i + 2];
|
|
195
|
+
// The +1 avoids dividing by zero on pure black.
|
|
196
|
+
const sum = r + g + b + 1;
|
|
197
|
+
// Chromaticity is noisy in the dark, so each pixel counts in proportion to its brightness.
|
|
198
|
+
// Dividing by brightness is what removes the lighting; a and c are the two opponent axes.
|
|
199
|
+
const a = (r - g) / sum;
|
|
200
|
+
const c = (r + g - 2 * b) / sum;
|
|
201
|
+
weight += sum;
|
|
202
|
+
meanA += a * sum;
|
|
203
|
+
meanB += c * sum;
|
|
204
|
+
luma += r * 0.299 + g * 0.587 + b * 0.114;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
meanA /= weight;
|
|
208
|
+
meanB /= weight;
|
|
209
|
+
const meanLuma = luma / (side * side);
|
|
210
|
+
return {
|
|
211
|
+
chroma: [meanA, meanB],
|
|
212
|
+
contrast: descriptor.energy / (meanLuma + thresholds.material.contrastOffset),
|
|
213
|
+
lightness: Math.log(meanLuma + thresholds.material.lightnessOffset),
|
|
214
|
+
orientations: descriptor.orientations,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Compares two squares' signatures one aspect at a time, so a caller (the eval's calibration) can see
|
|
219
|
+
* which aspect separates same-material pairs from different ones. `energyA` and `energyB` are the squares'
|
|
220
|
+
* descriptor energies; they gate the edge-direction term exactly as in `descriptorDistance`.
|
|
221
|
+
*/
|
|
222
|
+
export function materialTerms(a, b, energyA, energyB) {
|
|
223
|
+
const m = thresholds.material;
|
|
224
|
+
let chi = 0;
|
|
225
|
+
for (let i = 0; i < a.orientations.length; i++) {
|
|
226
|
+
const sum = a.orientations[i] + b.orientations[i];
|
|
227
|
+
if (sum > 0) {
|
|
228
|
+
chi += (a.orientations[i] - b.orientations[i]) ** 2 / sum;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const noise = thresholds.descriptor.noiseEnergy;
|
|
232
|
+
const confidence = Math.max(0, Math.min(1, Math.min(energyA, energyB) / noise - 1));
|
|
233
|
+
return {
|
|
234
|
+
chroma: Math.hypot(a.chroma[0] - b.chroma[0], a.chroma[1] - b.chroma[1]) /
|
|
235
|
+
m.chromaScale,
|
|
236
|
+
contrast: Math.abs(Math.log((a.contrast + m.contrastFloor) / (b.contrast + m.contrastFloor))) / m.contrastScale,
|
|
237
|
+
lightness: Math.abs(a.lightness - b.lightness) / m.lightnessScale,
|
|
238
|
+
orientation: ((chi / 2) * confidence) / m.orientationScale,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* How different two squares' materials are, ignoring lighting (the Euclidean norm of `materialTerms`):
|
|
243
|
+
* 0 is identical, and ranking calls two crops one material below `thresholds.ranking.duplicateThreshold`.
|
|
244
|
+
*/
|
|
245
|
+
export function materialDistance(a, b, energyA, energyB) {
|
|
246
|
+
const { chroma, contrast, orientation, lightness } = materialTerms(a, b, energyA, energyB);
|
|
247
|
+
return Math.hypot(chroma, contrast, orientation, lightness);
|
|
248
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { PercentRectangle, Rectangle } from "./types.js";
|
|
2
|
+
/** One candidate region's fate at a pipeline stage; collected only when the caller passes a collector. */
|
|
3
|
+
export interface StageEvent {
|
|
4
|
+
/**
|
|
5
|
+
* Which pipeline step made the decision: window segmentation, fitting a square, ranking, or `timing`,
|
|
6
|
+
* which carries how long a stage took (`detail.ms`, with the stage's name in `pass`).
|
|
7
|
+
*/
|
|
8
|
+
stage: "segment" | "crop" | "rank" | "timing";
|
|
9
|
+
/**
|
|
10
|
+
* Names the candidate. Segment events carry the window scale ("w16", or "w16-merge" for joining, "w16+"
|
|
11
|
+
* for the labels after joining); crop events add the region ("w16#42", or "w16+#42" for a union of
|
|
12
|
+
* segments); rank events carry the provisional candidate id ("surface-w16#42"), not the final "surface-1" id.
|
|
13
|
+
*/
|
|
14
|
+
pass: string;
|
|
15
|
+
outcome: "kept" | "rejected" | "shrunk";
|
|
16
|
+
reason: string;
|
|
17
|
+
/** Region size as a fraction of the analyzed image, when known. */
|
|
18
|
+
coverage?: number;
|
|
19
|
+
/** Largest interior square before any inset, and the square finally proposed (analysis pixels). */
|
|
20
|
+
interior?: Rectangle;
|
|
21
|
+
rect?: Rectangle;
|
|
22
|
+
/** The proposed crop in source percentages, for rank-stage events. */
|
|
23
|
+
crop?: PercentRectangle;
|
|
24
|
+
/** Per-pixel segment ids (analysis image size, -1 for none) from a segmentation pass, for drawing the raw segmentation. */
|
|
25
|
+
labels?: Int32Array;
|
|
26
|
+
/** Measured values behind the decision, e.g. dispersion, quality or score. A same-material rejection names its `twin`. */
|
|
27
|
+
detail?: Record<string, number | string>;
|
|
28
|
+
}
|
|
29
|
+
/** Dev-only sink for stage decisions; analysis output is identical with or without it. */
|
|
30
|
+
export interface Diagnostics {
|
|
31
|
+
/** Appended to in pipeline order; the caller creates the array and reads it afterwards. */
|
|
32
|
+
events: StageEvent[];
|
|
33
|
+
}
|
|
34
|
+
/** Records an event when a collector is present; otherwise does nothing. */
|
|
35
|
+
export declare function record(diagnostics: Diagnostics | undefined, event: StageEvent): void;
|
|
36
|
+
/** Adds up the time spent in named stages. Without a collector it does nothing and never reads the clock. */
|
|
37
|
+
export interface Stopwatch {
|
|
38
|
+
/** Credits the time since the last mark (or since the stopwatch started) to `stage`. */
|
|
39
|
+
mark: (stage: string) => void;
|
|
40
|
+
/** Records one `timing` event per stage marked, in the order each was first marked. */
|
|
41
|
+
report: () => void;
|
|
42
|
+
}
|
|
43
|
+
/** Starts a stopwatch that reports into `diagnostics`. */
|
|
44
|
+
export declare const stopwatch: (diagnostics: Diagnostics | undefined) => Stopwatch;
|
|
45
|
+
//# sourceMappingURL=diagnostics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../src/analysis/diagnostics.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE9D,0GAA0G;AAC1G,MAAM,WAAW,UAAU;IACzB;;;OAGG;IACH,KAAK,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC;IAC9C;;;;OAIG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,QAAQ,CAAC;IACxC,MAAM,EAAE,MAAM,CAAC;IACf,mEAAmE;IACnE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,sEAAsE;IACtE,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACxB,2HAA2H;IAC3H,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,0HAA0H;IAC1H,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;CAC1C;AAED,0FAA0F;AAC1F,MAAM,WAAW,WAAW;IAC1B,2FAA2F;IAC3F,MAAM,EAAE,UAAU,EAAE,CAAC;CACtB;AAED,4EAA4E;AAC5E,wBAAgB,MAAM,CACpB,WAAW,EAAE,WAAW,GAAG,SAAS,EACpC,KAAK,EAAE,UAAU,GAChB,IAAI,CAEN;AAED,6GAA6G;AAC7G,MAAM,WAAW,SAAS;IACxB,wFAAwF;IACxF,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9B,uFAAuF;IACvF,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAOD,0DAA0D;AAC1D,eAAO,MAAM,SAAS,gBAAiB,WAAW,GAAG,SAAS,KAAG,SAwBhE,CAAC"}
|