@aiquants/plant-scene 0.0.0-stage → 0.2.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,55 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (2026-11-28)
4
+
5
+ Site markers: the host stands markers on points of the site from its own data, and they are picked, selected and
6
+ focused like the models' objects.
7
+
8
+ ### Added
9
+
10
+ - **`markers`** on `PlantSceneCanvas` (`SiteMarker`: `id`, `label`, `position`, `color`): each marker is a pole from
11
+ the ground and a head above the roofs around its point, with a name tag beside the head that turns to the camera,
12
+ keeps its size on the screen and is drawn over the models; its text is black or white, whichever contrasts more with
13
+ the marker's colour. A new array draws the markers again without loading the models again, and the markers hide while
14
+ a detailed building is shown alone. Nothing is fetched for them.
15
+ - **`markerPosition(pointMm, originMm)`**: a marker's place from a point of the site drawing (mm) and the drawing's point
16
+ the site model's origin stands on, in the frame `detailPlacement` places detailed buildings in.
17
+ - **`checkedMarkers`**: refuses, with a `RangeError` while rendering, an empty or shared id, a blank label, a point that
18
+ is not finite and a colour that is not `#rrggbb`. A marker with the id of an object of the models is reported through
19
+ `onFailure`.
20
+ - **`MarkerObject`** (`kind: "marker"`, `id`, `label`) among the `SceneObject`s: `onPick` returns it, `display.selection`
21
+ selects it (`focus` turns the camera to it), and `sceneObjectLabel` and `objectSummary` label it.
22
+ - **The `markers` display option** (`印`), on by default and kept with the other options; `offeredOptions` offers it
23
+ when `hasMarkers` is true.
24
+ - **The test hook `data-marker-positions`**: every frame drawn writes, as JSON, where a tap picks each marker in sight
25
+ (CSS pixels from the canvas's top left corner).
26
+
27
+ ### Changed
28
+
29
+ - `PlantSceneCanvasProps.markers` and `OptionSubjects.hasMarkers` are required: pass `[]` and `false` for no markers,
30
+ which draw, pick and offer options as 0.1.0 did (the canvas only carries `data-marker-positions="[]"` too).
31
+ `DisplayOptions` has `markers`, and code that switches over `SceneObject.kind` needs a `"marker"` case.
32
+
33
+ ## 0.1.0 (2026-11-09)
34
+
35
+ The first release: a React 3D view of a plant site drawn with Babylon.js, and the rules a page around it lists the
36
+ scene's objects by.
37
+
38
+ ### Added
39
+
40
+ - **`PlantSceneCanvas`**: draws the site's boxes first, then the site drawing's lines and the detailed buildings' models
41
+ as they arrive; reports picks, loads and failures; shows a detailed building alone up to a floor; frames into the part
42
+ of the canvas the host's panels leave (`insets`). Babylon.js loads only when the canvas mounts, with a dynamic
43
+ `import()`. The canvas lays itself out with its own `style`.
44
+ - **Colours from the host** (`ScenePaint`, `checkedPaint`): the sky, the ground, the drawings' ink and the floors, each
45
+ `#rrggbb`; a changed colour repaints the open view. A colour that is not `#rrggbb`, and insets that leave no height in
46
+ sight, throw a `RangeError` while rendering.
47
+ - **Display options** (`useDisplayOptions`, `offeredOptions`, `DEFAULT_DISPLAY_OPTIONS`): kept in `localStorage` under a
48
+ key the host chooses, followed by every reader of the key in every tab.
49
+ - **Panels over the view** (`useViewInsets`): measures how much of the view the panels hide.
50
+ - **Rules for the page's list and cards** (`listedBuildings`, `objectSummary`, `detailOfObject`, `buildingRequestOf`,
51
+ `sceneObjectLabel`, `detailPlacement`): they take the host's own manifest entries (`SceneDetail`) and hand them back in
52
+ the host's type.
53
+ - **Search folding** (`foldForSearch`, `searchTerms`): NFKC, lower case, split by white space.
54
+
55
+ Peers: `@babylonjs/core` ^9.31.0, `@babylonjs/loaders` ^9.31.0, `react` >=19.2.0, `zod` ^3.25.0.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Quants
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,220 @@
1
- # Temporary Holding Version
1
+ # @aiquants/plant-scene
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A React 3D view of a plant site, drawn with Babylon.js, and the rules a page around it lists the scene's objects by.
4
+ Babylon.js で描く工場の構内の 3D の表示 (React) と、周りの画面が場面の物体を並べる規則。
5
+
6
+ ---
7
+
8
+ ## Overview / 概要
9
+
10
+ - **The view**: `PlantSceneCanvas` draws the site's buildings and tanks as boxes first, then lays the site drawing's lines and text and the detailed buildings' models over them as they arrive, and stands the host's markers on points of the site. A click picks a building, a tank, a piece of equipment or a marker; a detailed building can be shown alone, up to one of its floors.
11
+ - **表示**: `PlantSceneCanvas` はまず構内の建屋とタンクを箱で描き、届き次第、構内の図面の線と字と詳しい建屋の模型を重ね、使い手の印を構内の点に立てる。押すと建屋・タンク・機器・印を選べ、詳しい建屋は 1 つだけ、ある階までを見せられる。
12
+ - **Babylon.js loads late**: the canvas loads the scene module with a dynamic `import()` when it mounts, so the page's entry chunk and the server render never carry Babylon.js.
13
+ - **Babylon.js は後から読む**: キャンバスは置かれたときに場面のモジュールを動的な `import()` で読むので、画面の入口の塊にもサーバの描画にも Babylon.js は載らない。
14
+ - **The rules around it**: the list of buildings with their floors and equipment, the summary of a selected object, the drawings an object asks for, the display options a manifest offers, and the search folding.
15
+ - **周りの規則**: 建屋とその階・機器の一覧、選んだ物体の要約、物体が求める図面、目録が出す表示オプション、検索の語のそろえ方。
16
+ - **What the host keeps**: the route that serves the models, the manifest of detailed buildings, the points and labels of its markers, the colours of its theme, the key the display options are kept under, and the page's own panels.
17
+ - **使い手が持つもの**: 模型を配る口、詳しい建屋の目録、印の点と名札、テーマの色、表示オプションを残す鍵、画面の欄。
18
+
19
+ The labels the package returns and shows (the display options, the legend, the object summaries and the canvas's accessible name) are Japanese.
20
+ パッケージが返し見せる名 (表示オプション・凡例・物体の要約・キャンバスの名) は日本語。
21
+
22
+ ---
23
+
24
+ ## Installation / インストール
25
+
26
+ ```bash
27
+ pnpm add @aiquants/plant-scene @babylonjs/core @babylonjs/loaders zod
28
+ ```
29
+
30
+ Peer dependencies:
31
+
32
+ ```json
33
+ {
34
+ "peerDependencies": {
35
+ "@babylonjs/core": "^9.31.0",
36
+ "@babylonjs/loaders": "^9.31.0",
37
+ "react": ">=19.2.0",
38
+ "zod": "^3.25.0"
39
+ }
40
+ }
41
+ ```
42
+
43
+ The package is ES modules only (`import`), as Babylon.js 9 is. React 19.2 is the first version with `useEffectEvent`, which the canvas uses.
44
+ パッケージは ES モジュールだけ (`import`。Babylon.js 9 と同じ)。キャンバスが使う `useEffectEvent` は React 19.2 から。
45
+
46
+ ---
47
+
48
+ ## Usage / 使い方
49
+
50
+ ```tsx
51
+ import { detailPlacement, type DetailModel, markerPosition, PlantSceneCanvas, type ScenePaint, type SceneSelection, type SiteMarker, useDisplayOptions, useViewInsets } from "@aiquants/plant-scene"
52
+ import { useMemo, useState } from "react"
53
+
54
+ const PAINT: ScenePaint = { sky: "#f1f5f9", ground: "#e2e8f0", ink: "#0f172a", floor: "#ffffff" }
55
+
56
+ export const PlantView = ({ manifest, points }: { manifest: YourManifest; points: readonly YourPoint[] }) => {
57
+ const [options] = useDisplayOptions("<your-app>:plant-scene:display-options")
58
+ const [view, setView] = useState<HTMLDivElement | null>(null)
59
+ const [card, setCard] = useState<HTMLDivElement | null>(null)
60
+ const panels = useMemo(() => [card], [card])
61
+ const insets = useViewInsets(view, panels)
62
+ const [selection, setSelection] = useState<SceneSelection | null>(null)
63
+ const details = useMemo<DetailModel[]>(
64
+ () => manifest.details.map((detail) => ({ key: detail.key, glbUrl: `/your-asset-route/${detail.glb}`, buildingId: detail.buildingId, placement: detailPlacement(detail, manifest.originMm), floors: detail.floors })),
65
+ [manifest],
66
+ )
67
+ const markers = useMemo<SiteMarker[]>(
68
+ () => points.map((point) => ({ id: `point-${point.id}`, label: point.name, position: markerPosition(point.positionMm, manifest.originMm), color: "#1d4ed8" })),
69
+ [points, manifest],
70
+ )
71
+
72
+ return (
73
+ <div ref={setView} style={{ position: "relative", height: "100dvh", background: PAINT.sky }}>
74
+ <PlantSceneCanvas
75
+ massingUrl="/your-asset-route/site.massing.glb"
76
+ linesUrl="/your-asset-route/site.lines.glb"
77
+ details={details}
78
+ heights={manifest.heights}
79
+ markers={markers}
80
+ display={{ isolated: null, floor: null, selection }}
81
+ options={options}
82
+ insets={insets}
83
+ paint={PAINT}
84
+ onPick={(object) => setSelection(object === null ? null : { id: object.id, focus: false })}
85
+ onLoad={({ objects, legend, complete }) => { /* list the objects, show the legend */ }}
86
+ onFailure={(error) => { /* show the error */ }}
87
+ />
88
+ <div ref={setCard} style={{ position: "absolute", top: 0, left: 0, right: 0 }}>{/* a panel over the view */}</div>
89
+ </div>
90
+ )
91
+ }
92
+ ```
93
+
94
+ The canvas fills its nearest positioned ancestor, which gives it its size; it lays itself out with its own `style` and needs no stylesheet. Pass stable arrays (`details`, `heights`): the view lives as long as the two URLs and these arrays, compared by identity, and a new one closes the view and loads the models again. A new `markers` array draws the markers again and keeps the models, so the markers may come after the host's data has loaded; pass a memoized one all the same, as each new array makes the markers' meshes again.
95
+ キャンバスはいちばん近い位置指定の祖先いっぱいに広がり、その祖先が大きさを与える。自分の `style` で自分を置くので、スタイルシートは要らない。`details`・`heights` は変わらない配列を渡すこと。表示は 2 つの URL とこれらの配列 (同一性で比べる) と同じだけ生き、新しいものなら表示を閉じて模型を読み直す。新しい `markers` の配列は印だけを描き直し、模型は読み直さないので、印は使い手のデータを読んだ後に渡してよい。それでも新しい配列のたびに印の網を作り直すので、変わらない配列を渡すこと。
96
+
97
+ ### `PlantSceneCanvas` props / 引数
98
+
99
+ | Prop | Type | What it is |
100
+ | --- | --- | --- |
101
+ | `massingUrl` | `string` | GLB of the site's buildings and tanks. 構内の建屋とタンクの GLB。 |
102
+ | `linesUrl` | `string` | GLB of the site drawing's lines and text. 構内の図面の線と字の GLB。 |
103
+ | `details` | `readonly DetailModel[]` | The detailed buildings' models: `key`, `glbUrl`, `buildingId` (the site building it replaces), `placement` (`detailPlacement`) and `floors`. 詳しい建屋の模型。 |
104
+ | `heights` | `readonly BuildingHeight[]` | Heights of the site buildings whose height is known (`buildingId`, `buildingName`, `heightMm`). 高さの分かる構内の建屋の高さ。 |
105
+ | `markers` | `readonly SiteMarker[]` | The markers on points of the site: `id` (no building's, tank's or piece of equipment's id), `label` (not blank), `position` (`markerPosition`) and `color` (`#rrggbb`); `[]` for none. 構内の点に立てる印。 |
106
+ | `display` | `SceneDisplay` | What the view shows: `isolated` (a detailed building's key shown alone, or `null`), `floor` (the floor it is shown up to, or `null`) and `selection` (`{ id, focus }` or `null`, `id` an object's or a marker's; `focus` turns the camera to it). 表示が見せるもの。 |
107
+ | `options` | `DisplayOptions` | How the view draws (`useDisplayOptions`). 描き方。 |
108
+ | `insets` | `ViewInsets` | The parts of the canvas's height the panels hide (`useViewInsets`): each side 0 or more, the two less than 1. 欄が隠す高さの部分。 |
109
+ | `paint` | `ScenePaint` | The colours of the sky, the ground, the drawings' ink and the floors, each `#rrggbb`. 空・地面・墨・床の色。 |
110
+ | `onPick` | `(object: SceneObject \| null) => void` | The object or marker (`kind: "marker"`) a click hit, or `null`. 押して当たった物体か印。 |
111
+ | `onLoad` | `(models: LoadedModels) => void` | The objects and the legend each time more models have loaded (`complete` once everything has). 読み進めるたびの物体と凡例。 |
112
+ | `onFailure` | `(error: Error) => void` | Babylon.js or a model could not be loaded, a model breaks the contract below, or a marker has the id of an object of the models. 読めなかったとき、模型が約束を破るとき、印が模型の物体の ID を持つとき。 |
113
+
114
+ A colour that is not `#rrggbb` (`checkedPaint`), insets that leave no height in sight (`checkedInsets`) or markers `checkedMarkers` refuses make the canvas throw a `RangeError` while rendering, before a view opens or is painted; an error boundary of the host catches it.
115
+ `#rrggbb` でない色、見える高さを残さない余白、`checkedMarkers` が退ける印は、描く中で `RangeError` になる (表示を開く前・塗る前)。使い手のエラーの境界が受ける。
116
+
117
+ ### The rest of the API / ほかの API
118
+
119
+ | Name | What it does |
120
+ | --- | --- |
121
+ | `useDisplayOptions(storageKey)` | The display options kept under the host's key in `localStorage`, and the function that keeps new ones. Every reader of the same key, in this tab and the others, follows a change; the server render gets `DEFAULT_DISPLAY_OPTIONS`. An empty key throws a `RangeError`. 使い手の鍵で残す表示オプションと、それを変える関数。 |
122
+ | `offeredOptions({ hasDetails, hasHeights, hasMarkers })` | The options worth offering for a manifest and the host's markers, with their labels, in the page's order (`印` only with markers). 目録と使い手の印に意味のあるオプション。 |
123
+ | `DEFAULT_DISPLAY_OPTIONS` | Every option on. 全てのオプションが入った状態。 |
124
+ | `useViewInsets(view, panels)` | How much of the view the panels laid over it hide, measured again whenever the view or a panel changes size. Pass a memoized `panels` array. 重ねた欄が隠す部分。 |
125
+ | `detailPlacement(detail, originMm)` | Where a detailed building's model goes on the site model, from its turn (`rotationDeg`) and shift (`offsetMm`) on the site drawing and the drawing's point the site model's origin stands on. 詳しい建屋の模型の置き方。 |
126
+ | `markerPosition(pointMm, originMm)` | Where a site marker stands on the site model, from its point on the site drawing (mm) and the drawing's point the site model's origin stands on, in the frame `detailPlacement` places in. A coordinate that is not finite throws a `RangeError`. 構内の印の立つ所。 |
127
+ | `listedBuildings(objects, details, filter, only)` | The page's list: the named buildings and the detailed ones, with their floors (highest first) and equipment, narrowed by words. 画面の一覧。 |
128
+ | `objectSummary(object, details, objects)` | A selected object's title, what it is, and its detailed building. 選んだ物体の要約。 |
129
+ | `detailOfObject(object, details)` | The detailed building a building or a piece of equipment belongs to, or `null`. 物体が属する詳しい建屋。 |
130
+ | `buildingRequestOf(object, details)` | The site building and the words an object asks the drawings for, or `null`. 物体が図面に求める建屋と語。 |
131
+ | `sceneObjectLabel(object)` | An object's label (a marker's is its `label`). 物体の名札 (印は名札の字)。 |
132
+ | `foldForSearch(text)` / `searchTerms(query)` | The search folding (NFKC, then lower case) and a query split into folded words at any white space. Fold the host's own matches the same way. 検索の語のそろえ方。 |
133
+ | `checkedPaint(paint)` | Returns the paint when every colour is `#rrggbb`, or throws a `RangeError` naming the first wrong one. 色を確かめる。 |
134
+ | `checkedMarkers(markers)` | Returns the markers when each has an id of its own that is not empty, a label that is not blank, a finite point and a `#rrggbb` colour, or throws a `RangeError` naming the first wrong one. 印を確かめる。 |
135
+
136
+ `detailOfObject`, `objectSummary` and `listedBuildings` take the host's own manifest entries (any type with the fields of `SceneDetail`: `key`, `buildingId`, `buildingName`, `rotationDeg`, `offsetMm`, `floors`) and hand them back in the host's type.
137
+ `detailOfObject`・`objectSummary`・`listedBuildings` は使い手の目録の項目 (`SceneDetail` の項目を持つ型) を受け、使い手の型のまま返す。
138
+
139
+ ---
140
+
141
+ ## Site markers / 構内の印
142
+
143
+ A marker stands on a point the host's data knows and the models do not: a switchboard room, a meter, a camera, a muster point.
144
+ 構内の点のうち、模型に無く使い手のデータにある所 (配電室・計器・カメラ・集合場所など) に立てる印。
145
+
146
+ - **Where**: `markerPosition(pointMm, originMm)` turns a point of the site drawing (mm) into the site model's frame, the one `detailPlacement` places detailed buildings in, so a manifest with a new `originMm` needs no change to the host's points.
147
+ - **置き場所**: `markerPosition(pointMm, originMm)` が構内の図面の点 (mm) を、`detailPlacement` が詳しい建屋を置くのと同じ構内の模型の座標系へ移す。目録の `originMm` が替わっても、使い手の点は直さずに済む。
148
+ - **How it draws**: a pole from the ground and a head in the marker's `color`, the head 4 m above the highest roof within 10 m of the point and at least 6 m above the ground, so a marker inside a building shows its head above the roof. The head, the pole and the name tag keep their sizes on the screen, and the head and the tag are drawn over the models, so no building hides them.
149
+ - **描き方**: 地面からの柱と頭を印の `color` で描き、頭は点から 10 m の内のいちばん高い屋根の 4 m 上、地面から少なくとも 6 m に立つ (建屋の中の点の印も、屋根の上に頭を見せる)。頭・柱・名札は画面の上の大きさを保ち、頭と名札は模型の上に描くので、どの建屋にも隠れない。
150
+ - **Name tag**: beside the head and turned to the camera, in the marker's colour, with the `label` in black or white, whichever contrasts more with it: at least 4.58 : 1 on any colour, in bold 19 px, which is large text, of which WCAG's AAA asks 4.5 : 1.
151
+ - **名札**: 頭の横で視点へ向き、印の色の地に `label` を黒と白のうちその色とのコントラストの高い方で書く。どの色の上でも少なくとも 4.58 : 1 で、太字の 19 px は WCAG の AAA が 4.5 : 1 を求める大きな字。
152
+ - **Picking and selection**: a tap on a head or a name tag picks the marker before the models, and `onPick` returns `{ kind: "marker", id, label }`. `display.selection` with a marker's `id` makes it glow, and `focus` turns the camera to it.
153
+ - **押しと選択**: 頭か名札を押すと、模型より先にその印が選ばれ、`onPick` は `{ kind: "marker", id, label }` を返す。`display.selection` に印の `id` を渡すと光り、`focus` が真なら視点がその印へ向く。
154
+ - **When it shows**: while the whole site is shown (never while `display.isolated` names a detailed building) and the `markers` display option (`印`) is on. `offeredOptions` offers that option only with `hasMarkers`, and `useDisplayOptions` keeps it with the others.
155
+ - **見せる間**: 構内の全体を見せる間 (`display.isolated` が詳しい建屋を名指す間は見せない) で、表示オプション `markers` (`印`) が入の間。`offeredOptions` はこのオプションを `hasMarkers` のときだけ出し、`useDisplayOptions` がほかのオプションと共に残す。
156
+ - **Ids**: the host chooses ids no building, tank or piece of equipment has. A marker with the id of an object of the models is reported through `onFailure`, when the markers come or when the model that holds the object loads.
157
+ - **ID**: 建屋・タンク・機器の ID と重ならない ID を使い手が決める。模型の物体と同じ ID の印は、印が来たとき、またはその物体を持つ模型を読んだときに `onFailure` で知らせる。
158
+ - **No markers**: with `markers={[]}` and `hasMarkers: false`, nothing of the markers is drawn or offered, a tap reaches the models alone, and `data-marker-positions` reads `[]`.
159
+ - **印が無いとき**: `markers={[]}` と `hasMarkers: false` なら、印は描かず表示オプションにも出さず、押しは模型だけに届き、`data-marker-positions` は `[]`。
160
+
161
+ ---
162
+
163
+ ## The models / 模型の約束
164
+
165
+ The view reads what each mesh is from its glTF `extras`:
166
+ 表示は網ごとの glTF の `extras` から、それが何かを読む。
167
+
168
+ | Model | Mesh | `extras` |
169
+ | --- | --- | --- |
170
+ | Site boxes (`massingUrl`) | A building | `sceneRole: "building"`, `buildingId`, `buildingCode`, `buildingName` (the last two may be empty) |
171
+ | | A tank | `sceneRole: "tank"`, `tankId` |
172
+ | Site drawing (`linesUrl`) | Lines, text | `sceneRole: "lines"` or `"text"` |
173
+ | A detailed building (`glbUrl`) | The lowest floor | `sceneRole: "slab"`, `floorName` |
174
+ | | The other floors | `sceneRole: "plate"`, `floorName` |
175
+ | | A floor plan's lines and text | `sceneRole: "lines"` or `"text"`, `floorName` |
176
+ | | A piece of equipment | `sceneRole: "equipment"`, `equipmentId`, `equipmentName`, `equipmentTag` (may be empty), `floorName`, `drawingQuery` |
177
+
178
+ An unknown role, a building, tank or piece of equipment missing a field, a part of a detailed building that names no floor, or equipment in the site model is reported through `onFailure`. The site model and the detailed models share one frame (east +X, north +Y and up +Z in the tool that builds them, in metres), which the glTF loader turns the same way for both. `floorName` is a floor's `name` in `details[].floors`.
179
+ 知らない役、項目の欠けた建屋・タンク・機器、階を名乗らない詳しい建屋の部品、構内の模型の機器は `onFailure` で知らせる。構内の模型と詳しい模型は 1 つの軸 (作る道具で東が +X・北が +Y・上が +Z、m) を共にし、glTF の読み手はどちらも同じ形で回す。`floorName` は `details[].floors` の階の `name`。
180
+
181
+ ---
182
+
183
+ ## Network / 通信
184
+
185
+ The view fetches the GLB URLs it is given and nothing else; the markers fetch nothing (their name tags are drawn on a canvas in the browser's own `sans-serif` font). Babylon.js fetches a decoder from its own CDN only for a model compressed with Draco, meshopt or KTX2 / Basis textures, so build the models without those compressions (or point Babylon.js's decoder URLs at the host before the canvas mounts).
186
+ 表示は渡された GLB の URL だけを読み、印は何も読まない (名札はブラウザ自身の `sans-serif` の字体でキャンバスに描く)。Babylon.js は Draco・meshopt・KTX2 / Basis で縮めた模型のときだけ自身の CDN から復号器を読むので、模型はそれらで縮めずに作ること (またはキャンバスを置く前に Babylon.js の復号器の URL を使い手へ向けること)。
187
+
188
+ ---
189
+
190
+ ## Bundling with Vite / Vite での束ね方
191
+
192
+ - **Pre-bundle the package** (`optimizeDeps.include: ["@aiquants/plant-scene"]`). A host whose dev server does not scan its sources for dependencies (React Router's default) otherwise finds the package and the Babylon.js modules of its scene chunk only on the first visit, and reloads the page to optimize them.
193
+ - **パッケージを事前バンドルに挙げる**。依存を探しにソースを走査しない開発サーバー (React Router の既定) では、挙げなければ初めて訪れたときにパッケージと場面の塊の Babylon.js のモジュールが見つかり、それらを最適化するために画面を読み直す。
194
+ - **Name the pre-bundled chunks without the source's name** (`optimizeDeps.esbuildOptions: { chunkNames: "chunk-[hash]" }`). A chunk named after a Babylon.js shader (`default.vertex-XXXX.js`) has a dot in its name and is served without its version query, so after the dev server optimizes again a browser keeps an old copy and the scene draws nothing.
195
+ - **事前バンドルの塊の名に元の名を入れない**。Babylon.js の色付け器の名の塊 (`default.vertex-XXXX.js`) は名に点があり版の問い合わせなしで配られるので、開発サーバーが最適化し直した後もブラウザが古い写しを使い、場面が何も描かない。
196
+ - **Keep Babylon.js in a chunk of its own** when the build groups `node_modules` into named chunks (`manualChunks`), so no other page's chunk depends on it statically. Match Babylon.js by its own directory (`/node_modules/@babylonjs/`), not by `@babylonjs` anywhere in a module's path: pnpm writes a package's peers into its directory name (`@aiquants+plant-scene@0.1.0_@babylonjs+core@…`), so the looser test also moves this package's own modules, the canvas included, into the Babylon.js chunk, and the page then loads Babylon.js before the view mounts.
197
+ - 組み立てが `node_modules` を名前付きの塊へまとめるときは、**Babylon.js を自分の塊に置く** (ほかの画面の塊が静的に頼らないように)。Babylon.js は自身のディレクトリ (`/node_modules/@babylonjs/`) で見分け、モジュールの道のどこかにある `@babylonjs` では見分けない。pnpm はパッケージの peer をディレクトリの名に書く (`@aiquants+plant-scene@0.1.0_@babylonjs+core@…`) ので、緩い見分けはこのパッケージ自身のモジュール (キャンバスを含む) まで Babylon.js の塊へ移し、画面は表示を置く前に Babylon.js を読む。
198
+
199
+ ---
200
+
201
+ ## Test hooks / 試験のフック
202
+
203
+ - The canvas is `data-testid="plant-scene-canvas"`.
204
+ - Every frame drawn writes the camera into the canvas's `data-camera-pose`: alpha, beta, radius and the target's x, y and z, split by spaces.
205
+ - キャンバスは `data-testid="plant-scene-canvas"`。描くコマごとに視点をキャンバスの `data-camera-pose` へ書く (alpha・beta・radius・注視点の x・y・z を空白で分ける)。
206
+ - Every frame drawn writes the markers in sight into the canvas's `data-marker-positions` as JSON, in the order of `markers`: `[{ "id": "point-7", "x": 412.5, "y": 233.25 }]`, where a tap at x, y (CSS pixels from the canvas's top left corner) picks that marker. A marker hidden (a building shown alone, the option off), behind the camera, outside the canvas or covered there by a nearer marker is left out; a page's panel laid over the canvas may still cover a listed point.
207
+ - 描くコマごとに、見えている印をキャンバスの `data-marker-positions` へ JSON で `markers` の順に書く (`[{ "id": "point-7", "x": 412.5, "y": 233.25 }]`。キャンバスの左上の角から CSS の px で x・y の所を押すと、その印が選ばれる)。隠した印 (建屋を 1 つだけ見せる間・オプションを切った間)・視点の後ろの印・キャンバスの外の印・そこを手前の印が覆う印は書かない。画面の欄がキャンバスに重なれば、書いた点を覆うこともある。
208
+
209
+ ---
210
+
211
+ ## What ships / 配るもの
212
+
213
+ `dist/` holds the minified ES modules (the entry and the chunks it loads, Babylon.js kept external) and one declaration file whose comments are removed; no source map ships. This README is the reference.
214
+ `dist/` には縮めた ES モジュール (入口と、それが読む塊。Babylon.js は外のまま) と注記を除いた宣言のファイル 1 つがあり、ソースマップは配らない。説明はこの README。
215
+
216
+ ---
217
+
218
+ ## License / ライセンス
219
+
220
+ MIT
@@ -0,0 +1,4 @@
1
+ var E=/^#[0-9a-f]{6}$/iu,h=e=>typeof e=="string"&&E.test(e),O=["sky","ground","ink","floor"],B=e=>{for(let t of O){let n=e[t];if(!h(n))throw new RangeError(`the scene's ${t} colour must be #rrggbb, not ${JSON.stringify(n)}`)}return e},T=e=>{let t=new Set;for(let{id:n,label:r,position:o,color:i}of e){let s=JSON.stringify(n);if(typeof n!="string"||n==="")throw new RangeError(`a site marker's id must be a string that is not empty, not ${s}`);if(t.has(n))throw new RangeError(`two site markers share the id ${s}`);if(t.add(n),typeof r!="string"||r.trim()==="")throw new RangeError(`site marker ${s} needs a label that is not blank, not ${JSON.stringify(r)}`);if(!(Number.isFinite(o.x)&&Number.isFinite(o.z)))throw new RangeError(`site marker ${s} must stand at a finite point, not x ${o.x}, z ${o.z}`);if(!h(i))throw new RangeError(`site marker ${s}'s colour must be #rrggbb, not ${JSON.stringify(i)}`)}return e};var k={top:0,bottom:0},$=.15,N=1e-4,j=e=>{for(let t of[e.top,e.bottom])if(!Number.isFinite(t)||t<0)throw new RangeError(`view insets must be finite and not negative: top ${e.top}, bottom ${e.bottom}`);if(e.top+e.bottom>=1)throw new RangeError(`view insets must leave some height in sight: top ${e.top}, bottom ${e.bottom}`);return e},L=(e,t)=>{let n=e.bottom-e.top,r=e.right-e.left;if(!(Number.isFinite(n)&&Number.isFinite(r)&&n>0&&r>0))return k;let o=(e.top+e.bottom)/2,i=0,s=0;for(let l of t){let a={left:Math.max(l.left,e.left),top:Math.max(l.top,e.top),right:Math.min(l.right,e.right),bottom:Math.min(l.bottom,e.bottom)};a.left<a.right&&a.top<a.bottom&&((a.top+a.bottom)/2<o?i=Math.max(i,a.bottom-e.top):s=Math.max(s,e.bottom-a.top))}let d={top:i/n,bottom:s/n};return d.top+d.bottom<1?d:k},V=(e,t,n)=>{if(!Number.isFinite(n)||n<0)throw new RangeError(`elapsed seconds must be finite and not negative: ${n}`);let r=1-Math.exp(-n/$),o=(i,s)=>{let d=i+(s-i)*r;return Math.abs(s-d)<N?s:d};return{top:o(e.top,t.top),bottom:o(e.bottom,t.bottom)}},X=(e,t)=>{let n=1-t.top-t.bottom,r=t.bottom-t.top,o=e.m;for(let i=0;i<4;i+=1){let s=i*4;e.setRowFromFloats(i,o[s]*n,o[s+1]*n+o[s+3]*r,o[s+2],o[s+3])}};var S=(e,t)=>({x:-(e[0]-t[0])/1e3,z:-(e[1]-t[1])/1e3}),K=(e,t)=>{let{x:n,z:r}=S(e.offsetMm,t);return{rotationY:-e.rotationDeg*Math.PI/180,position:[n,0,r]}},v=(e,t)=>{if(![e[0],e[1],t[0],t[1]].every(n=>Number.isFinite(n)))throw new RangeError(`a site marker's point and the site's origin must be finite: point [${e.join(", ")}], origin [${t.join(", ")}]`);return S(e,t)},Z=(e,t,n,r)=>{let o=d=>{let l=e.find(a=>a.name===d);if(l===void 0)throw new Error(`floor ${d} is not one of the building's floors (${e.map(a=>a.name).join(", ")})`);return l.levelMm},i=o(n);if(t===null)return"shown";let s=o(t);return i>s?"hidden":i<s&&(r==="lines"||r==="text")?"faint":"shown"},Y=({alone:e,open:t,envelope:n,near:r})=>e||t&&!n?"hidden":t?"envelope":r?"see-through":"solid";var w=(e,t)=>Math.hypot(Math.max(0,e.minX-t.maxX,t.minX-e.maxX),Math.max(0,e.minZ-t.maxZ,t.minZ-e.maxZ)),J=(e,t)=>{let n=Math.hypot(e.maxX-e.minX,e.maxZ-e.minZ)*1;return t.filter(r=>w(e,r.footprint)<=n).map(r=>r.id)},G=({alone:e,markers:t})=>!e&&t;var Q=(e,t,n)=>{let r={minX:e.x,maxX:e.x,minZ:e.z,maxZ:e.z},o=n+6;for(let i of t)w(r,i.footprint)<=10&&(o=Math.max(o,i.top+4));return o};var f=e=>e.normalize("NFKC").toLowerCase(),M=e=>f(e).split(/\s+/u).filter(t=>t!=="");import{z as u}from"zod";var q=["building","tank","lines","text","slab","plate","equipment"],I=u.object({gltf:u.object({extras:u.record(u.string(),u.unknown())})}),P=u.object({sceneRole:u.enum(q),floorName:u.string().min(1).optional()}),D=u.object({buildingId:u.string().min(1),buildingCode:u.string(),buildingName:u.string()}),_=u.object({tankId:u.string().min(1)}),F=u.object({equipmentId:u.string().min(1),equipmentName:u.string().min(1),equipmentTag:u.string(),floorName:u.string().min(1),drawingQuery:u.string().min(1)}),R=e=>{let t=I.safeParse(e);return t.success?t.data.gltf.extras:null},A=(e,t)=>`${e}/${t}`,ne=e=>{let t=R(e);if(t===null||!("sceneRole"in t))return null;let n=P.parse(t);return{role:n.sceneRole,floor:n.floorName===void 0?null:n.floorName}},re=(e,t)=>{let n=R(e);if(n===null)return null;if("buildingId"in n){let r=D.parse(n);return{kind:"building",id:r.buildingId,code:r.buildingCode,name:r.buildingName}}if("tankId"in n)return{kind:"tank",id:_.parse(n).tankId};if("equipmentId"in n){let r=F.parse(n);if(t===null)throw new Error(`equipment ${r.equipmentId} is in the site's model, outside every detailed building`);return{kind:"equipment",id:A(t,r.equipmentId),detailKey:t,name:r.equipmentName,tag:r.equipmentTag,floor:r.floorName,query:r.drawingQuery}}return null},oe=(e,t)=>{for(let n=e;n!==null;n=n.parent){let r=t(n.metadata);if(r!==null)return r}return null},g=e=>{switch(e.kind){case"marker":return e.label;case"tank":return`\u30BF\u30F3\u30AF (${e.id})`;case"equipment":return e.tag===""?`${e.name} (${e.floor})`:`${e.name} (${e.tag}\u30FB${e.floor})`;case"building":return e.name===""?`\u540D\u524D\u306E\u7121\u3044\u5EFA\u5C4B (${e.id})`:e.code===""?e.name:`${e.name} (${e.code})`}},b=(e,t)=>{let n=t.find(r=>r.key===e.detailKey);if(n===void 0)throw new Error(`equipment ${e.id} belongs to detailed building ${e.detailKey}, which the manifest does not have`);return n},ie=(e,t)=>{switch(e.kind){case"equipment":return{building:b(e,t).buildingName,query:e.query};case"building":return e.name===""?null:{building:e.name,query:""};case"tank":case"marker":return null}},ae=(e,t,n,r)=>{let o=M(n),i=l=>{let a=f(l);return o.every(p=>a.includes(p))},s=e.filter(l=>l.kind==="equipment"),d=[];for(let l of e){if(l.kind!=="building")continue;let a=t.find(c=>c.buildingId===l.id);if(a===void 0&&l.name===""||r!==null&&a?.key!==r)continue;let p=i(`${l.name}
2
+ ${l.code}`),x=a===void 0?[]:[...a.floors].sort((c,m)=>m.levelMm-c.levelMm).map(c=>({floor:c,equipment:s.filter(m=>m.detailKey===a.key&&m.floor===c.name&&(p||i(`${m.name}
3
+ ${m.tag}
4
+ ${m.floor}`))).sort((m,y)=>m.name.localeCompare(y.name,"ja")||m.id.localeCompare(y.id))})).filter(c=>p||c.equipment.length>0);(p||x.length>0)&&d.push({building:l,detail:a===void 0?null:a,floors:x})}return d.sort((l,a)=>l.building.name.localeCompare(a.building.name,"ja")||l.building.id.localeCompare(a.building.id))},C=(e,t)=>{switch(e.kind){case"equipment":return b(e,t);case"building":{let n=t.find(r=>r.buildingId===e.id);return n===void 0?null:n}case"tank":case"marker":return null}},se=(e,t,n)=>{switch(e.kind){case"building":{let r=C(e,t);if(r===null)return{title:g(e),meta:"\u5EFA\u5C4B",detail:r};let o=n.filter(i=>i.kind==="equipment"&&i.detailKey===r.key).length;return{title:g(e),meta:`\u5EFA\u5C4B\u30FB\u8A73\u3057\u3044\u6A21\u578B\u3042\u308A (${r.floors.length} \u968E\u30FB\u6A5F\u5668 ${o})`,detail:r}}case"tank":return{title:g(e),meta:"\u30BF\u30F3\u30AF",detail:null};case"marker":return{title:g(e),meta:"\u5370",detail:null};case"equipment":{let r=b(e,t),o=e.tag===""?"":`\u30FB\u8A2D\u5099\u30BF\u30B0 ${e.tag}`;return{title:e.name,meta:`\u6A5F\u5668\u30FB${r.buildingName}\u306E ${e.floor}${o}`,detail:r}}}},le=e=>({kind:"marker",id:e.id,label:e.label}),ue=(e,t)=>{let n=new Map(t.map(r=>[r.id,r.kind]));for(let{id:r}of e){let o=n.get(r);if(o!==void 0)throw new RangeError(`site marker ${JSON.stringify(r)} has the id of an object of the models (${o})`)}return e};export{h as a,B as b,T as c,k as d,j as e,L as f,V as g,X as h,K as i,v as j,Z as k,Y as l,J as m,G as n,Q as o,f as p,M as q,ne as r,re as s,oe as t,g as u,ie as v,ae as w,C as x,se as y,le as z,ue as A};
@@ -0,0 +1,197 @@
1
+ import { z } from "zod";
2
+ import * as react from "react";
3
+ declare const displayOptionsSchema: z.ZodObject<{
4
+ shadows: z.ZodCatch<z.ZodBoolean>;
5
+ shading: z.ZodCatch<z.ZodBoolean>;
6
+ edges: z.ZodCatch<z.ZodBoolean>;
7
+ fadeLines: z.ZodCatch<z.ZodBoolean>;
8
+ envelope: z.ZodCatch<z.ZodBoolean>;
9
+ realHeights: z.ZodCatch<z.ZodBoolean>;
10
+ markers: z.ZodCatch<z.ZodBoolean>;
11
+ }, "strip", z.ZodTypeAny, {
12
+ shadows: boolean;
13
+ shading: boolean;
14
+ edges: boolean;
15
+ fadeLines: boolean;
16
+ envelope: boolean;
17
+ realHeights: boolean;
18
+ markers: boolean;
19
+ }, {
20
+ shadows?: unknown;
21
+ shading?: unknown;
22
+ edges?: unknown;
23
+ fadeLines?: unknown;
24
+ envelope?: unknown;
25
+ realHeights?: unknown;
26
+ markers?: unknown;
27
+ }>;
28
+ type DisplayOptions = z.infer<typeof displayOptionsSchema>;
29
+ type DisplayOptionKey = keyof DisplayOptions;
30
+ declare const DEFAULT_DISPLAY_OPTIONS: DisplayOptions;
31
+ type OptionSubjects = {
32
+ hasDetails: boolean;
33
+ hasHeights: boolean;
34
+ hasMarkers: boolean;
35
+ };
36
+ type OfferedOption = {
37
+ key: DisplayOptionKey;
38
+ label: string;
39
+ };
40
+ declare const offeredOptions: ({ hasDetails, hasHeights, hasMarkers }: OptionSubjects) => OfferedOption[];
41
+ declare const useDisplayOptions: (storageKey: string) => [
42
+ DisplayOptions,
43
+ (options: DisplayOptions) => void
44
+ ];
45
+ type PlantFloor = {
46
+ readonly name: string;
47
+ readonly levelMm: number;
48
+ };
49
+ type BuildingHeight = {
50
+ readonly buildingId: string;
51
+ readonly buildingName: string;
52
+ readonly heightMm: number;
53
+ };
54
+ type SceneDetail = {
55
+ readonly key: string;
56
+ readonly buildingId: string;
57
+ readonly buildingName: string;
58
+ readonly rotationDeg: number;
59
+ readonly offsetMm: readonly [
60
+ number,
61
+ number
62
+ ];
63
+ readonly floors: readonly PlantFloor[];
64
+ };
65
+ type ScenePaint = {
66
+ readonly sky: string;
67
+ readonly ground: string;
68
+ readonly ink: string;
69
+ readonly floor: string;
70
+ };
71
+ declare const checkedPaint: (paint: ScenePaint) => ScenePaint;
72
+ type MarkerPosition = {
73
+ readonly x: number;
74
+ readonly z: number;
75
+ };
76
+ type SiteMarker = {
77
+ readonly id: string;
78
+ readonly label: string;
79
+ readonly position: MarkerPosition;
80
+ readonly color: string;
81
+ };
82
+ declare const checkedMarkers: (markers: readonly SiteMarker[]) => readonly SiteMarker[];
83
+ type BuildingObject = {
84
+ kind: "building";
85
+ id: string;
86
+ code: string;
87
+ name: string;
88
+ };
89
+ type TankObject = {
90
+ kind: "tank";
91
+ id: string;
92
+ };
93
+ type EquipmentObject = {
94
+ kind: "equipment";
95
+ id: string;
96
+ detailKey: string;
97
+ name: string;
98
+ tag: string;
99
+ floor: string;
100
+ query: string;
101
+ };
102
+ type MarkerObject = {
103
+ kind: "marker";
104
+ id: string;
105
+ label: string;
106
+ };
107
+ type SceneObject = BuildingObject | TankObject | EquipmentObject | MarkerObject;
108
+ type SceneSelection = {
109
+ id: string;
110
+ focus: boolean;
111
+ };
112
+ declare const sceneObjectLabel: (object: SceneObject) => string;
113
+ type BuildingRequest = {
114
+ building: string;
115
+ query: string;
116
+ };
117
+ declare const buildingRequestOf: <D extends SceneDetail>(object: SceneObject, details: readonly D[]) => BuildingRequest | null;
118
+ type ListedFloor = {
119
+ floor: PlantFloor;
120
+ equipment: EquipmentObject[];
121
+ };
122
+ type ListedBuilding<D extends SceneDetail> = {
123
+ building: BuildingObject;
124
+ detail: D | null;
125
+ floors: ListedFloor[];
126
+ };
127
+ declare const listedBuildings: <D extends SceneDetail>(objects: readonly SceneObject[], details: readonly D[], filter: string, only: string | null) => ListedBuilding<D>[];
128
+ declare const detailOfObject: <D extends SceneDetail>(object: SceneObject, details: readonly D[]) => D | null;
129
+ type ObjectSummary<D extends SceneDetail> = {
130
+ title: string;
131
+ meta: string;
132
+ detail: D | null;
133
+ };
134
+ declare const objectSummary: <D extends SceneDetail>(object: SceneObject, details: readonly D[], objects: readonly SceneObject[]) => ObjectSummary<D>;
135
+ type DetailPlacement = {
136
+ rotationY: number;
137
+ position: readonly [
138
+ number,
139
+ number,
140
+ number
141
+ ];
142
+ };
143
+ declare const detailPlacement: (detail: Pick<SceneDetail, "rotationDeg" | "offsetMm">, originMm: readonly [
144
+ number,
145
+ number
146
+ ]) => DetailPlacement;
147
+ declare const markerPosition: (pointMm: readonly [
148
+ number,
149
+ number
150
+ ], originMm: readonly [
151
+ number,
152
+ number
153
+ ]) => MarkerPosition;
154
+ type ViewInsets = {
155
+ top: number;
156
+ bottom: number;
157
+ };
158
+ type DetailModel = {
159
+ key: string;
160
+ glbUrl: string;
161
+ buildingId: string;
162
+ placement: DetailPlacement;
163
+ floors: readonly PlantFloor[];
164
+ };
165
+ type SceneDisplay = {
166
+ isolated: string | null;
167
+ floor: string | null;
168
+ selection: SceneSelection | null;
169
+ };
170
+ type LegendEntry = {
171
+ label: string;
172
+ color: string;
173
+ };
174
+ type LoadedModels = {
175
+ objects: SceneObject[];
176
+ legend: LegendEntry[];
177
+ complete: boolean;
178
+ };
179
+ type PlantSceneCanvasProps = {
180
+ massingUrl: string;
181
+ linesUrl: string;
182
+ details: readonly DetailModel[];
183
+ heights: readonly BuildingHeight[];
184
+ markers: readonly SiteMarker[];
185
+ display: SceneDisplay;
186
+ options: DisplayOptions;
187
+ insets: ViewInsets;
188
+ paint: ScenePaint;
189
+ onPick: (object: SceneObject | null) => void;
190
+ onLoad: (models: LoadedModels) => void;
191
+ onFailure: (error: Error) => void;
192
+ };
193
+ declare const PlantSceneCanvas: ({ massingUrl, linesUrl, details, heights, markers, display, options, insets, paint, onPick, onLoad, onFailure }: PlantSceneCanvasProps) => react.JSX.Element;
194
+ declare const foldForSearch: (text: string) => string;
195
+ declare const searchTerms: (query: string) => string[];
196
+ declare const useViewInsets: (view: Element | null, panels: readonly (Element | null)[]) => ViewInsets;
197
+ export { type BuildingHeight, type BuildingObject, type BuildingRequest, DEFAULT_DISPLAY_OPTIONS, type DetailModel, type DetailPlacement, type DisplayOptionKey, type DisplayOptions, type EquipmentObject, type LegendEntry, type ListedBuilding, type ListedFloor, type LoadedModels, type MarkerObject, type MarkerPosition, type ObjectSummary, type OfferedOption, type OptionSubjects, type PlantFloor, PlantSceneCanvas, type PlantSceneCanvasProps, type SceneDetail, type SceneDisplay, type SceneObject, type ScenePaint, type SceneSelection, type SiteMarker, type TankObject, type ViewInsets, buildingRequestOf, checkedMarkers, checkedPaint, detailOfObject, detailPlacement, foldForSearch, listedBuildings, markerPosition, objectSummary, offeredOptions, sceneObjectLabel, searchTerms, useDisplayOptions, useViewInsets };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{b as w,c as k,d as h,e as H,f as A,i as ee,j as te,p as ne,q as oe,u as se,v as re,w as ie,x as ae,y as le}from"./chunk-SL5ZL75K.js";import{useCallback as F,useSyncExternalStore as pe}from"react";import{z as _}from"zod";var p=_.boolean().catch(!0),ce=_.object({shadows:p,shading:p,edges:p,fadeLines:p,envelope:p,realHeights:p,markers:p}),S={shadows:!0,shading:!0,edges:!0,fadeLines:!0,envelope:!0,realHeights:!0,markers:!0},ye=({hasDetails:e,hasHeights:t,hasMarkers:n})=>[{key:"shadows",label:"\u5F71"},{key:"shading",label:"\u9670\u5F71\u3092\u5F37\u3081\u308B"},{key:"edges",label:"\u8F2A\u90ED\u7DDA"},{key:"fadeLines",label:"\u9060\u304F\u306E\u7DDA\u3092\u8584\u304F"},...e?[{key:"envelope",label:"\u8A73\u3057\u3044\u5EFA\u5C4B\u306E\u5916\u58C1"}]:[],...t?[{key:"realHeights",label:"\u5B9F\u969B\u306E\u9AD8\u3055"}]:[],...n?[{key:"markers",label:"\u5370"}]:[]],ue=e=>{if(e===null)return S;try{let t=ce.safeParse(JSON.parse(e));return t.success?t.data:S}catch(t){if(t instanceof SyntaxError)return S;throw t}},D=new Set,de=e=>(D.add(e),window.addEventListener("storage",e),()=>{D.delete(e),window.removeEventListener("storage",e)}),N=new Map,fe=e=>{let t=window.localStorage.getItem(e),n=N.get(e);if(n!==void 0&&n.text===t)return n.options;let o=ue(t);return N.set(e,{text:t,options:o}),o},Oe=()=>S,me=(e,t)=>{window.localStorage.setItem(e,JSON.stringify(t));for(let n of D)n()},Se=e=>{if(e==="")throw new RangeError("useDisplayOptions needs a storage key");let t=F(()=>fe(e),[e]),n=F(o=>me(e,o),[e]);return[pe(de,t,Oe),n]};import{useEffect as d,useEffectEvent as i,useRef as P}from"react";import{jsx as we}from"react/jsx-runtime";var be={position:"absolute",top:0,right:0,bottom:0,left:0,display:"block",width:"100%",height:"100%",touchAction:"none",outlineStyle:"none"},q=e=>e instanceof Error?e:new Error(String(e)),ge=({massingUrl:e,linesUrl:t,details:n,heights:o,markers:r,display:f,options:a,insets:s,paint:c,onPick:Y,onLoad:J,onFailure:U})=>{let v=P(null),y=P(null),b=P(null),G=i(Y),Q=i(J),x=i(U),W=i(()=>f),X=i(()=>c),Z=i(()=>s),$=i(()=>a),K=i(()=>r),{isolated:E,floor:L,selection:j}=f,{top:I,bottom:M}=H(s),{sky:V,ground:R,ink:C,floor:T}=w(c);return k(r),d(()=>{let O=v.current;if(O===null)return;let u=!1,B=()=>{};return(async()=>{let{openPlantSceneView:g}=await import("./plantScene-W6XPMVO7.js");if(u)return;let m=g(O,X(),$(),l=>G(l));y.current=m,B=m.close,m.inset(Z()),m.markers(K()),await m.load({massingUrl:e,linesUrl:t},n,o,l=>{u||(b.current=l,l.show(W()),Q({objects:l.objects,legend:l.legend,complete:l.complete}))})})().catch(g=>{u||x(q(g))}),()=>{u=!0,y.current=null,b.current=null,B()}},[e,t,n,o]),d(()=>{y.current?.paint({sky:V,ground:R,ink:C,floor:T})},[V,R,C,T]),d(()=>{y.current?.inset({top:I,bottom:M})},[I,M]),d(()=>{y.current?.options(a)},[a]),d(()=>{let O=y.current;if(O!==null)try{O.markers(r)}catch(u){x(q(u))}},[r]),d(()=>{b.current?.show({isolated:E,floor:L,selection:j})},[E,L,j]),we("canvas",{ref:v,"data-testid":"plant-scene-canvas",style:be,"aria-label":"\u5DE5\u5834\u306E 3D \u6A21\u578B"})};import{useEffect as ke,useState as he}from"react";var z=e=>{let{left:t,top:n,right:o,bottom:r}=e.getBoundingClientRect();return{left:t,top:n,right:o,bottom:r}},De=(e,t)=>{let[n,o]=he(h);return ke(()=>{if(e===null){o(h);return}let r=t.filter(s=>s!==null),f=()=>{let s=A(z(e),r.map(z));o(c=>c.top===s.top&&c.bottom===s.bottom?c:s)},a=new ResizeObserver(f);a.observe(e);for(let s of r)a.observe(s);return f(),()=>a.disconnect()},[e,t]),n};export{S as DEFAULT_DISPLAY_OPTIONS,ge as PlantSceneCanvas,re as buildingRequestOf,k as checkedMarkers,w as checkedPaint,ae as detailOfObject,ee as detailPlacement,ne as foldForSearch,ie as listedBuildings,te as markerPosition,le as objectSummary,ye as offeredOptions,se as sceneObjectLabel,oe as searchTerms,Se as useDisplayOptions,De as useViewInsets};
@@ -0,0 +1 @@
1
+ import{A as de,a as rt,b as ke,c as st,d as it,e as at,g as lt,h as ct,k as dt,l as ut,m as mt,n as pt,o as ht,r as Ae,s as Re,t as ne,z as ft}from"./chunk-SL5ZL75K.js";import"@babylonjs/core/Animations/animatable.js";import"@babylonjs/core/Culling/ray.js";import"@babylonjs/core/Rendering/edgesRenderer.js";import"@babylonjs/loaders/glTF/index.js";import{Animation as $}from"@babylonjs/core/Animations/animation.js";import{ArcRotateCamera as wn}from"@babylonjs/core/Cameras/arcRotateCamera.js";import{ArcRotateCameraPointersInput as Pn}from"@babylonjs/core/Cameras/Inputs/arcRotateCameraPointersInput.js";import{Engine as In}from"@babylonjs/core/Engines/engine.js";import{PointerEventTypes as En}from"@babylonjs/core/Events/pointerEvents.js";import{HighlightLayer as On}from"@babylonjs/core/Layers/highlightLayer.js";import{DirectionalLight as kn}from"@babylonjs/core/Lights/directionalLight.js";import{HemisphericLight as jt}from"@babylonjs/core/Lights/hemisphericLight.js";import{ShadowGenerator as An}from"@babylonjs/core/Lights/Shadows/shadowGenerator.js";import{ImportMeshAsync as De}from"@babylonjs/core/Loading/sceneLoader.js";import{Material as $t}from"@babylonjs/core/Materials/material.js";import{StandardMaterial as me}from"@babylonjs/core/Materials/standardMaterial.js";import{DynamicTexture as Rn}from"@babylonjs/core/Materials/Textures/dynamicTexture.js";import{RenderTargetTexture as Tn}from"@babylonjs/core/Materials/Textures/renderTargetTexture.js";import{Color3 as k,Color4 as Gt}from"@babylonjs/core/Maths/math.color.js";import{Matrix as _n,Vector3 as P}from"@babylonjs/core/Maths/math.vector.js";import{CreateCylinder as Nn}from"@babylonjs/core/Meshes/Builders/cylinderBuilder.js";import{CreateGround as Ln}from"@babylonjs/core/Meshes/Builders/groundBuilder.js";import{CreatePlane as Dn}from"@babylonjs/core/Meshes/Builders/planeBuilder.js";import{CreateSphere as Cn}from"@babylonjs/core/Meshes/Builders/sphereBuilder.js";import{Mesh as vn}from"@babylonjs/core/Meshes/mesh.js";import{TransformNode as Fe}from"@babylonjs/core/Meshes/transformNode.js";import{Scene as Fn}from"@babylonjs/core/scene.js";var _e=1e3,Mt=2,ue=[-.5,-1,.35],sn=-ue[1]/Math.hypot(...ue),an={sky:.55,skyGround:[.3,.3,.34],sun:1},ln={sky:.75,skyGround:[.45,.45,.5],sun:.6},yt=e=>e?an:ln,cn=.85,St=(e,n,r,l)=>{let c=n/2/cn/(Math.tan(r/2)*l);return Number.isFinite(c)?Math.max(e,c):e},wt=e=>1-e*sn,dn=.35,un=1,mn=.7,Pt=(e,n)=>{let r=n*dn,l=n*un;return mn*Math.min(1,Math.max(0,(e-r)/(l-r)))},pn=1,hn=50,It=(e,n)=>2*hn*pn*e/n,Et=(e,n,r)=>{let l=r/(n-e);return{scaleY:l,offsetY:e-e*l}},Ot=(e,n)=>e===null?n:e/_e,kt=(e,n,r)=>{if(n!==null)return n/_e;let l=e.at(-1),c=e.at(-2);return l===void 0||c===void 0?r:(l.levelMm*2-c.levelMm)/_e},Te=3,At=()=>{let e=Te,n=[];return{invalidate:()=>{e=Te},shouldDraw:(r,l)=>{let c=r.length!==n.length||r.some((i,I)=>i!==n[I]);return n=r,(c||l)&&(e=Te),e>0},drawn:r=>{r&&(e=Math.max(0,e-1))}}},fn=[6,12],gt=8,Rt=(e,n)=>fn.flatMap(r=>Array.from({length:gt},(l,c)=>{let i=c/gt*2*Math.PI;return{x:e+r*Math.cos(i),y:n+r*Math.sin(i)}})),gn=Math.PI/4,Tt=e=>Math.min(e,gn),_t=(e,n,r,l)=>r/(2*e*Math.tan(n/2))/(1-l),Nt=4,Lt=(e,n,r,l)=>{let c=(r-e.y)/n.y;return c>0&&c<=l?{x:e.x+n.x*c,y:r,z:e.z+n.z*c}:null},Dt=(e,n,r,l,c)=>{let i=e.x+n.x-r.x-l.x,I=e.z+n.z-r.z-l.z,d=Math.min(1,c/Math.hypot(i,I));return{x:l.x+i*d,y:e.y,z:l.z+I*d}},Ct=(e,n,r)=>2*e*Math.tan(n/2)/r,vt=(e,n,r,l)=>{let c=n.x*e[0]+n.y*e[4]+n.z*e[8]+e[12],i=n.x*e[1]+n.y*e[5]+n.z*e[9]+e[13],I=n.x*e[3]+n.y*e[7]+n.z*e[11]+e[15];if(!(I>0))return null;let d=c/I,p=i/I;return Math.abs(d)>1||Math.abs(p)>1?null:{x:(d+1)/2*r,y:(1-p)/2*l}},bt=e=>{if(!rt(e))throw new RangeError(`a colour must be #rrggbb, not ${JSON.stringify(e)}`);let[n,r,l]=[1,3,5].map(c=>{let i=Number.parseInt(e.slice(c,c+2),16)/255;return i<=.04045?i/12.92:((i+.055)/1.055)**2.4});return .2126*n+.7152*r+.0722*l},xt=(e,n)=>{let[r,l]=[bt(e),bt(n)].sort((c,i)=>i-c);return(r+.05)/(l+.05)},bn=["#000000","#ffffff"],Ft=e=>{let[n,r]=bn;return xt(e,n)>=xt(e,r)?n:r},Ne=16,Le=3,xn=19,Mn=28,yn=8,Sn=4,Ht=e=>`bold ${Math.round(xn*e)}px sans-serif`,Bt=(e,n)=>{let r=Math.ceil(e+2*yn*n),l=Math.round(Mn*n),c=r/n;return{textureWidth:r,textureHeight:l,widthPx:c,heightPx:l/n,offsetPx:Ne/2+Sn+c/2}};var Hn=[1,.78,.18],Bn=2.7,jn=4,Wt=1.1,Gn=3,Wn=5,zn=1.3,Vn=2,Ce=30,Xn=.05,Un=1.3,$n=.35,Yn=.25,Zn=.25,Kn=.22,qn=.005,Jn=.05,Qn=2048,eo=.45,to=3e-4,no=2,oo=.95,ro=[.12,.16,.22,.55],zt=new Set(["building","tank","slab","equipment"]),so=new Set(["building","tank","equipment"]),io=e=>{let n=e.material;return n!==null&&"albedoColor"in n&&n.albedoColor instanceof k?n.albedoColor.toGammaSpace().toHexString():null},oe=(e,n,r)=>{e.setEnabled(n!=="hidden"),e.visibility=n==="faint"?Zn:1,e.isPickable=r&&n==="shown"},Vt=(e,n,r)=>{e.material=n,e.setEnabled(!0),e.visibility=r,e.isPickable=!1},ao=e=>{let n=e.clone(`${e.name}-see-through`);if(n===null)throw new Error(`the site model's material ${e.name} cannot be copied`);return n.transparencyMode=$t.MATERIAL_ALPHABLEND,n.backFaceCulling=!0,n},Xt=e=>e.flatMap(n=>{let r=ne(n,Ae);return r===null?[]:[{mesh:n,part:r,detail:null,object:ne(n,l=>Re(l,null))}]}),re=e=>e.detail===null&&(e.part.role==="building"||e.part.role==="tank"),Ut=e=>({min:e.reduce((n,r)=>P.Minimize(n,r.min),new P(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)),max:e.reduce((n,r)=>P.Maximize(n,r.max),new P(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY))}),ve=1,lo=e=>{e.setRenderingAutoClearDepthStencil(ve,!0,!0,!1);let n=[],r=!1,l=new Map,c=P.Zero(),i=d=>{let p=`marker-${d.id}`,h=new me(`${p}-paint`,e);h.disableLighting=!0,h.emissiveColor=k.FromHexString(d.color);let x=1/e.getEngine().getHardwareScalingLevel(),M=Ht(x),_=new Rn(`${p}-tag`,{width:1,height:1},e,!1),z=_.getContext();z.font=M;let C=Bt(z.measureText(d.label).width,x);_.scaleTo(C.textureWidth,C.textureHeight),_.drawText(d.label,null,null,M,Ft(d.color),d.color,!0,!0);let L=new me(`${p}-board`,e);L.disableLighting=!0,L.emissiveTexture=_;let G=new Fe(p,e),A=Nn(`${p}-pole`,{height:1,diameter:1,tessellation:12},e),R=Cn(`${p}-head`,{diameter:1,segments:12},e),D=Dn(`${p}-tag`,{width:C.widthPx,height:C.heightPx},e);D.bakeTransformIntoVertices(_n.Translation(C.offsetPx,0,0)),D.billboardMode=Fe.BILLBOARDMODE_ALL,D.material=L,A.material=h,R.material=h,A.isPickable=!1,R.renderingGroupId=ve,D.renderingGroupId=ve;for(let Y of[A,R,D])Y.parent=G;G.setEnabled(r);let X={object:ft(d),position:d.position,root:G,pole:A,head:R,tag:D,headPoint:P.Zero(),paint:h,board:L,texture:_};return l.set(R,X),l.set(D,X),X},I=(d,p)=>{if(!r||n.length===0)return null;let{pickedMesh:h}=e.pick(d,p,M=>l.has(M)&&M.isEnabled()&&M.isPickable),x=h===null?void 0:l.get(h);return x===void 0?null:x.object};return{draw:d=>{for(let p of n)p.root.dispose(),p.paint.dispose(),p.board.dispose(),p.texture.dispose();l.clear(),n=d.map(i)},place:(d,p)=>{for(let h of n){let x=ht(h.position,p,d)-d;h.root.position.copyFromFloats(h.position.x,d,h.position.z),h.pole.position.y=x/2,h.pole.scaling.y=x,h.head.position.y=x,h.tag.position.y=x,h.headPoint.copyFromFloats(h.position.x,d+x,h.position.z)}},show:d=>{r=d;for(let p of n)p.root.setEnabled(d)},scale:(d,p,h,x)=>{if(r)for(let M of n){P.TransformCoordinatesToRef(M.headPoint,d,c);let _=Ct(Math.max(c.z,x),p,h);M.head.scaling.setAll(Ne*_),M.tag.scaling.setAll(_),M.pole.scaling.x=Le*_,M.pole.scaling.z=Le*_}},meshesOf:d=>{let p=n.find(h=>h.object.id===d);return p===void 0?[]:[p.pole,p.head]},at:I,positions:(d,p,h)=>r?n.flatMap(x=>{let M=vt(d.m,x.headPoint,p,h);return M===null||I(M.x,M.y)?.id!==x.object.id?[]:[{id:x.object.id,x:M.x,y:M.y}]}):[]}},Vo=(e,n,r,l)=>{ke(n);let c=new In(e,!0,{stencil:!0,preserveDrawingBuffer:!1,limitDeviceRatio:Mt},!0),i=new Fn(c),I=At(),d=o=>{let s=new me(o,i);return s.disableLighting=!0,s},p=o=>{let s=new me(o,i);return s.specularColor=k.Black(),s},h=p("ground"),x=d("ink-lines");x.fillMode=$t.LineListDrawMode;let M=d("ink-text");M.backFaceCulling=!1;let _=p("floor-slab"),z=d("floor-plate");z.alpha=$n,z.backFaceCulling=!1;let C=new jt("sky",P.Up(),i),L=new kn("sun",new P(...ue),i),G=new jt("ground-fill",P.Up(),i);G.groundColor=k.Black(),G.specular=k.Black();let A=Ln("ground",{width:1,height:1},i);A.material=h,A.isPickable=!1,A.receiveShadows=!0,C.excludedMeshes=[A],G.includedOnlyMeshes=[A];let R=new An(Qn,L);R.usePercentageCloserFiltering=!0,R.setDarkness(eo),R.bias=to,R.transparencyShadow=!0;let D=R.getShadowMap();if(D===null)throw new Error("the sun's shadow generator has no shadow map");D.refreshRate=Tn.REFRESHRATE_RENDER_ONCE;let X=new k,Y=new k,Yt=new Gt(...ro),pe=0,v=r,Z=it,K=!1,se=!0,he=()=>{},q=()=>{K=!1,I.invalidate()},He=()=>{k.LerpToRef(X,Y,pe,x.emissiveColor),M.emissiveColor.copyFrom(x.emissiveColor)},Be=o=>{let{sky:s,ground:f,ink:g,floor:S}=ke(o);i.clearColor=Gt.FromColor3(k.FromHexString(s),1),Y.copyFrom(k.FromHexString(f)),h.diffuseColor.copyFrom(Y),X.copyFrom(k.FromHexString(g)),He(),_.diffuseColor=k.FromHexString(S),z.emissiveColor=k.FromHexString(S),q()};Be(n);let T=[],je=new Map,fe=new Map,Ge=new Map,ge=new Map,We=new Map,ze=new Map,be=null,xe={isolated:null,floor:null,selection:null},Me=new On("selection",i),Zt=new k(...Hn),W=lo(i),ye=!1,ie=[],Kt=o=>T.filter(s=>s.object?.id===o&&s.part.role!=="lines"&&s.part.role!=="text"&&!(s.detail===null&&ge.has(o))).map(s=>s.mesh),J=()=>[...new Map(T.flatMap(o=>o.object===null?[]:[[o.object.id,o.object]])).values()],Ve=()=>{if(!ye)return;let o=T.filter(re).map(({mesh:s})=>{s.computeWorldMatrix(!0);let{minimumWorld:f,maximumWorld:g}=s.getBoundingInfo().boundingBox;return{footprint:{minX:f.x,maxX:g.x,minZ:f.z,maxZ:g.z},top:g.y}});W.place(A.position.y,o)},qt=(o,s,f,g)=>{let S=o.object!==null&&zt.has(o.part.role),E=je.get(o.mesh);if(E===void 0){oe(o.mesh,s?"hidden":"shown",S);return}let m=g?.has(String(o.mesh.uniqueId))===!0;m?R.removeShadowCaster(o.mesh,!1):R.addShadowCaster(o.mesh,!1);let F=f!==void 0&&o.object?.id===f.buildingId;switch(ut({alone:s,open:F,envelope:v.envelope,near:m})){case"hidden":oe(o.mesh,"hidden",S);break;case"envelope":Vt(o.mesh,E.seeThrough,Kn);break;case"see-through":Vt(o.mesh,E.seeThrough,Yn);break;case"solid":o.mesh.material=E.solid,oe(o.mesh,"shown",S);break}},Se=o=>{xe=o;let s=be===null||o.isolated===null?null:be.find(m=>m.key===o.isolated);if(s===void 0)throw new Error(`no detailed building ${o.isolated} to show alone`);let f=o.selection===null?void 0:ze.get(o.selection.id),g=s===null?f:s,S=s===null&&f!==void 0?We.get(f.key):void 0;for(let m of T){if(m.detail===null){qt(m,s!==null,g,S);continue}let F=m.object!==null&&zt.has(m.part.role);if(m.detail.key!==g?.key){oe(m.mesh,"hidden",F);continue}let H=m.part.floor;if(H===null)throw new Error(`a ${m.part.role} of detailed building ${m.detail.key} names no floor`);oe(m.mesh,s===null?"shown":dt(m.detail.floors,o.floor,H,m.part.role),F)}W.show(pt({alone:s!==null,markers:v.markers})),Me.removeAllMeshes();let E=o.selection===null?[]:[...Kt(o.selection.id),...W.meshesOf(o.selection.id)].filter(m=>m.isEnabled());for(let m of E)m instanceof vn&&Me.addMesh(m,Zt);return{isolated:s,selectedMeshes:E}},Jt=o=>{v.edges&&o.edgesRenderer===null&&(o.enableEdgesRendering(oo,!0),o.edgesColor=Yt),o.edgesRenderer!==null&&(o.edgesRenderer.isEnabled=v.edges)},Qt=({mesh:o,object:s})=>{if(s?.kind!=="building")return;let{minimum:f,maximum:g}=o.getBoundingInfo().boundingBox,S=g.y-f.y,E=v.realHeights?Ge.get(s.id)??null:null,m=ge.get(s.id),F=m===void 0?Ot(E,S):kt(m.floors,E,S),{scaleY:H,offsetY:N}=Et(f.y,g.y,F);o.scaling.y=H,o.position.y=N},ae=()=>{let o=yt(v.shading);C.intensity=o.sky,C.groundColor=new k(...o.skyGround),L.intensity=o.sun,G.intensity=wt(o.sun),L.shadowEnabled=v.shadows;for(let s of T)re(s)&&(Jt(s.mesh),Qt(s));Ve(),Se(xe),se=!0,q()};ae();let Xe=o=>{let{min:s,max:f}=Ut(o),g=P.Center(s,f),S=Math.max(f.x-s.x,f.z-s.z)*Un;A.scaling=new P(S,1,S),A.position=new P(g.x,s.y-Xn,g.z);let E=S*no;L.position=g.subtract(L.direction.normalizeToNew().scale(E)),L.shadowMinZ=1,L.shadowMaxZ=E*2},en=o=>{let s=new Map;for(let{mesh:f}of o.filter(re)){let g=f.material;if(g===null)throw new Error(`the site model's box ${f.name} has no material`);let S=s.get(g)??ao(g);s.set(g,S),je.set(f,{solid:g,seeThrough:S})}},Ue=o=>{for(let{mesh:s,part:f}of o)so.has(f.role)&&R.addShadowCaster(s,!1);for(let s of o)s.mesh.receiveShadows=re(s)||s.part.role==="slab"},$e=new ResizeObserver(()=>{c.resize(),I.invalidate(),he()});$e.observe(e);let Ye=()=>I.invalidate();document.addEventListener("visibilitychange",Ye),c.onContextRestoredObservable.add(q);let U=new AbortController;return{load:async(o,s,f,g)=>{let S=await De(o.massingUrl,i,{pluginExtension:".glb"});if(i.isDisposed)return;T.push(...Xt(S.meshes)),de(ie,J()),en(T);let E=new Map(T.flatMap(t=>t.object?.kind==="building"?[[t.object.id,t.object]]:[]));for(let{buildingId:t,heightMm:u}of f){if(!E.has(t))throw new Error(`the height table names site building ${t}, which the site model does not have`);Ge.set(t,u)}Ue(T);let m=S.meshes[0].getHierarchyBoundingVectors(!0),F=P.Center(m.min,m.max),H=Math.max(m.max.x-m.min.x,m.max.z-m.min.z);Xe([m]),ye=!0,W.draw(ie);let N=Z,a=new wn("camera",Math.PI/2,Math.PI/3.2,H*Wt,F.clone(),i),we=(t,u)=>St(t,u,a.fov,e.clientWidth/e.clientHeight),Pe=()=>we(H*Wt,H);a.radius=Pe(),a.lowerRadiusLimit=Vn,a.upperBetaLimit=Math.PI/2.05,a.wheelDeltaPercentage=.02,a.attachControl(e,!0);let le=a.inputs.attached.pointers;le instanceof Pn&&(le.useNaturalPinchZoom=!0,le.multiTouchPanAndZoom=!1,le.multiTouchPanning=!1);let Q=new Map,ee=null,Ze=()=>{let[t,u]=[...Q.values()],{origin:b,direction:y}=i.createPickingRay((t.x+u.x)/2,(t.y+u.y)/2,null,a);return Lt(b,y,A.position.y,a.radius*Nt)},Ke=t=>{t.pointerType==="touch"&&(Q.set(t.pointerId,{x:t.offsetX,y:t.offsetY}),t.type==="pointerdown"&&Q.size===2&&(ee=Ze()))},qe=t=>{Q.delete(t.pointerId)};e.addEventListener("pointerdown",Ke,{signal:U.signal}),e.addEventListener("pointermove",Ke,{signal:U.signal}),e.addEventListener("pointerup",qe,{signal:U.signal}),e.addEventListener("pointercancel",qe,{signal:U.signal}),e.addEventListener("touchend",t=>t.preventDefault(),{passive:!1,signal:U.signal});let tn=()=>{if(Q.size!==2){ee=null;return}let t=Ze();if(t===null)return;if(ee===null){ee=t;return}let{x:u,y:b,z:y}=Dt(a.target,ee,t,F,H);a.target.copyFromFloats(u,b,y)};a.onProjectionMatrixChangedObservable.add(()=>ct(a.getProjectionMatrix(),N)),i.onBeforeRenderObservable.add(()=>{a.minZ=Math.max(Jn,a.radius*qn);let t=lt(N,Z,c.getDeltaTime()/1e3);(t.top!==N.top||t.bottom!==N.bottom)&&(N=t,a.getProjectionMatrix(!0));let u=v.fadeLines?Pt(a.radius,H):0;if(u!==pe&&(pe=u,He()),v.edges){let b=It(a.radius,e.clientHeight);for(let y of T)y.mesh.edgesWidth=b}W.scale(a.getViewMatrix(),a.fov,e.clientHeight*(1-N.top-N.bottom),a.minZ)});let Ie=(t,u,b)=>{$.CreateAndStartAnimation("move-target",a,"target",60,Ce,a.target.clone(),t,$.ANIMATIONLOOPMODE_CONSTANT),$.CreateAndStartAnimation("move-radius",a,"radius",60,Ce,a.radius,u,$.ANIMATIONLOOPMODE_CONSTANT),b!==null&&$.CreateAndStartAnimation("move-beta",a,"beta",60,Ce,a.beta,b,$.ANIMATIONLOOPMODE_CONSTANT)},Je=null,Qe=null,et=t=>{let{isolated:u,selectedMeshes:b}=Se(t),y=t.selection,O=u===null?null:u.key;if(O!==Je)if(O===null)Ie(F,Pe(),null);else{let w=fe.get(O);if(w!==void 0){let{min:B,max:j}=w.getHierarchyBoundingVectors(!0),V=P.Distance(B,j);Ie(P.Center(B,j),we(V*zn,V),null)}}else if(y!==null&&y!==Qe&&y.focus&&b.length>0){let{min:w,max:B}=Ut(b.map(V=>V.getHierarchyBoundingVectors(!0))),j=P.Distance(w,B);Ie(P.Center(w,B),we(Math.max(j*Gn,Wn),j),Tt(a.beta))}Je=O,Qe=y,se=!0,q()},nn=(t,u)=>{let b=W.at(i.pointerX,i.pointerY);if(b!==null)return b;let y=t===null?void 0:T.find(O=>O.mesh===t);if(y!==void 0||!u)return y===void 0?null:y.object;for(let{x:O,y:w}of Rt(i.pointerX,i.pointerY)){let B=W.at(O,w);if(B!==null)return B;let{pickedMesh:j}=i.pick(O,w),V=j===null?void 0:T.find(rn=>rn.mesh===j);if(V!==void 0)return V.object}return null};i.onPointerObservable.add(t=>{if(t.type!==En.POINTERTAP)return;let u="pointerType"in t.event&&t.event.pointerType==="touch";l(nn(t.pickInfo?.hit===!0?t.pickInfo.pickedMesh:null,u))});let Ee=[],Oe=(t,u)=>{if(u===void 0)return;let b=io(u.mesh);if(b===null)throw new Error(`the site model's box ${u.mesh.name} (${t}) has no PBR base colour`);Ee.push({label:t,color:b})},ce=T.filter(re);Oe("\u540D\u524D\u306E\u3042\u308B\u5EFA\u5C4B",ce.find(t=>t.object?.kind==="building"&&t.object.name!=="")),Oe("\u540D\u524D\u306E\u7121\u3044\u5EFA\u5C4B",ce.find(t=>t.object?.kind==="building"&&t.object.name==="")),Oe("\u30BF\u30F3\u30AF",ce.find(t=>t.part.role==="tank")),ae(),he=()=>i.render(!1),c.runRenderLoop(()=>{a.panningSensibility=_t(a.radius,a.fov,e.clientHeight*(1-N.top-N.bottom),a.panningInertia),a.upperRadiusLimit=Pe()*Bn,a.maxZ=a.upperRadiusLimit*jn,a.update(),tn();let t=N.top!==Z.top||N.bottom!==Z.bottom,u=[a.alpha,a.beta,a.radius,a.target.x,a.target.y,a.target.z];I.shouldDraw(u,t||i.animatables.length>0)&&(e.dataset.cameraPose=u.join(" "),K=K||i.isReady(),K&&se&&(se=!1,D.resetRefreshCounter()),he(),e.dataset.markerPositions=JSON.stringify(W.positions(i.getTransformMatrix(),e.clientWidth,e.clientHeight)),I.drawn(K))}),g({objects:J(),legend:Ee,complete:!1,show:et});let[tt,...nt]=await Promise.all([De(o.linesUrl,i,{pluginExtension:".glb"}),...s.map(t=>De(t.glbUrl,i,{pluginExtension:".glb"}))]);if(i.isDisposed)return;let te=Xt(tt.meshes);s.forEach((t,u)=>{let b=E.get(t.buildingId);if(b===void 0)throw new Error(`detailed building ${t.key} replaces site building ${t.buildingId}, which the site model does not have`);let y=new Fe(`detail-${t.key}`,i);y.rotation.y=t.placement.rotationY,y.position=new P(...t.placement.position),nt[u].meshes[0].parent=y,fe.set(t.key,y),ge.set(t.buildingId,t);for(let O of nt[u].meshes){let w=ne(O,Ae);if(w===null)continue;if(w.floor===null)throw new Error(`a ${w.role} of detailed building ${t.key} names no floor`);let B=w.role==="slab"||w.role==="plate"?b:ne(O,j=>Re(j,t.key));te.push({mesh:O,part:w,detail:t,object:B})}});for(let t of te)switch(t.part.role){case"lines":t.mesh.material=x;break;case"text":t.mesh.material=M;break;case"slab":t.mesh.material=_,C.excludedMeshes.push(t.mesh),G.includedOnlyMeshes.push(t.mesh);break;case"plate":t.mesh.material=z;break;default:break}T.push(...te),de(ie,J()),Ue(te);let ot=[...fe.values()].map(t=>t.getHierarchyBoundingVectors(!0));Xe([m,tt.meshes[0].getHierarchyBoundingVectors(!0),...ot]);let on=t=>{let{minimumWorld:u,maximumWorld:b}=t.getBoundingInfo().boundingBox;return{minX:u.x,maxX:b.x,minZ:u.z,maxZ:b.z}};s.forEach((t,u)=>{let{min:b,max:y}=ot[u],O=ce.filter(w=>w.object?.id!==t.buildingId).map(w=>({id:String(w.mesh.uniqueId),footprint:on(w.mesh)}));We.set(t.key,new Set(mt({minX:b.x,maxX:y.x,minZ:b.z,maxZ:y.z},O)))});for(let t of te)t.detail!==null&&t.object!==null&&ze.set(t.object.id,t.detail);be=s,ae(),g({objects:J(),legend:Ee,complete:!0,show:et})},paint:Be,inset:o=>{Z=at(o)},options:o=>{v=o,ae()},markers:o=>{de(st(o),J()),ie=o,Me.removeAllMeshes(),ye&&(W.draw(o),Ve()),Se(xe),q()},close:()=>{$e.disconnect(),document.removeEventListener("visibilitychange",Ye),U.abort(),c.stopRenderLoop(),i.dispose(),c.dispose()}}};export{Vo as openPlantSceneView};
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@aiquants/plant-scene",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "React 3D view of a plant site drawn with Babylon.js: site massing and drawing lines from GLB, detailed buildings by floor, site markers with name tags, an orbit camera moved by fingers, picking and display options.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "CHANGELOG.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "babylonjs",
22
+ "glb",
23
+ "gltf",
24
+ "3d",
25
+ "plant",
26
+ "react",
27
+ "typescript"
28
+ ],
29
+ "author": "AI Quants",
30
+ "license": "MIT",
31
+ "peerDependencies": {
32
+ "@babylonjs/core": "^9.31.0",
33
+ "@babylonjs/loaders": "^9.31.0",
34
+ "react": ">=19.2.0",
35
+ "zod": "^3.25.0"
36
+ },
37
+ "devDependencies": {
38
+ "@babylonjs/core": "^9.31.0",
39
+ "@babylonjs/loaders": "^9.31.0",
40
+ "@testing-library/react": "^16.3.2",
41
+ "@types/node": "^25.9.1",
42
+ "@types/react": "^19.2.7",
43
+ "@types/react-dom": "^19.2.3",
44
+ "jsdom": "^27.4.0",
45
+ "react": "^19.2.7",
46
+ "react-dom": "^19.2.7",
47
+ "rimraf": "^6.1.2",
48
+ "tsup": "^8.5.1",
49
+ "typescript": "^5.9.3",
50
+ "vitest": "^4.1.10",
51
+ "zod": "^3.25.76"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "scripts": {
57
+ "build": "pnpm -w run workspace:build \"$PNPM_SCRIPT_SRC_DIR\"",
58
+ "prebuild:self": "pnpm -w run workspace:sync \"$PNPM_SCRIPT_SRC_DIR\"",
59
+ "build:self": "tsup && node ../../.config/scripts/strip-dts-comments.mjs dist && node scripts/check-dist.mjs dist",
60
+ "typecheck": "tsc --noEmit",
61
+ "clean": "rimraf dist",
62
+ "test": "vitest run",
63
+ "test:scripts": "node --test scripts/check-dist.test.mjs",
64
+ "check": "biome check src/ scripts/",
65
+ "check:fix": "biome check --write src/ scripts/",
66
+ "check:md": "cd ../.. && node_modules/.bin/markdownlint-cli2 \"packages/plant-scene/**/*.md\"",
67
+ "verify": "node_modules/.bin/tsc --noEmit && node_modules/.bin/tsc --noEmit -p tsconfig.spec.json && ../../node_modules/.bin/biome check src/ scripts/ && pnpm run check:md && node_modules/.bin/vitest run && node --test scripts/check-dist.test.mjs",
68
+ "publish:patch": "pnpm run verify && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version patch --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
69
+ "publish:minor": "pnpm run verify && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version minor --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
70
+ "publish:major": "pnpm run verify && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version major --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks"
71
+ }
6
72
  }