@team-geospan/struct3d 1.0.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.
@@ -0,0 +1,50 @@
1
+ name: Deploy to GitHub Pages
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+ pages: write
12
+ id-token: write
13
+
14
+ jobs:
15
+ build:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - name: Checkout Website
19
+ uses: actions/checkout@v4
20
+
21
+ - name: Setup Node
22
+ uses: actions/setup-node@v4
23
+ with:
24
+ node-version: '20'
25
+
26
+ - name: Install Dependencies
27
+ run: npm ci
28
+
29
+ - name: Setup Pages
30
+ id: pages
31
+ uses: actions/configure-pages@v5
32
+
33
+ - name: Build Docs
34
+ run: npm run build
35
+
36
+ - name: Upload Artifact
37
+ uses: actions/upload-pages-artifact@v3
38
+ with:
39
+ path: ./docs/dist
40
+
41
+ deploy:
42
+ environment:
43
+ name: github-pages
44
+ url: ${{ steps.deployment.outputs.page_url }}
45
+ runs-on: ubuntu-latest
46
+ needs: build
47
+ steps:
48
+ - name: Deploy to GitHub Pages
49
+ id: deployment
50
+ uses: actions/deploy-pages@v4
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,17 @@
1
+ # Struct3D
2
+
3
+ The 3D Viewer component for StructuresJSON collections.
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ npm install @team-geospan/struct3d
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ The docs contain a [great example](./docs/src/pages/demo.jsx).
14
+
15
+ ## License
16
+
17
+ Apache 2.0. Availabe in [LICENSE](./LICENSE).
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'astro/config';
2
+ import react from '@astrojs/react';
3
+ // https://astro.build/config
4
+ export default defineConfig({
5
+ site: 'https://team-geospan.github.io',
6
+ base: '/struct3d/',
7
+ integrations: [react()]
8
+ });
@@ -0,0 +1,205 @@
1
+ import React, { useRef, useState, useEffect } from "react";
2
+ import PropTypes from "prop-types";
3
+ import StructureThreeD from "../../../lib/index.js";
4
+
5
+ // This is a nice default with two structures
6
+ const DEMO_URL =
7
+ "https://raw.githubusercontent.com/team-geospan/structures-json/refs/heads/main/versions/examples/V1.0-draft/two-structure-collection.json";
8
+
9
+ // Demo changing the edge colors using different palettes
10
+ const PALETTES = {
11
+ hicontrast: {
12
+ eave: "#000000", // Black
13
+ hip: "#FFFFFF", // White
14
+ valley: "#FFD700", // Bright Yellow
15
+ flash: "#FF0000", // Bright Red
16
+ ridge: "#00FFFF", // Cyan
17
+ rake: "#FF00FF", // Magenta
18
+ stepflash: "#00FF00", // Neon Green
19
+ parapet: "#0000FF", // Pure Blue
20
+ fance: "#FFA500", // Orange
21
+ chimney: "#808080", // Gray for balance
22
+ },
23
+ hotdog: {
24
+ eave: "#FF0000", // Bright Red
25
+ hip: "#FFFF00", // Bright Yellow
26
+ valley: "#00FFFF", // Cyan
27
+ flash: "#FF00FF", // Magenta
28
+ ridge: "#0000FF", // Blue
29
+ rake: "#FFA500", // Orange
30
+ stepflash: "#00FF00", // Bright Green
31
+ parapet: "#FF4500", // Red-Orange
32
+ fance: "#FFD700", // Gold
33
+ chimney: "#800000", // Dark Red
34
+ },
35
+ };
36
+
37
+ // Somewhat bad practice to put all the components into one file but this
38
+ // puts everything into a singular grokable view.
39
+ function SelectedInfo({ structureCollection, selectedId }) {
40
+ const [structureIndex, elementId] = selectedId.split("-");
41
+ const structure = structureCollection.structures[parseInt(structureIndex)];
42
+
43
+ let unitLabel = "sq. m.";
44
+ let value = 0.0;
45
+ if (structure.edges[elementId]) {
46
+ // use as edge
47
+ unitLabel = "m.";
48
+ value = structure.edges[elementId].properties.length;
49
+ } else {
50
+ // assume a surface
51
+ value = structure.surfaces[elementId].properties.area;
52
+ }
53
+
54
+ return (
55
+ <div>
56
+ {elementId}: {value} {unitLabel}
57
+ </div>
58
+ );
59
+ }
60
+
61
+ SelectedInfo.propTypes = {
62
+ structureCollection: PropTypes.object,
63
+ selectedId: PropTypes.string,
64
+ };
65
+
66
+ function Demo() {
67
+ const [isLoading, setLoading] = useState(true);
68
+ const [structureCollection, setStructureCollection] = useState(null);
69
+ const [selectedIds, setSelectedIds] = useState([]);
70
+ const [url, setUrl] = useState(DEMO_URL);
71
+ const [palette, setPalette] = useState("");
72
+ const inputRef = useRef();
73
+
74
+ useEffect(() => {
75
+ fetch(url)
76
+ .then((r) => r.json())
77
+ .then((stc) => {
78
+ if (stc.kind === "structurecollection") {
79
+ setStructureCollection(stc);
80
+ } else if (stc.kind === "structure") {
81
+ setStructureCollection({
82
+ kind: "structurecollection",
83
+ structures: [stc],
84
+ });
85
+ }
86
+ setLoading(false);
87
+ });
88
+ }, [url]);
89
+
90
+ return (
91
+ <div
92
+ style={{
93
+ display: "flex",
94
+ flexDirection: "column",
95
+ flex: 1,
96
+ position: "absolute",
97
+ top: 0,
98
+ left: 0,
99
+ width: "100%",
100
+ height: "100%",
101
+ }}
102
+ >
103
+ <div
104
+ style={{
105
+ padding: "6px",
106
+ display: "flex",
107
+ flexDirection: "column",
108
+ gap: 6,
109
+ }}
110
+ >
111
+ <div
112
+ style={{
113
+ display: "flex",
114
+ gap: 1,
115
+ }}
116
+ >
117
+ <input ref={inputRef} defaultValue={url} style={{ flex: 1 }} />
118
+ <button
119
+ onClick={() => {
120
+ setUrl(inputRef.current.value);
121
+ }}
122
+ >
123
+ Load
124
+ </button>
125
+ </div>
126
+ <div>
127
+ <label>Color palette:</label>
128
+ <select
129
+ value={palette}
130
+ onChange={(evt) => {
131
+ setPalette(evt.target.value);
132
+ }}
133
+ >
134
+ <option value="">Default</option>
135
+ <option value="hicontrast">High Contrast</option>
136
+ <option value="hotdog">Hot Dog Stand</option>
137
+ </select>
138
+ </div>
139
+ </div>
140
+ <div
141
+ style={{
142
+ position: "relative",
143
+ flex: 1,
144
+ }}
145
+ >
146
+ {selectedIds && selectedIds.length > 0 && (
147
+ <div
148
+ style={{
149
+ position: "absolute",
150
+ zIndex: 10,
151
+ left: 12,
152
+ top: 12,
153
+ padding: 12,
154
+ borderRadius: 6,
155
+ border: "solid 2px #d4af38",
156
+ backgroundColor: "#333",
157
+ color: "white",
158
+ }}
159
+ >
160
+ {selectedIds.map((selectedId) => (
161
+ <SelectedInfo
162
+ key={selectedId}
163
+ selectedId={selectedId}
164
+ structureCollection={structureCollection}
165
+ />
166
+ ))}
167
+ </div>
168
+ )}
169
+ {isLoading && (
170
+ <div
171
+ style={{
172
+ display: "flex",
173
+ position: "absolute",
174
+ left: 0,
175
+ top: 0,
176
+ width: "100%",
177
+ height: "100%",
178
+ alignItems: "center",
179
+ justifyContent: "center",
180
+ }}
181
+ >
182
+ Loading...
183
+ </div>
184
+ )}
185
+ {!isLoading && structureCollection && (
186
+ <StructureThreeD
187
+ key={url + palette}
188
+ structureCollection={structureCollection}
189
+ onClick={(ids) => {
190
+ setSelectedIds(ids);
191
+ }}
192
+ selectedIds={selectedIds}
193
+ edgeColors={PALETTES[palette]}
194
+ />
195
+ )}
196
+ </div>
197
+ </div>
198
+ );
199
+ }
200
+
201
+ Demo.propTypes = {
202
+ url: PropTypes.string,
203
+ };
204
+
205
+ export default Demo;
@@ -0,0 +1,60 @@
1
+ ---
2
+ import Demo from "./demo.jsx";
3
+ ---
4
+
5
+ <html>
6
+ <head>
7
+ <title>Struct3D: Renderer for StructuresJSON</title>
8
+ <style>
9
+ body {
10
+ font-family: sans-serif;
11
+ display: flex;
12
+ flex-direction: column;
13
+ }
14
+
15
+ html, body {
16
+ height: 100%;
17
+ padding: 0;
18
+ margin: 0;
19
+ }
20
+
21
+ header {
22
+ margin: 24px;
23
+ margin-bottom: 0px;
24
+ }
25
+
26
+ footer {
27
+ margin: 24px;
28
+ margin-top: 0px;
29
+ }
30
+
31
+ h1 {
32
+ margin: 0;
33
+ padding: 0;
34
+ }
35
+
36
+ #viewer {
37
+ flex: 1;
38
+ position: relative;
39
+ margin: 24px;
40
+ border: solid 1px black;
41
+ border-radius: 12px;
42
+ overflow: hidden;
43
+ }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <header>
48
+ <h1>Struct3D</h1>
49
+ <p>
50
+ 3D Renderer for <a href="https://github.com/team-geospan/structures-json">StructuresJSON</a> files.
51
+ </p>
52
+ </header>
53
+ <div id="viewer">
54
+ <Demo client:only="react" />
55
+ </div>
56
+ <footer>
57
+ &copy; 2025 GEOSPAN Corp. Apache-2 License
58
+ </footer>
59
+ </body>
60
+ </html>
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "astro/tsconfigs/base",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "jsxImportSource": "react"
6
+ }
7
+ }
@@ -0,0 +1,22 @@
1
+ export const DEFAULT_FACET_COLORS = {
2
+ asphalt: "#ecc696",
3
+ wood: "#ffdbb7",
4
+ tile: "#a4e6ff",
5
+ metal: "#ceffe3",
6
+ slate: "#95be8f",
7
+ membrane: "#c39fcc",
8
+ solar: "#c6a2ab",
9
+ };
10
+
11
+ export const DEFAULT_EDGE_COLORS = {
12
+ eave: "#9f476d",
13
+ hip: "#83b936",
14
+ valley: "#7663cf",
15
+ flash: "#bbb047",
16
+ ridge: "#5b8acc",
17
+ rake: "#d05330",
18
+ stepflash: "#40bbc1",
19
+ parapet: "#62be89",
20
+ fance: "#a97bc2",
21
+ chimney: "#6f903e",
22
+ };
package/lib/draw.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Copyright GEOSPAN Corp
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import earcut, { flatten } from "earcut";
18
+ import * as THREE from "three";
19
+ import { Line2 } from "three/addons/lines/Line2.js";
20
+ import { LineGeometry } from "three/addons/lines/LineGeometry.js";
21
+ import { LineMaterial } from "three/addons/lines/LineMaterial.js";
22
+
23
+ function calcCollectionBounds(collection) {
24
+ let [minx, miny, minz, maxx, maxy, maxz] = [
25
+ null,
26
+ null,
27
+ null,
28
+ null,
29
+ null,
30
+ null,
31
+ ];
32
+
33
+ collection.structures.forEach((st) => {
34
+ Object.values(st.points).map((pt) => {
35
+ const [x, y, z] = pt.coordinates;
36
+ if (minx === null || x < minx) {
37
+ minx = x;
38
+ }
39
+ if (maxx === null || x > maxx) {
40
+ maxx = x;
41
+ }
42
+ if (miny === null || y < miny) {
43
+ miny = y;
44
+ }
45
+ if (maxy === null || y > maxy) {
46
+ maxy = y;
47
+ }
48
+ if (minz === null || z < minz) {
49
+ minz = z;
50
+ }
51
+ if (maxz === null || z > maxz) {
52
+ maxz = z;
53
+ }
54
+ });
55
+ });
56
+
57
+ // make this compatible with 2d representation
58
+ return [minx, miny, maxx, maxy, minz, maxz];
59
+ }
60
+
61
+ function getAnchor(collection) {
62
+ const bounds = calcCollectionBounds(collection);
63
+ const x0 = bounds[0] + (bounds[2] - bounds[0]) / 2;
64
+ const y0 = bounds[1] + (bounds[3] - bounds[1]) / 2;
65
+ return [x0, y0, bounds[4]];
66
+ }
67
+
68
+ export function createLines(
69
+ collection,
70
+ baseElevation,
71
+ edgeColors,
72
+ width,
73
+ height,
74
+ ) {
75
+ const [x0, y0, minz] = getAnchor(collection);
76
+ const lines = collection.structures.flatMap((structure, stIdx) => {
77
+ const { edges, points } = structure;
78
+ return Object.keys(edges).map((edgeId) => {
79
+ const edge = edges[edgeId];
80
+ // offset and swap coordinates
81
+ const linePoints = edge.points.map((pointId) => {
82
+ const pt = points[pointId].coordinates;
83
+ return [pt[0] - x0, pt[2] - minz + baseElevation, y0 - pt[1]];
84
+ });
85
+
86
+ const geometry = new LineGeometry();
87
+ geometry.setPositions(linePoints.flatMap((p) => p));
88
+
89
+ const material = new LineMaterial({
90
+ color: edgeColors[edge.kind] || "#000000",
91
+ linewidth: edge.kind ? 3 : 1,
92
+ });
93
+ material.resolution.set(width, height);
94
+
95
+ const line = new Line2(geometry, material);
96
+ line.userData = {
97
+ ...edge.properties,
98
+ kind: edge.kind,
99
+ id: `${stIdx}-${edgeId}`,
100
+ layer: "edges",
101
+ };
102
+ return line;
103
+ });
104
+ });
105
+
106
+ return lines;
107
+ }
108
+
109
+ /**
110
+ * Convert the edge into a list of point IDs,
111
+ * edges are not directional! The ends need to be checked for
112
+ * continuity
113
+ */
114
+ function simplifyRing(edges) {
115
+ if (!edges || edges.length === 0) {
116
+ return [];
117
+ }
118
+
119
+ const sortedList = [edges.shift()];
120
+
121
+ while (edges.length > 0) {
122
+ for (let i = 0; i < edges.length; i++) {
123
+ const edge = edges[i];
124
+ if (sortedList[sortedList.length - 1][1] === edge[0]) {
125
+ sortedList.push(edges.splice(i, 1)[0]);
126
+ break;
127
+ } else if (sortedList[sortedList.length - 1][1] === edge[1]) {
128
+ sortedList.push(edges.splice(i, 1)[0].reverse());
129
+ break;
130
+ }
131
+ }
132
+ }
133
+
134
+ const asPoints = sortedList.map((e) => e[0]);
135
+ asPoints.push(sortedList[0][0]);
136
+ return asPoints;
137
+ }
138
+
139
+ export function createFacets(structureCollection, baseElevation, facetColors) {
140
+ const [x0, y0, minz] = getAnchor(structureCollection);
141
+
142
+ const meshes = structureCollection.structures.flatMap((structure, stIdx) => {
143
+ const { edges, points } = structure;
144
+
145
+ return Object.keys(structure.surfaces).map((surfaceId) => {
146
+ const surface = structure.surfaces[surfaceId];
147
+
148
+ const coords = surface.edges.map((ring) => {
149
+ return simplifyRing(
150
+ structuredClone(ring.map((edgeId) => edges[edgeId].points)),
151
+ )
152
+ .map((ptId) => points[ptId].coordinates)
153
+ .map((pt) => [pt[0] - x0, y0 - pt[1], pt[2] - minz + baseElevation]);
154
+ });
155
+
156
+ // make all the triangles, thank you earcut!
157
+ const data = flatten(coords);
158
+ const triangles = earcut(data.vertices, data.holes, data.dimensions);
159
+
160
+ // swap the y and z coordinates
161
+ for (let i = 0, len = data.vertices.length; i < len; i += 3) {
162
+ const y = data.vertices[i + 1];
163
+ const z = data.vertices[i + 2];
164
+ data.vertices[i + 1] = z;
165
+ data.vertices[i + 2] = y;
166
+ }
167
+
168
+ const bufferGeometry = new THREE.BufferGeometry();
169
+ bufferGeometry.setIndex(triangles);
170
+ bufferGeometry.setAttribute(
171
+ "position",
172
+ new THREE.BufferAttribute(new Float32Array(data.vertices), 3),
173
+ );
174
+ // Normally, the normals would be used to calculate the normal
175
+ // for each vertex and apply the material, *however* we use flatShading
176
+ // so do not want to compute the normals
177
+ // bufferGeometry.computeVertexNormals();
178
+
179
+ const material = new THREE.MeshPhongMaterial({
180
+ side: THREE.DoubleSide,
181
+ color: facetColors[surface.properties.material || "asphalt"],
182
+ flatShading: true,
183
+ shininess: 30,
184
+ });
185
+
186
+ const polygon = new THREE.Mesh(bufferGeometry, material);
187
+ polygon.userData = {
188
+ ...surface.properties,
189
+ id: `${stIdx}-${surfaceId}`,
190
+ layer: "facets",
191
+ };
192
+ return polygon;
193
+ });
194
+ });
195
+ return meshes;
196
+ }
197
+
198
+ export function createReferences(scene) {
199
+ const floorGeom = new THREE.PlaneGeometry(1000, 1000);
200
+ const floorMaterial = new THREE.MeshPhongMaterial({
201
+ color: 0x315d0a,
202
+ side: THREE.DoubleSide,
203
+ });
204
+ const floorMesh = new THREE.Mesh(floorGeom, floorMaterial);
205
+ floorMesh.rotation.x = -Math.PI / 2;
206
+ floorMesh.receiveShadow = true;
207
+ scene.add(floorMesh);
208
+
209
+ // TODO: Size is set to "1" which is one meter in this projection,
210
+ // we should do something for US measurements
211
+ const gridHelper = new THREE.GridHelper(100, 100, 0x888888, 0x888888);
212
+ gridHelper.receiveShadow = true;
213
+ gridHelper.position.set(0, 0.1, 0);
214
+ scene.add(gridHelper);
215
+ }
216
+
217
+ export function addLights(scene, center, bounds) {
218
+ const intensity = 5000;
219
+ const ambient = new THREE.AmbientLight(0xffffff);
220
+ ambient.intensity = 1.5;
221
+ scene.add(ambient);
222
+
223
+ const spotLight = new THREE.SpotLight(0xffffff, intensity);
224
+ spotLight.position.set(bounds.x / 2, bounds.y + 50, bounds.z / 2);
225
+ spotLight.castShadow = true;
226
+ spotLight.angle = 5.0;
227
+ spotLight.lookAt(center);
228
+
229
+ scene.add(spotLight);
230
+ }
231
+
232
+ export function clearScene(scene) {
233
+ scene.clear();
234
+ }
package/lib/index.js ADDED
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Copyright GEOSPAN Corp
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { createElement, useCallback, useEffect, useMemo, useRef } from "react";
18
+ import { useResizeDetector } from "react-resize-detector";
19
+ import { DEFAULT_EDGE_COLORS, DEFAULT_FACET_COLORS } from "./defaults";
20
+ import { toMercator } from "@turf/projection";
21
+ import PropTypes from "prop-types";
22
+ import * as THREE from "three";
23
+ import { OrbitControls } from "three/addons/controls/OrbitControls";
24
+
25
+ import {
26
+ addLights,
27
+ clearScene,
28
+ createFacets,
29
+ createLines,
30
+ createReferences,
31
+ } from "./draw";
32
+
33
+ const THREED_SKY_COLOR = "#CDEBF7";
34
+
35
+ const setupScene = (
36
+ divRef,
37
+ sceneRef,
38
+ cameraRef,
39
+ rendererRef,
40
+ orbitRef,
41
+ fieldOfView,
42
+ ) => {
43
+ const [width, height] = [
44
+ divRef.current.offsetWidth,
45
+ divRef.current.offsetHeight,
46
+ ];
47
+
48
+ // create the scene
49
+ const scene = new THREE.Scene();
50
+ sceneRef.current = scene;
51
+
52
+ scene.background = new THREE.Color(THREED_SKY_COLOR);
53
+ scene.fog = new THREE.Fog(scene.background, 1, 5000);
54
+
55
+ const camera = new THREE.PerspectiveCamera(
56
+ fieldOfView,
57
+ width / height,
58
+ 0.1,
59
+ 1000.0,
60
+ );
61
+ cameraRef.current = camera;
62
+ const renderer = new THREE.WebGLRenderer({
63
+ preserveDrawingBuffer: true,
64
+ antialias: true,
65
+ });
66
+
67
+ const orbitControl = new OrbitControls(camera, renderer.domElement);
68
+ orbitControl.minPolarAngle = 0;
69
+ orbitControl.maxPolarAngle = Math.PI * 0.5;
70
+ orbitRef.current = orbitControl;
71
+
72
+ renderer.setSize(width, height);
73
+ renderer.shadowMap.enabled = true;
74
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
75
+ rendererRef.current = renderer;
76
+ renderer.setAnimationLoop(() => {
77
+ renderer.render(scene, camera);
78
+ });
79
+ divRef.current.appendChild(renderer.domElement);
80
+ };
81
+
82
+ const renderModel = (
83
+ divRef,
84
+ collection,
85
+ baseElevation,
86
+ facetColors,
87
+ edgeColors,
88
+ sceneRef,
89
+ cameraRef,
90
+ orbitRef,
91
+ fieldOfView,
92
+ ) => {
93
+ // calculate the spatial extents of the meshes
94
+ const boundingBox = new THREE.Box3();
95
+ const [width, height] = [
96
+ divRef.current.offsetWidth,
97
+ divRef.current.offsetHeight,
98
+ ];
99
+ const scene = sceneRef.current;
100
+ const camera = cameraRef.current;
101
+ const orbitControl = orbitRef.current;
102
+
103
+ // convert the polygons to meshes
104
+ const meshes = createFacets(collection, baseElevation, facetColors);
105
+
106
+ meshes.forEach((mesh) => {
107
+ mesh.receiveShadow = true;
108
+ mesh.castShadow = true;
109
+ scene.add(mesh);
110
+ boundingBox.expandByObject(mesh);
111
+ });
112
+
113
+ const lines = createLines(
114
+ collection,
115
+ baseElevation + 0.01,
116
+ edgeColors,
117
+ width,
118
+ height,
119
+ );
120
+ lines.forEach((line) => {
121
+ scene.add(line);
122
+ });
123
+
124
+ const center = new THREE.Vector3();
125
+ boundingBox.getCenter(center);
126
+
127
+ const bounds = new THREE.Vector3();
128
+ boundingBox.getSize(bounds);
129
+
130
+ createReferences(scene, center, bounds);
131
+
132
+ addLights(scene, center, bounds);
133
+
134
+ orbitControl.target = center;
135
+
136
+ // calculate the distance to zoom out in order to fit the entire model
137
+ const h = bounds.x / 2 / Math.tan(((fieldOfView / 2.0) * Math.PI) / 180);
138
+ const d = bounds.z / 2 / Math.tan(((fieldOfView / 2.0) * Math.PI) / 180);
139
+
140
+ camera.position.x = center.x / 1.25;
141
+ camera.position.y = Math.max(h, d) + bounds.y;
142
+ camera.position.z = bounds.z / 1.25;
143
+ camera.lookAt(center);
144
+ };
145
+
146
+ export default function StructureThreeD({
147
+ structureCollection,
148
+ selectedIds,
149
+ onClick,
150
+ selectionColor = "#d4af38",
151
+ facetColors = DEFAULT_FACET_COLORS,
152
+ edgeColors = DEFAULT_EDGE_COLORS,
153
+ }) {
154
+ const baseElevation = 10;
155
+ const fieldOfView = 70;
156
+ const divRef = useRef(null);
157
+ const sceneRef = useRef(null);
158
+ const cameraRef = useRef(null);
159
+ const orbitRef = useRef(null);
160
+ const rendererRef = useRef(null);
161
+
162
+ const collection = useMemo(() => {
163
+ // check the projection of the structures and put them into webmerc
164
+ const cleanCollection = structuredClone(structureCollection);
165
+ cleanCollection.structures.forEach((structure) => {
166
+ if (structure.projection === "crs84") {
167
+ // convert the points to mercator
168
+ Object.keys(structure.points).forEach((pointId) => {
169
+ // this looks messier than it is, get the coordinates from the point,
170
+ // shim toMercator to use a GeoJSON style point, then pull the coordinates
171
+ // out in order to reproject the stucture.
172
+ const coordinates = structure.points[pointId].coordinates;
173
+ structure.points[pointId].coordinates = toMercator({
174
+ type: "Point",
175
+ coordinates,
176
+ }).coordinates;
177
+ });
178
+ structure.projection = "webmerc";
179
+ } else if (structure.projection === "webmerc") {
180
+ return structure;
181
+ } else {
182
+ // yikes this is unsupported right now!
183
+ console.error(
184
+ `Structure with projection "${structure.projection}" is not currently supported.`,
185
+ );
186
+ }
187
+ });
188
+
189
+ return cleanCollection;
190
+ }, [structureCollection]);
191
+
192
+ // handle resizing of the div!
193
+ const { width, height, ref } = useResizeDetector();
194
+
195
+ useEffect(() => {
196
+ if (divRef.current) {
197
+ if (sceneRef.current === null) {
198
+ setupScene(
199
+ divRef,
200
+ sceneRef,
201
+ cameraRef,
202
+ rendererRef,
203
+ orbitRef,
204
+ fieldOfView,
205
+ );
206
+ }
207
+
208
+ clearScene(sceneRef.current);
209
+ renderModel(
210
+ divRef,
211
+ collection,
212
+ baseElevation,
213
+ facetColors,
214
+ edgeColors,
215
+ sceneRef,
216
+ cameraRef,
217
+ orbitRef,
218
+ fieldOfView,
219
+ );
220
+ }
221
+ }, [collection, selectionColor]);
222
+
223
+ const handleClick = useCallback(
224
+ (evt) => {
225
+ const [x, y] = [evt.nativeEvent.offsetX, evt.nativeEvent.offsetY];
226
+ const [width, height] = [
227
+ divRef.current.offsetWidth,
228
+ divRef.current.offsetHeight,
229
+ ];
230
+ const raycaster = new THREE.Raycaster();
231
+ const mouse = new THREE.Vector2();
232
+ mouse.set((x / width) * 2 - 1, -(y / height) * 2 + 1);
233
+ raycaster.setFromCamera(mouse, cameraRef.current);
234
+ const intersects = raycaster.intersectObjects(
235
+ sceneRef.current.children,
236
+ true,
237
+ );
238
+ const ids = intersects
239
+ .map((f) => f.object.userData)
240
+ .map((f) => f.id)
241
+ // ensure the object has an ID
242
+ .filter((id) => !!id);
243
+ if (onClick) {
244
+ onClick(ids);
245
+ }
246
+ },
247
+ [onClick],
248
+ );
249
+
250
+ useEffect(() => {
251
+ if (sceneRef.current) {
252
+ sceneRef.current.traverse((object) => {
253
+ // ensure the object has a material set and the userData has our layer specified
254
+ if (object.material && Boolean(object.userData?.layer)) {
255
+ let color =
256
+ object.userData.layer === "facets"
257
+ ? facetColors[object.userData?.material || "asphalt"]
258
+ : edgeColors[object.userData.kind] || "#00000000";
259
+ if (selectedIds.includes(object.userData?.id)) {
260
+ color = selectionColor;
261
+ }
262
+ object.material.color.set(color);
263
+ }
264
+ });
265
+ }
266
+ }, [selectedIds, selectionColor]);
267
+
268
+ useEffect(() => {
269
+ if (rendererRef.current && cameraRef.current && !!width && !!height) {
270
+ cameraRef.current.aspect = width / height;
271
+ cameraRef.current.updateProjectionMatrix();
272
+ rendererRef.current.setSize(width, height);
273
+ }
274
+ }, [width, height]);
275
+
276
+ return createElement(
277
+ "div",
278
+ {
279
+ ref,
280
+ style: {
281
+ position: "absolute",
282
+ top: 0,
283
+ left: 0,
284
+ width: "100%",
285
+ height: "100%",
286
+ backgroundColor: "#eee",
287
+ },
288
+ },
289
+ [
290
+ createElement("div", {
291
+ ref: divRef,
292
+ onClick: handleClick,
293
+ className: "struct-3d",
294
+ style: {
295
+ position: "absolute",
296
+ top: 0,
297
+ left: 0,
298
+ width: "100%",
299
+ height: "100%",
300
+ },
301
+ }),
302
+ ],
303
+ );
304
+ }
305
+
306
+ StructureThreeD.propTypes = {
307
+ structureCollection: PropTypes.object,
308
+ selectedIds: PropTypes.array,
309
+ onClick: PropTypes.func,
310
+ selectionColor: PropTypes.string,
311
+ facetColors: PropTypes.object,
312
+ edgeColors: PropTypes.object,
313
+ };
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@team-geospan/struct3d",
3
+ "version": "1.0.0",
4
+ "description": "The 3D Viewer component for StructuresJSON models.",
5
+ "license": "Apache-2.0",
6
+ "author": "GEOSPAN Corp and Contributors",
7
+ "type": "module",
8
+ "scripts": {
9
+ "build:copy-files": "node ./scripts/bundle.js",
10
+ "lint": "eslint --report-unused-disable-directives --max-warnings 0 ./lib ./docs --ext .js,.jsx",
11
+ "lint:fix": "npm run lint -- --fix",
12
+ "start": "astro dev --root ./docs",
13
+ "build": "astro build --root ./docs",
14
+ "test": "echo \"Error: no test specified\" && exit 1"
15
+ },
16
+ "eslintConfig": {
17
+ "env": {
18
+ "browser": true,
19
+ "es2021": true
20
+ },
21
+ "parserOptions": {
22
+ "ecmaVersion": "latest",
23
+ "sourceType": "module"
24
+ },
25
+ "settings": {
26
+ "react": {
27
+ "version": "detect"
28
+ }
29
+ },
30
+ "extends": [
31
+ "eslint:recommended",
32
+ "plugin:react/recommended",
33
+ "plugin:prettier/recommended"
34
+ ],
35
+ "rules": {
36
+ "prettier/prettier": "error"
37
+ }
38
+ },
39
+ "dependencies": {
40
+ "@turf/projection": "^6.5.0",
41
+ "earcut": "^3.0.1",
42
+ "react-resize-detector": "^12.0.2",
43
+ "three": "^0.167.1"
44
+ },
45
+ "devDependencies": {
46
+ "@astrojs/react": "^4.2.0",
47
+ "@swc/cli": "^0.3.12",
48
+ "@swc/core": "^1.5.25",
49
+ "@types/react": "^19.0.10",
50
+ "@types/react-dom": "^19.0.4",
51
+ "astro": "^5.3.0",
52
+ "eslint": "^8.57.0",
53
+ "eslint-config-prettier": "^10.0.1",
54
+ "eslint-plugin-prettier": "^5.2.3",
55
+ "eslint-plugin-react": "^7.37.4",
56
+ "prop-types": "^15.8.1"
57
+ },
58
+ "peerDependencies": {
59
+ "react": "^19.0.0",
60
+ "react-dom": "^19.0.0"
61
+ }
62
+ }