@thi.ng/geom-sdf 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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2022-06-20T17:33:30Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
8
+
9
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
10
+ and/or version bumps of transitive dependencies.
11
+
12
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/geom-sdf@0.1.0) (2022-06-20)
13
+
14
+ #### 🚀 Features
15
+
16
+ - import as new pkg ([06dcca2](https://github.com/thi-ng/umbrella/commit/06dcca2))
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+
3
+ # ![geom-sdf](https://media.thi.ng/umbrella/banners/thing-geom-sdf.svg?6069668d)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/geom-sdf.svg)](https://www.npmjs.com/package/@thi.ng/geom-sdf)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/geom-sdf.svg)
7
+ [![Twitter Follow](https://img.shields.io/twitter/follow/thing_umbrella.svg?style=flat-square&label=twitter)](https://twitter.com/thing_umbrella)
8
+
9
+ This project is part of the
10
+ [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo.
11
+
12
+ - [About](#about)
13
+ - [Status](#status)
14
+ - [Installation](#installation)
15
+ - [Dependencies](#dependencies)
16
+ - [API](#api)
17
+ - [Authors](#authors)
18
+ - [License](#license)
19
+
20
+ ## About
21
+
22
+ 2D Signed Distance Field creation from [@thi.ng/geom](https://github.com/thi-ng/umbrella/tree/develop/packages/geom) shapes, conversions, sampling, combinators.
23
+
24
+ ### Status
25
+
26
+ **ALPHA** - bleeding edge / work-in-progress
27
+
28
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Bgeom-sdf%5D+in%3Atitle)
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ yarn add @thi.ng/geom-sdf
34
+ ```
35
+
36
+ ES module import:
37
+
38
+ ```html
39
+ <script type="module" src="https://cdn.skypack.dev/@thi.ng/geom-sdf"></script>
40
+ ```
41
+
42
+ [Skypack documentation](https://docs.skypack.dev/)
43
+
44
+ For Node.js REPL:
45
+
46
+ ```text
47
+ # with flag only for < v16
48
+ node --experimental-repl-await
49
+
50
+ > const geomSdf = await import("@thi.ng/geom-sdf");
51
+ ```
52
+
53
+ Package sizes (gzipped, pre-treeshake): ESM: 2.61 KB
54
+
55
+ ## Dependencies
56
+
57
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
58
+ - [@thi.ng/checks](https://github.com/thi-ng/umbrella/tree/develop/packages/checks)
59
+ - [@thi.ng/defmulti](https://github.com/thi-ng/umbrella/tree/develop/packages/defmulti)
60
+ - [@thi.ng/errors](https://github.com/thi-ng/umbrella/tree/develop/packages/errors)
61
+ - [@thi.ng/geom](https://github.com/thi-ng/umbrella/tree/develop/packages/geom)
62
+ - [@thi.ng/geom-api](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-api)
63
+ - [@thi.ng/geom-isoline](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-isoline)
64
+ - [@thi.ng/math](https://github.com/thi-ng/umbrella/tree/develop/packages/math)
65
+ - [@thi.ng/transducers](https://github.com/thi-ng/umbrella/tree/develop/packages/transducers)
66
+ - [@thi.ng/vectors](https://github.com/thi-ng/umbrella/tree/develop/packages/vectors)
67
+
68
+ ## API
69
+
70
+ [Generated API docs](https://docs.thi.ng/umbrella/geom-sdf/)
71
+
72
+ ```js
73
+ import { asSvg, bounds, circle, group, simplify, svgDoc } from "@thi.ng/geom";
74
+ import { asPolygons, asSDF, sample2d } from "@thi.ng/geom-sdf";
75
+ import { range, repeatedly } from "@thi.ng/transducers";
76
+ import { randMinMax2 } from "@thi.ng/vectors";
77
+ import { writeFileSync } from "fs";
78
+
79
+ const RES = [256, 256];
80
+
81
+ // create a group of 20 random circle shapes
82
+ // the special `__sdf` attrib object is used to control the conversion later
83
+ // the `smooth` option will combine the circles using the `smoothUnion()` operator
84
+ // see: https://docs.thi.ng/umbrella/geom-sdf/interfaces/SDFAttribs.html
85
+ const scene = group({ stroke: "red", __sdf: { smooth: 20 } }, [
86
+ ...repeatedly(
87
+ () =>
88
+ circle(
89
+ randMinMax2([], [-100, -100], [100, 100]),
90
+ 5 + Math.random() * 15
91
+ ),
92
+ 20
93
+ ),
94
+ ]);
95
+
96
+ // compute bounding box + some extra margin
97
+ // the margin is to ensure
98
+ const sceneBounds = bounds(scene, 40);
99
+
100
+ // convert to an SDF distance function
101
+ // more information about supported shape types:
102
+ // https://docs.thi.ng/umbrella/geom-sdf/modules.html#asSDF
103
+ const sdf = asSDF(scene);
104
+
105
+ // sample SDF in given bounding rect and resolution
106
+ const image = sample2d(sdf, sceneBounds, RES);
107
+
108
+ // extract contour polygons from given image
109
+ // in this case the contours extracted are at distances in the [0..32) interval
110
+ // afterwards we also simplify the resulting polygons using the Douglas-Peucker algorithm
111
+ // see: https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
112
+ const contours = asPolygons(image, sceneBounds, RES, range(0, 32, 4)).map(
113
+ (p) => simplify(p, 0.25)
114
+ );
115
+
116
+ // convert to SVG and output as file
117
+ writeFileSync(
118
+ "export/metaballs.svg",
119
+ asSvg(
120
+ svgDoc(
121
+ { fill: "none" },
122
+ // contour polygons
123
+ group({ stroke: "#000" }, contours),
124
+ // original geometry
125
+ scene
126
+ )
127
+ )
128
+ );
129
+ ```
130
+
131
+ Results:
132
+
133
+ | using `circle()` | using `rect()` |
134
+ |------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
135
+ | ![metaballs based on circles](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/geom-sdf/metaballs.png) | ![metaballs based on rectangles](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/geom-sdf/metaballs-rect.png) |
136
+
137
+ ## Authors
138
+
139
+ Karsten Schmidt
140
+
141
+ If this project contributes to an academic publication, please cite it as:
142
+
143
+ ```bibtex
144
+ @misc{thing-geom-sdf,
145
+ title = "@thi.ng/geom-sdf",
146
+ author = "Karsten Schmidt",
147
+ note = "https://thi.ng/geom-sdf",
148
+ year = 2022
149
+ }
150
+ ```
151
+
152
+ ## License
153
+
154
+ &copy; 2022 Karsten Schmidt // Apache Software License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { Fn } from "@thi.ng/api";
2
+ import type { ReadonlyVec } from "@thi.ng/vectors";
3
+ export declare type SDFn = Fn<ReadonlyVec, number>;
4
+ export declare type SDFCombineOp = "union" | "isec" | "diff";
5
+ export interface SDFAttribs {
6
+ combine: SDFCombineOp;
7
+ smooth: number;
8
+ flip: boolean;
9
+ abs: boolean;
10
+ round: number;
11
+ }
12
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/as-sdf.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { MultiFn1 } from "@thi.ng/defmulti";
2
+ import type { IShape } from "@thi.ng/geom-api";
3
+ import type { SDFn } from "./api.js";
4
+ /**
5
+ * Takes an {@link @thi.ng/geom-api#IShape} instance (possibly a tree, e.g. via
6
+ * {@link @thi.ng/geom#group}) and converts it into a {@link SDFn}.
7
+ *
8
+ * @remarks
9
+ * Currently supported shape types:
10
+ *
11
+ * - circle
12
+ * - ellipse
13
+ * - group
14
+ * - line
15
+ * - points
16
+ * - polygon
17
+ * - polyline
18
+ * - quadratic bezier
19
+ * - rect
20
+ */
21
+ export declare const asSDF: MultiFn1<IShape, SDFn>;
22
+ //# sourceMappingURL=as-sdf.d.ts.map
package/as-sdf.js ADDED
@@ -0,0 +1,74 @@
1
+ import { DEFAULT, defmulti } from "@thi.ng/defmulti/defmulti";
2
+ import { unsupported } from "@thi.ng/errors/unsupported";
3
+ import { __dispatch } from "@thi.ng/geom/internal/dispatch";
4
+ import { maddN2 } from "@thi.ng/vectors/maddn";
5
+ import { difference, intersection, smoothDifference, smoothIntersection, smoothUnion, union, } from "./ops.js";
6
+ import { box2, circle2, DEFAULT_ATTRIBS, ellipse2, line2, points2, polygon2, polyline2, quadratic2, withSDFAttribs, } from "./shapes.js";
7
+ /**
8
+ * Takes an {@link @thi.ng/geom-api#IShape} instance (possibly a tree, e.g. via
9
+ * {@link @thi.ng/geom#group}) and converts it into a {@link SDFn}.
10
+ *
11
+ * @remarks
12
+ * Currently supported shape types:
13
+ *
14
+ * - circle
15
+ * - ellipse
16
+ * - group
17
+ * - line
18
+ * - points
19
+ * - polygon
20
+ * - polyline
21
+ * - quadratic bezier
22
+ * - rect
23
+ */
24
+ export const asSDF = defmulti(__dispatch, {
25
+ quad: "poly",
26
+ tri: "poly",
27
+ }, {
28
+ [DEFAULT]: ($) => unsupported(`shape type: ${$.type}`),
29
+ circle: ($) => circle2($.pos, $.r, __sdfAttribs($.attribs)),
30
+ ellipse: ($) => ellipse2($.pos, $.r, __sdfAttribs($.attribs)),
31
+ group: ({ attribs, children }) => {
32
+ const $attribs = { ...DEFAULT_ATTRIBS, ...__sdfAttribs(attribs) };
33
+ const $children = children.map(asSDF);
34
+ let res;
35
+ if ($children.length > 1) {
36
+ switch ($attribs.combine) {
37
+ case "diff":
38
+ res =
39
+ $attribs.smooth !== 0
40
+ ? smoothDifference($attribs.smooth, ...$children)
41
+ : difference(...$children);
42
+ break;
43
+ case "isec":
44
+ res =
45
+ $attribs.smooth !== 0
46
+ ? smoothIntersection($attribs.smooth, ...$children)
47
+ : intersection($children);
48
+ break;
49
+ case "union":
50
+ default: {
51
+ res =
52
+ $attribs.smooth !== 0
53
+ ? smoothUnion($attribs.smooth, ...$children)
54
+ : union($children);
55
+ }
56
+ }
57
+ }
58
+ else if ($children.length) {
59
+ res = $children[0];
60
+ }
61
+ else {
62
+ return $attribs.flip ? () => -Infinity : () => Infinity;
63
+ }
64
+ return withSDFAttribs(res, $attribs);
65
+ },
66
+ line: ({ points: [a, b], attribs }) => line2(a, b, __sdfAttribs(attribs)),
67
+ points: ($) => points2($.points, __sdfAttribs($.attribs)),
68
+ poly: ($) => polygon2($.points, __sdfAttribs($.attribs)),
69
+ polyline: ($) => polyline2($.points, __sdfAttribs($.attribs)),
70
+ quadratic: ({ points: [a, b, c], attribs }) => quadratic2(a, b, c, __sdfAttribs(attribs)),
71
+ rect: ({ pos, size, attribs }) => box2(maddN2([], size, 0.5, pos), size, __sdfAttribs(attribs)),
72
+ });
73
+ /** @internal */
74
+ const __sdfAttribs = (attribs) => attribs ? attribs.__sdf : null;
package/dist.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { ReadonlyVec } from "@thi.ng/vectors/api";
2
+ export declare const distCircle2: (p: ReadonlyVec, radius: number) => number;
3
+ export declare const distBox2: (p: ReadonlyVec, size: ReadonlyVec) => number;
4
+ export declare const distPolygon2: (pts: ReadonlyVec[], p: ReadonlyVec) => number;
5
+ export declare const distSegment2: (a: ReadonlyVec, b: ReadonlyVec, p: ReadonlyVec) => number;
6
+ export declare const distPolyline2: (pts: ReadonlyVec[], p: ReadonlyVec) => number;
7
+ export declare const distArc2: (p: ReadonlyVec, apert: ReadonlyVec, ra: number, rb: number) => number;
8
+ export declare const distQuadratic2: (pos: ReadonlyVec, a: ReadonlyVec, b: ReadonlyVec, c: ReadonlyVec, signed?: boolean) => number;
9
+ export declare const distEllipse2: ([px, py]: ReadonlyVec, [abx, aby]: ReadonlyVec) => number;
10
+ //# sourceMappingURL=dist.d.ts.map
package/dist.js ADDED
@@ -0,0 +1,150 @@
1
+ import { SQRT3 } from "@thi.ng/math";
2
+ import { clamp01 } from "@thi.ng/math/interval";
3
+ import { abs2 } from "@thi.ng/vectors/abs";
4
+ import { add2 } from "@thi.ng/vectors/add";
5
+ import { ZERO2 } from "@thi.ng/vectors/api";
6
+ import { cross2 } from "@thi.ng/vectors/cross";
7
+ import { distSq2 } from "@thi.ng/vectors/distsq";
8
+ import { dot2 } from "@thi.ng/vectors/dot";
9
+ import { every3 } from "@thi.ng/vectors/every";
10
+ import { maddN2 } from "@thi.ng/vectors/maddn";
11
+ import { magSq2 } from "@thi.ng/vectors/magsq";
12
+ import { max2 } from "@thi.ng/vectors/max";
13
+ import { mul2 } from "@thi.ng/vectors/mul";
14
+ import { mulN2 } from "@thi.ng/vectors/muln";
15
+ import { powN2 } from "@thi.ng/vectors/pown";
16
+ import { sign2 } from "@thi.ng/vectors/sign";
17
+ import { some3 } from "@thi.ng/vectors/some";
18
+ import { sub2 } from "@thi.ng/vectors/sub";
19
+ const mag2 = (v) => Math.sqrt(magSq2(v));
20
+ export const distCircle2 = (p, radius) => mag2(p) - radius;
21
+ export const distBox2 = (p, size) => {
22
+ const d = sub2(null, abs2([], p), size);
23
+ return Math.min(Math.max(d[0], d[1]), 0) + mag2(max2(null, d, ZERO2));
24
+ };
25
+ export const distPolygon2 = (pts, p) => {
26
+ let d = distSq2(p, pts[0]);
27
+ let s = 1;
28
+ const py = p[1];
29
+ const t1 = [];
30
+ const t2 = [];
31
+ const t3 = [];
32
+ for (let n = pts.length, i = 0, j = n - 1; i < n; j = i, i++) {
33
+ const pi = pts[i];
34
+ const pj = pts[j];
35
+ const e = sub2(t1, pj, pi);
36
+ const w = sub2(t2, p, pi);
37
+ d = Math.min(d, distSq2(w, mulN2(t3, e, clamp01(dot2(w, e) / magSq2(e)))));
38
+ const c = [py >= pi[1], py < pj[1], e[0] * w[1] > e[1] * w[0]];
39
+ if (every3(c) || !some3(c))
40
+ s *= -1;
41
+ }
42
+ return s * Math.sqrt(d);
43
+ };
44
+ export const distSegment2 = (a, b, p) => {
45
+ const pa = sub2([], p, a);
46
+ const ba = sub2([], b, a);
47
+ const h = clamp01(dot2(pa, ba) / magSq2(ba));
48
+ return mag2(sub2(null, pa, mulN2(null, ba, h)));
49
+ };
50
+ export const distPolyline2 = (pts, p) => {
51
+ let d = Infinity;
52
+ for (let i = 1, n = pts.length; i < n; i++) {
53
+ d = Math.min(d, distSegment2(pts[i - 1], pts[i], p));
54
+ }
55
+ return d;
56
+ };
57
+ export const distArc2 = (p, apert, ra, rb) => {
58
+ const q = [Math.abs(p[0]), p[1]];
59
+ return ((apert[1] * q[0] > apert[0] * q[1]
60
+ ? mag2(maddN2(q, apert, -ra, q))
61
+ : Math.abs(mag2(q) - ra)) - rb);
62
+ };
63
+ export const distQuadratic2 = (pos, a, b, c, signed = true) => {
64
+ const aa = sub2([], b, a);
65
+ const bb = add2(null, maddN2([], b, -2, a), c);
66
+ const cc = mulN2([], aa, 2);
67
+ const dd = sub2([], a, pos);
68
+ const kk = 1 / magSq2(bb);
69
+ const kx = kk * dot2(aa, bb);
70
+ const ky = (kk * (2 * magSq2(aa) + dot2(dd, bb))) / 3;
71
+ const kz = kk * dot2(dd, aa);
72
+ const p = ky - kx * kx;
73
+ const q = kx * (2 * kx * kx - 3 * ky) + kz;
74
+ const p3 = p * p * p;
75
+ const q2 = q * q;
76
+ let h = q2 + 4 * p3;
77
+ if (h >= 0) {
78
+ h = Math.sqrt(h);
79
+ const x = [(h - q) / 2, (-h - q) / 2];
80
+ const uv = mul2(null, sign2([], x), powN2([], abs2([], x), 1 / 3));
81
+ const t = clamp01(uv[0] + uv[1] - kx);
82
+ const qq = maddN2(null, maddN2([], bb, t, cc), t, dd);
83
+ return (mag2(qq) *
84
+ (signed ? Math.sign(cross2(maddN2([], bb, 2 * t, cc), qq)) : 1));
85
+ }
86
+ else {
87
+ const z = Math.sqrt(-p);
88
+ const v = Math.acos(q / (p * z * 2)) / 3;
89
+ const m = Math.cos(v);
90
+ const n = Math.sin(v) * 1.732050808;
91
+ const tx = clamp01((m + m) * z - kx);
92
+ const ty = clamp01((-n - m) * z - kx);
93
+ const qx = maddN2(null, maddN2([], bb, tx, cc), tx, dd);
94
+ const dx = magSq2(qx);
95
+ const qy = maddN2(null, maddN2([], bb, ty, cc), ty, dd);
96
+ const dy = magSq2(qy);
97
+ if (dx < dy) {
98
+ return (Math.sqrt(dx) *
99
+ (signed ? Math.sign(cross2(maddN2([], bb, 2 * tx, cc), qx)) : 1));
100
+ }
101
+ else {
102
+ return (Math.sqrt(dy) *
103
+ (signed ? Math.sign(cross2(maddN2([], bb, 2 * ty, cc), qy)) : 1));
104
+ }
105
+ }
106
+ };
107
+ export const distEllipse2 = ([px, py], [abx, aby]) => {
108
+ px = Math.abs(px);
109
+ py = Math.abs(py);
110
+ if (px > py) {
111
+ let t = px;
112
+ px = py;
113
+ py = t;
114
+ t = abx;
115
+ abx = aby;
116
+ aby = t;
117
+ }
118
+ const l = aby * aby - abx * abx;
119
+ const m = (abx * px) / l;
120
+ const m2 = m * m;
121
+ const n = (aby * py) / l;
122
+ const n2 = n * n;
123
+ const c = (m2 + n2 - 1) / 3;
124
+ const c3 = c * c * c;
125
+ const mn2 = m2 * n2;
126
+ const d = c3 + mn2;
127
+ const q = c3 + mn2 * 2;
128
+ const g = m + m * n2;
129
+ let co;
130
+ if (d < 0) {
131
+ const h = Math.acos(q / c3) / 3;
132
+ const s = Math.cos(h);
133
+ const t = Math.sin(h) * SQRT3;
134
+ const rx = Math.sqrt(-c * (s + t + 2) + m2);
135
+ const ry = Math.sqrt(-c * (s - t + 2) + m2);
136
+ co = (ry + Math.sign(l) * rx + Math.abs(g) / (rx * ry) - m) / 2;
137
+ }
138
+ else {
139
+ const h = 2 * m * n * Math.sqrt(d);
140
+ const s = Math.sign(q + h) * Math.cbrt(Math.abs(q + h));
141
+ const u = Math.sign(q - h) * Math.cbrt(Math.abs(q - h));
142
+ const rx = -s - u - c * 4 + 2 * m2;
143
+ const ry = (s - u) * SQRT3;
144
+ const rm = Math.hypot(rx, ry);
145
+ co = (ry / Math.sqrt(rm - rx) + (2 * g) / rm - m) / 2;
146
+ }
147
+ const rx = abx * co;
148
+ const ry = aby * Math.sqrt(1 - co * co);
149
+ return Math.hypot(rx - px, ry - py) * Math.sign(py - ry);
150
+ };
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./api.js";
2
+ export * from "./as-sdf.js";
3
+ export * from "./dist.js";
4
+ export * from "./ops.js";
5
+ export * from "./sample.js";
6
+ export * from "./shapes.js";
7
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./api.js";
2
+ export * from "./as-sdf.js";
3
+ export * from "./dist.js";
4
+ export * from "./ops.js";
5
+ export * from "./sample.js";
6
+ export * from "./shapes.js";
package/ops.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { SDFn } from "./api.js";
2
+ export declare const abs: (sdf: SDFn) => SDFn;
3
+ export declare const flip: (sdf: SDFn) => SDFn;
4
+ export declare const round: (sdf: SDFn, r: number) => SDFn;
5
+ export declare const union: (children: SDFn[]) => SDFn;
6
+ export declare const intersection: (children: SDFn[]) => SDFn;
7
+ export declare const difference: (a: SDFn, ...children: SDFn[]) => SDFn;
8
+ export declare const smoothUnion: (k: number, a: SDFn, ...children: SDFn[]) => SDFn;
9
+ export declare const smoothIntersection: (k: number, a: SDFn, ...children: SDFn[]) => SDFn;
10
+ export declare const smoothDifference: (k: number, a: SDFn, ...children: SDFn[]) => SDFn;
11
+ //# sourceMappingURL=ops.d.ts.map
package/ops.js ADDED
@@ -0,0 +1,22 @@
1
+ import { clamp01, mix } from "@thi.ng/math";
2
+ export const abs = (sdf) => (p) => Math.abs(sdf(p));
3
+ export const flip = (sdf) => (p) => -sdf(p);
4
+ export const round = (sdf, r) => (p) => sdf(p) - r;
5
+ export const union = (children) => (p) => children.reduce((acc, f) => Math.min(acc, f(p)), Infinity);
6
+ export const intersection = (children) => (p) => children.reduce((acc, f) => Math.max(acc, f(p)), -Infinity);
7
+ export const difference = (a, ...children) => (p) => children.reduce((acc, f) => Math.max(acc, -f(p)), a(p));
8
+ export const smoothUnion = (k, a, ...children) => (p) => children.reduce((acc, f) => {
9
+ const d = f(p);
10
+ const h = clamp01(0.5 + (0.5 * (d - acc)) / k);
11
+ return mix(d, acc, h) - k * h * (1 - h);
12
+ }, a(p));
13
+ export const smoothIntersection = (k, a, ...children) => (p) => children.reduce((acc, f) => {
14
+ const d = f(p);
15
+ const h = clamp01(0.5 - (0.5 * (d - acc)) / k);
16
+ return mix(d, acc, h) + k * h * (1 - h);
17
+ }, a(p));
18
+ export const smoothDifference = (k, a, ...children) => (p) => children.reduce((acc, f) => {
19
+ const d = f(p);
20
+ const h = clamp01(0.5 - (0.5 * (acc + d)) / k);
21
+ return mix(acc, -d, h) + k * h * (1 - h);
22
+ }, a(p));
package/package.json ADDED
@@ -0,0 +1,114 @@
1
+ {
2
+ "name": "@thi.ng/geom-sdf",
3
+ "version": "0.1.0",
4
+ "description": "2D Signed Distance Field creation from @thi.ng/geom shapes, conversions, sampling, combinators",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/thi-ng/umbrella.git"
12
+ },
13
+ "homepage": "https://github.com/thi-ng/umbrella/tree/master/packages/geom-sdf#readme",
14
+ "funding": [
15
+ {
16
+ "type": "github",
17
+ "url": "https://github.com/sponsors/postspectacular"
18
+ },
19
+ {
20
+ "type": "patreon",
21
+ "url": "https://patreon.com/thing_umbrella"
22
+ }
23
+ ],
24
+ "author": "Karsten Schmidt <k+npm@thi.ng>",
25
+ "license": "Apache-2.0",
26
+ "scripts": {
27
+ "build": "yarn clean && tsc --declaration",
28
+ "clean": "rimraf '*.js' '*.d.ts' '*.map' doc",
29
+ "doc": "typedoc --excludePrivate --excludeInternal --out doc src/index.ts",
30
+ "doc:ae": "mkdir -p .ae/doc .ae/temp && api-extractor run --local --verbose",
31
+ "doc:readme": "yarn doc:stats && tools:readme",
32
+ "doc:stats": "tools:module-stats",
33
+ "pub": "yarn npm publish --access public",
34
+ "test": "testament test"
35
+ },
36
+ "dependencies": {
37
+ "@thi.ng/api": "^8.3.7",
38
+ "@thi.ng/checks": "^3.2.1",
39
+ "@thi.ng/defmulti": "^2.1.7",
40
+ "@thi.ng/errors": "^2.1.7",
41
+ "@thi.ng/geom": "^3.3.0",
42
+ "@thi.ng/geom-api": "^3.2.0",
43
+ "@thi.ng/geom-isoline": "^2.1.14",
44
+ "@thi.ng/math": "^5.3.3",
45
+ "@thi.ng/transducers": "^8.3.5",
46
+ "@thi.ng/vectors": "^7.5.6"
47
+ },
48
+ "devDependencies": {
49
+ "@microsoft/api-extractor": "^7.25.0",
50
+ "@thi.ng/testament": "^0.2.8",
51
+ "rimraf": "^3.0.2",
52
+ "tools": "^0.0.1",
53
+ "typedoc": "^0.22.17",
54
+ "typescript": "^4.7.3"
55
+ },
56
+ "keywords": [
57
+ "2d",
58
+ "arc",
59
+ "circle",
60
+ "bezier",
61
+ "conversion",
62
+ "distance",
63
+ "field",
64
+ "geometry",
65
+ "line",
66
+ "rect",
67
+ "sdf",
68
+ "shape",
69
+ "typescript"
70
+ ],
71
+ "publishConfig": {
72
+ "access": "public"
73
+ },
74
+ "browser": {
75
+ "process": false,
76
+ "setTimeout": false
77
+ },
78
+ "engines": {
79
+ "node": ">=14"
80
+ },
81
+ "files": [
82
+ "*.js",
83
+ "*.d.ts"
84
+ ],
85
+ "exports": {
86
+ ".": {
87
+ "default": "./index.js"
88
+ },
89
+ "./api": {
90
+ "default": "./api.js"
91
+ },
92
+ "./as-sdf": {
93
+ "default": "./as-sdf.js"
94
+ },
95
+ "./dist": {
96
+ "default": "./dist.js"
97
+ },
98
+ "./ops": {
99
+ "default": "./ops.js"
100
+ },
101
+ "./sample": {
102
+ "default": "./sample.js"
103
+ },
104
+ "./shapes": {
105
+ "default": "./shapes.js"
106
+ }
107
+ },
108
+ "thi.ng": {
109
+ "parent": "@thi.ng/geom",
110
+ "status": "alpha",
111
+ "year": 2022
112
+ },
113
+ "gitHead": "f50e292ecc7dc74a6705b07fc739bf827cc5efd7\n"
114
+ }
package/sample.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { NumericArray } from "@thi.ng/api";
2
+ import type { Polygon } from "@thi.ng/geom";
3
+ import type { AABBLike } from "@thi.ng/geom-api";
4
+ import { ReadonlyVec } from "@thi.ng/vectors";
5
+ import type { SDFn } from "./api.js";
6
+ export declare const sample2d: (sdf: SDFn, { pos: [px, py], size: [width, height] }: AABBLike, [resX, resY]: ReadonlyVec, buf?: NumericArray) => NumericArray;
7
+ export declare const asPolygons: (sdf: NumericArray | SDFn, bounds: AABBLike, res: ReadonlyVec, isoLevels?: Iterable<number>) => Polygon[];
8
+ //# sourceMappingURL=sample.d.ts.map
package/sample.js ADDED
@@ -0,0 +1,37 @@
1
+ import { isFunction } from "@thi.ng/checks/is-function";
2
+ import { assert } from "@thi.ng/errors/assert";
3
+ import { isolines, setBorder } from "@thi.ng/geom-isoline";
4
+ import { polygon } from "@thi.ng/geom/polygon";
5
+ import { comp } from "@thi.ng/transducers/comp";
6
+ import { map } from "@thi.ng/transducers/map";
7
+ import { mapcat } from "@thi.ng/transducers/mapcat";
8
+ import { push } from "@thi.ng/transducers/push";
9
+ import { transduce } from "@thi.ng/transducers/transduce";
10
+ import { add2, div2 } from "@thi.ng/vectors";
11
+ export const sample2d = (sdf, { pos: [px, py], size: [width, height] }, [resX, resY], buf) => {
12
+ if (buf) {
13
+ assert(buf.length >= resX * resY, "insufficient buffer size");
14
+ }
15
+ else {
16
+ buf = new Float32Array(resX * resY);
17
+ }
18
+ const dx = width / (resX - 1);
19
+ const dy = height / (resY - 1);
20
+ const p = [0, 0];
21
+ for (let y = 0, i = 0; y < resY; y++) {
22
+ p[1] = py + y * dy;
23
+ for (let x = 0; x < resX; x++, i++) {
24
+ p[0] = px + x * dx;
25
+ buf[i] = sdf(p);
26
+ }
27
+ }
28
+ return buf;
29
+ };
30
+ export const asPolygons = (sdf, bounds, res, isoLevels = [0]) => {
31
+ const $sdf = isFunction(sdf) ? sample2d(sdf, bounds, res) : sdf;
32
+ const { pos, size } = bounds;
33
+ const [resX, resY] = res;
34
+ setBorder($sdf, resX, resY, 1e6);
35
+ const scale = div2([], size, [resX - 1, resY - 1]);
36
+ return transduce(comp(mapcat((iso) => isolines($sdf, resX, resY, iso, scale)), map((pts) => polygon(pts.map((p) => add2(null, p, pos))))), push(), isoLevels);
37
+ };
package/shapes.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { ReadonlyVec } from "@thi.ng/vectors";
2
+ import type { SDFAttribs, SDFn } from "./api.js";
3
+ /** @internal */
4
+ export declare const DEFAULT_ATTRIBS: SDFAttribs;
5
+ export declare const withSDFAttribs: (fn: SDFn, attribs?: Partial<SDFAttribs>) => SDFn;
6
+ export declare const arc2: (apert: ReadonlyVec, ra: number, rb: number, attribs?: Partial<SDFAttribs>) => SDFn;
7
+ export declare const box2: (center: ReadonlyVec, size: ReadonlyVec, attribs?: Partial<SDFAttribs>) => SDFn;
8
+ export declare const circle2: (center: ReadonlyVec, radius: number, attribs?: Partial<SDFAttribs>) => SDFn;
9
+ export declare const ellipse2: (center: ReadonlyVec, radii: ReadonlyVec, attribs?: Partial<SDFAttribs>) => SDFn;
10
+ export declare const line2: (a: ReadonlyVec, b: ReadonlyVec, attribs?: Partial<SDFAttribs>) => SDFn;
11
+ export declare const points2: (pts: ReadonlyVec[], attribs?: Partial<SDFAttribs>) => SDFn;
12
+ export declare const polygon2: (pts: ReadonlyVec[], attribs?: Partial<SDFAttribs>) => SDFn;
13
+ export declare const polyline2: (pts: ReadonlyVec[], attribs?: Partial<SDFAttribs>) => SDFn;
14
+ export declare const quadratic2: (a: ReadonlyVec, b: ReadonlyVec, c: ReadonlyVec, attribs?: Partial<SDFAttribs>) => SDFn;
15
+ //# sourceMappingURL=shapes.d.ts.map
package/shapes.js ADDED
@@ -0,0 +1,33 @@
1
+ import { distSq2 } from "@thi.ng/vectors";
2
+ import { sub2 } from "@thi.ng/vectors/sub";
3
+ import { distArc2, distBox2, distCircle2, distEllipse2, distPolygon2, distPolyline2, distQuadratic2, distSegment2, } from "./dist.js";
4
+ import { abs as $abs, flip as $flip, round as $round } from "./ops.js";
5
+ /** @internal */
6
+ export const DEFAULT_ATTRIBS = {
7
+ abs: false,
8
+ combine: "union",
9
+ flip: false,
10
+ round: 0,
11
+ smooth: 0,
12
+ };
13
+ export const withSDFAttribs = (fn, attribs) => {
14
+ if (attribs) {
15
+ const { abs, flip, round } = { ...DEFAULT_ATTRIBS, ...attribs };
16
+ if (abs)
17
+ fn = $abs(fn);
18
+ if (round > 0)
19
+ fn = $round(fn, round);
20
+ if (flip)
21
+ fn = $flip(fn);
22
+ }
23
+ return fn;
24
+ };
25
+ export const arc2 = (apert, ra, rb, attribs) => withSDFAttribs((p) => distArc2(p, apert, ra, rb), attribs);
26
+ export const box2 = (center, size, attribs) => withSDFAttribs((p) => distBox2(sub2([], p, center), size), attribs);
27
+ export const circle2 = (center, radius, attribs) => withSDFAttribs((p) => distCircle2(sub2([], p, center), radius), attribs);
28
+ export const ellipse2 = (center, radii, attribs) => withSDFAttribs((p) => distEllipse2(sub2([], p, center), radii), attribs);
29
+ export const line2 = (a, b, attribs) => withSDFAttribs((p) => distSegment2(a, b, p), attribs);
30
+ export const points2 = (pts, attribs) => withSDFAttribs((p) => pts.reduce((acc, q) => Math.min(acc, distSq2(p, q)), Infinity), attribs);
31
+ export const polygon2 = (pts, attribs) => withSDFAttribs((p) => distPolygon2(pts, p), attribs);
32
+ export const polyline2 = (pts, attribs) => withSDFAttribs((p) => distPolyline2(pts, p), attribs);
33
+ export const quadratic2 = (a, b, c, attribs) => withSDFAttribs((p) => distQuadratic2(p, a, b, c), attribs);