@vulcan-energy/mcp-helper 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/bin/vulcan-mcp-helper.js +36 -34
- package/dist/hem-target-runtime/browser-adapter.mjs +49 -10
- package/dist/hem-target-runtime/host.mjs +124 -32
- package/dist/hem-target-runtime/preparation.mjs +19241 -11263
- package/dist/hem-target-runtime/python-worker.mjs +3192 -689
- package/dist/hem-target-runtime/release-manifests.mjs +73 -29
- package/dist/hem-target-runtime/rust-worker.mjs +2939 -51
- package/dist/server.js +35 -33
- package/package.json +1 -1
- package/wasm/wasm_version.json +9 -9
- package/wasm/wasm_wrapper.js +6 -6
- package/wasm/wasm_wrapper_bg.wasm +0 -0
|
@@ -16,445 +16,2627 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode,
|
|
19
|
+
var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
20
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
21
|
// file that has been converted to a CommonJS file using a Babel-
|
|
22
22
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
23
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
|
|
25
25
|
mod
|
|
26
26
|
));
|
|
27
27
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
28
28
|
|
|
29
|
-
// ../node_modules/
|
|
30
|
-
var
|
|
31
|
-
"../node_modules/
|
|
32
|
-
((
|
|
33
|
-
"
|
|
34
|
-
})(exports, function
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
29
|
+
// ../node_modules/polygon-clipping/dist/polygon-clipping.umd.js
|
|
30
|
+
var require_polygon_clipping_umd = __commonJS({
|
|
31
|
+
"../node_modules/polygon-clipping/dist/polygon-clipping.umd.js"(exports, module) {
|
|
32
|
+
(function(global, factory) {
|
|
33
|
+
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.polygonClipping = factory());
|
|
34
|
+
})(exports, function() {
|
|
35
|
+
"use strict";
|
|
36
|
+
function __generator(thisArg, body) {
|
|
37
|
+
var _ = {
|
|
38
|
+
label: 0,
|
|
39
|
+
sent: function() {
|
|
40
|
+
if (t[0] & 1) throw t[1];
|
|
41
|
+
return t[1];
|
|
42
|
+
},
|
|
43
|
+
trys: [],
|
|
44
|
+
ops: []
|
|
45
|
+
}, f, y, t, g;
|
|
46
|
+
return g = {
|
|
47
|
+
next: verb(0),
|
|
48
|
+
"throw": verb(1),
|
|
49
|
+
"return": verb(2)
|
|
50
|
+
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
51
|
+
return this;
|
|
52
|
+
}), g;
|
|
53
|
+
function verb(n) {
|
|
54
|
+
return function(v) {
|
|
55
|
+
return step([n, v]);
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function step(op) {
|
|
59
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
60
|
+
while (_) try {
|
|
61
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
62
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
63
|
+
switch (op[0]) {
|
|
64
|
+
case 0:
|
|
65
|
+
case 1:
|
|
66
|
+
t = op;
|
|
67
|
+
break;
|
|
68
|
+
case 4:
|
|
69
|
+
_.label++;
|
|
70
|
+
return {
|
|
71
|
+
value: op[1],
|
|
72
|
+
done: false
|
|
73
|
+
};
|
|
74
|
+
case 5:
|
|
75
|
+
_.label++;
|
|
76
|
+
y = op[1];
|
|
77
|
+
op = [0];
|
|
78
|
+
continue;
|
|
79
|
+
case 7:
|
|
80
|
+
op = _.ops.pop();
|
|
81
|
+
_.trys.pop();
|
|
82
|
+
continue;
|
|
83
|
+
default:
|
|
84
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
85
|
+
_ = 0;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
89
|
+
_.label = op[1];
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
if (op[0] === 6 && _.label < t[1]) {
|
|
93
|
+
_.label = t[1];
|
|
94
|
+
t = op;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
if (t && _.label < t[2]) {
|
|
98
|
+
_.label = t[2];
|
|
99
|
+
_.ops.push(op);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
if (t[2]) _.ops.pop();
|
|
103
|
+
_.trys.pop();
|
|
104
|
+
continue;
|
|
56
105
|
}
|
|
57
|
-
|
|
106
|
+
op = body.call(thisArg, _);
|
|
107
|
+
} catch (e) {
|
|
108
|
+
op = [6, e];
|
|
109
|
+
y = 0;
|
|
110
|
+
} finally {
|
|
111
|
+
f = t = 0;
|
|
58
112
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
113
|
+
if (op[0] & 5) throw op[1];
|
|
114
|
+
return {
|
|
115
|
+
value: op[0] ? op[1] : void 0,
|
|
116
|
+
done: true
|
|
117
|
+
};
|
|
118
|
+
}
|
|
63
119
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
120
|
+
var Node = (
|
|
121
|
+
/** @class */
|
|
122
|
+
/* @__PURE__ */ function() {
|
|
123
|
+
function Node2(key, data) {
|
|
124
|
+
this.next = null;
|
|
125
|
+
this.key = key;
|
|
126
|
+
this.data = data;
|
|
127
|
+
this.left = null;
|
|
128
|
+
this.right = null;
|
|
129
|
+
}
|
|
130
|
+
return Node2;
|
|
131
|
+
}()
|
|
132
|
+
);
|
|
133
|
+
function DEFAULT_COMPARE(a, b) {
|
|
134
|
+
return a > b ? 1 : a < b ? -1 : 0;
|
|
135
|
+
}
|
|
136
|
+
function splay(i, t, comparator) {
|
|
137
|
+
var N = new Node(null, null);
|
|
138
|
+
var l = N;
|
|
139
|
+
var r = N;
|
|
140
|
+
while (true) {
|
|
141
|
+
var cmp2 = comparator(i, t.key);
|
|
142
|
+
if (cmp2 < 0) {
|
|
143
|
+
if (t.left === null) break;
|
|
144
|
+
if (comparator(i, t.left.key) < 0) {
|
|
145
|
+
var y = t.left;
|
|
146
|
+
t.left = y.right;
|
|
147
|
+
y.right = t;
|
|
148
|
+
t = y;
|
|
149
|
+
if (t.left === null) break;
|
|
78
150
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
151
|
+
r.left = t;
|
|
152
|
+
r = t;
|
|
153
|
+
t = t.left;
|
|
154
|
+
} else if (cmp2 > 0) {
|
|
155
|
+
if (t.right === null) break;
|
|
156
|
+
if (comparator(i, t.right.key) > 0) {
|
|
157
|
+
var y = t.right;
|
|
158
|
+
t.right = y.left;
|
|
159
|
+
y.left = t;
|
|
160
|
+
t = y;
|
|
161
|
+
if (t.right === null) break;
|
|
85
162
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
163
|
+
l.right = t;
|
|
164
|
+
l = t;
|
|
165
|
+
t = t.right;
|
|
166
|
+
} else break;
|
|
167
|
+
}
|
|
168
|
+
l.right = t.left;
|
|
169
|
+
r.left = t.right;
|
|
170
|
+
t.left = N.right;
|
|
171
|
+
t.right = N.left;
|
|
172
|
+
return t;
|
|
94
173
|
}
|
|
95
|
-
function
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
|
|
174
|
+
function insert(i, data, t, comparator) {
|
|
175
|
+
var node = new Node(i, data);
|
|
176
|
+
if (t === null) {
|
|
177
|
+
node.left = node.right = null;
|
|
178
|
+
return node;
|
|
179
|
+
}
|
|
180
|
+
t = splay(i, t, comparator);
|
|
181
|
+
var cmp2 = comparator(i, t.key);
|
|
182
|
+
if (cmp2 < 0) {
|
|
183
|
+
node.left = t.left;
|
|
184
|
+
node.right = t;
|
|
185
|
+
t.left = null;
|
|
186
|
+
} else if (cmp2 >= 0) {
|
|
187
|
+
node.right = t.right;
|
|
188
|
+
node.left = t;
|
|
189
|
+
t.right = null;
|
|
190
|
+
}
|
|
191
|
+
return node;
|
|
110
192
|
}
|
|
111
|
-
function
|
|
112
|
-
var
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
var
|
|
117
|
-
if (
|
|
193
|
+
function split(key, v, comparator) {
|
|
194
|
+
var left = null;
|
|
195
|
+
var right = null;
|
|
196
|
+
if (v) {
|
|
197
|
+
v = splay(key, v, comparator);
|
|
198
|
+
var cmp2 = comparator(v.key, key);
|
|
199
|
+
if (cmp2 === 0) {
|
|
200
|
+
left = v.left;
|
|
201
|
+
right = v.right;
|
|
202
|
+
} else if (cmp2 < 0) {
|
|
203
|
+
right = v.right;
|
|
204
|
+
v.right = null;
|
|
205
|
+
left = v;
|
|
206
|
+
} else {
|
|
207
|
+
left = v.left;
|
|
208
|
+
v.left = null;
|
|
209
|
+
right = v;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
left,
|
|
214
|
+
right
|
|
118
215
|
};
|
|
119
216
|
}
|
|
120
|
-
function
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
u.prototype.resume.apply(this, arguments), this._input.resume();
|
|
127
|
-
}, this.stream = function(e2) {
|
|
128
|
-
this._input = e2, this._input.on("data", this._streamData), this._input.on("end", this._streamEnd), this._input.on("error", this._streamError);
|
|
129
|
-
}, this._checkIsFinished = function() {
|
|
130
|
-
r2 && 1 === t.length && (this._finished = true);
|
|
131
|
-
}, this._nextChunk = function() {
|
|
132
|
-
this._checkIsFinished(), t.length ? this.parseChunk(t.shift()) : i2 = true;
|
|
133
|
-
}, this._streamData = y(function(e2) {
|
|
134
|
-
try {
|
|
135
|
-
t.push("string" == typeof e2 ? e2 : e2.toString(this._config.encoding)), i2 && (i2 = false, this._checkIsFinished(), this.parseChunk(t.shift()));
|
|
136
|
-
} catch (e3) {
|
|
137
|
-
this._streamError(e3);
|
|
138
|
-
}
|
|
139
|
-
}, this), this._streamError = y(function(e2) {
|
|
140
|
-
this._streamCleanUp(), this._sendError(e2);
|
|
141
|
-
}, this), this._streamEnd = y(function() {
|
|
142
|
-
this._streamCleanUp(), r2 = true, this._streamData("");
|
|
143
|
-
}, this), this._streamCleanUp = y(function() {
|
|
144
|
-
this._input.removeListener("data", this._streamData), this._input.removeListener("end", this._streamEnd), this._input.removeListener("error", this._streamError);
|
|
145
|
-
}, this);
|
|
217
|
+
function merge(left, right, comparator) {
|
|
218
|
+
if (right === null) return left;
|
|
219
|
+
if (left === null) return right;
|
|
220
|
+
right = splay(left.key, right, comparator);
|
|
221
|
+
right.left = left;
|
|
222
|
+
return right;
|
|
146
223
|
}
|
|
147
|
-
function
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
for (var e2 = 0; _2() && e2 < p2.data.length; e2++) p2.data[e2].forEach(t3);
|
|
162
|
-
p2.data.splice(0, 1);
|
|
163
|
-
} else p2.data.forEach(t3);
|
|
164
|
-
}
|
|
165
|
-
function i3(e3, t3) {
|
|
166
|
-
for (var i4 = m2.header ? {} : [], r4 = 0; r4 < e3.length; r4++) {
|
|
167
|
-
var n3 = r4, s3 = e3[r4], s3 = ((e4, t4) => ((e5) => (m2.dynamicTypingFunction && void 0 === m2.dynamicTyping[e5] && (m2.dynamicTyping[e5] = m2.dynamicTypingFunction(e5)), true === (m2.dynamicTyping[e5] || m2.dynamicTyping)))(e4) ? "true" === t4 || "TRUE" === t4 || "false" !== t4 && "FALSE" !== t4 && (((e5) => {
|
|
168
|
-
if (u2.test(e5)) {
|
|
169
|
-
e5 = parseFloat(e5);
|
|
170
|
-
if (h2 < e5 && e5 < o2) return 1;
|
|
171
|
-
}
|
|
172
|
-
})(t4) ? parseFloat(t4) : d2.test(t4) ? new Date(t4) : "" === t4 ? null : t4) : t4)(n3 = m2.header ? r4 >= c2.length ? "__parsed_extra" : c2[r4] : n3, s3 = m2.transform ? m2.transform(s3, n3) : s3);
|
|
173
|
-
"__parsed_extra" === n3 ? (i4[n3] = i4[n3] || [], i4[n3].push(s3)) : i4[n3] = s3;
|
|
224
|
+
function printRow(root, prefix, isTail, out, printNode) {
|
|
225
|
+
if (root) {
|
|
226
|
+
out("" + prefix + (isTail ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ") + printNode(root) + "\n");
|
|
227
|
+
var indent = prefix + (isTail ? " " : "\u2502 ");
|
|
228
|
+
if (root.left) printRow(root.left, indent, false, out, printNode);
|
|
229
|
+
if (root.right) printRow(root.right, indent, true, out, printNode);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
var Tree = (
|
|
233
|
+
/** @class */
|
|
234
|
+
function() {
|
|
235
|
+
function Tree2(comparator) {
|
|
236
|
+
if (comparator === void 0) {
|
|
237
|
+
comparator = DEFAULT_COMPARE;
|
|
174
238
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}), this.parse = function(e2, t2, i3) {
|
|
190
|
-
var r3 = m2.quoteChar || '"', r3 = (m2.newline || (m2.newline = this.guessLineEndings(e2, r3)), a2 = false, m2.delimiter ? U(m2.delimiter) && (m2.delimiter = m2.delimiter(e2), p2.meta.delimiter = m2.delimiter) : ((r3 = ((e3, t3, i4, r4, n3) => {
|
|
191
|
-
var s3, a3, o3, h3;
|
|
192
|
-
n3 = n3 || [",", " ", "|", ";", v.RECORD_SEP, v.UNIT_SEP];
|
|
193
|
-
for (var u3 = 0; u3 < n3.length; u3++) {
|
|
194
|
-
for (var d3, f3 = n3[u3], l3 = 0, c3 = 0, p3 = 0, g3 = (o3 = void 0, new E({ comments: r4, delimiter: f3, newline: t3, preview: 10 }).parse(e3)), _3 = 0; _3 < g3.data.length; _3++) i4 && y2(g3.data[_3]) ? p3++ : (d3 = g3.data[_3].length, c3 += d3, void 0 === o3 ? o3 = d3 : 0 < d3 && (l3 += Math.abs(d3 - o3), o3 = d3));
|
|
195
|
-
0 < g3.data.length && (c3 /= g3.data.length - p3), (void 0 === a3 || l3 <= a3) && (void 0 === h3 || h3 < c3) && 1.99 < c3 && (a3 = l3, s3 = f3, h3 = c3);
|
|
239
|
+
this._root = null;
|
|
240
|
+
this._size = 0;
|
|
241
|
+
this._comparator = comparator;
|
|
242
|
+
}
|
|
243
|
+
Tree2.prototype.insert = function(key, data) {
|
|
244
|
+
this._size++;
|
|
245
|
+
return this._root = insert(key, data, this._root, this._comparator);
|
|
246
|
+
};
|
|
247
|
+
Tree2.prototype.add = function(key, data) {
|
|
248
|
+
var node = new Node(key, data);
|
|
249
|
+
if (this._root === null) {
|
|
250
|
+
node.left = node.right = null;
|
|
251
|
+
this._size++;
|
|
252
|
+
this._root = node;
|
|
196
253
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}, this.guessLineEndings = function(e2, t2) {
|
|
211
|
-
e2 = e2.substring(0, 1048576);
|
|
212
|
-
var t2 = new RegExp(P(t2) + "([^]*?)" + P(t2), "gm"), i3 = (e2 = e2.replace(t2, "")).split("\r"), t2 = e2.split("\n"), e2 = 1 < t2.length && t2[0].length < i3[0].length;
|
|
213
|
-
if (1 === i3.length || e2) return "\n";
|
|
214
|
-
for (var r3 = 0, n3 = 0; n3 < i3.length; n3++) "\n" === i3[n3][0] && r3++;
|
|
215
|
-
return r3 >= i3.length / 2 ? "\r\n" : "\r";
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
function P(e) {
|
|
219
|
-
return e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
220
|
-
}
|
|
221
|
-
function E(C) {
|
|
222
|
-
var S = (C = C || {}).delimiter, O = C.newline, x = C.comments, I = C.step, A = C.preview, T = C.fastMode, D = null, L = false, F = null == C.quoteChar ? '"' : C.quoteChar, j = F;
|
|
223
|
-
if (void 0 !== C.escapeChar && (j = C.escapeChar), ("string" != typeof S || -1 < v.BAD_DELIMITERS.indexOf(S)) && (S = ","), x === S) throw new Error("Comment character same as delimiter");
|
|
224
|
-
true === x ? x = "#" : ("string" != typeof x || -1 < v.BAD_DELIMITERS.indexOf(x)) && (x = false), "\n" !== O && "\r" !== O && "\r\n" !== O && (O = "\n");
|
|
225
|
-
var z = 0, M = false;
|
|
226
|
-
this.parse = function(i2, t, r2) {
|
|
227
|
-
if ("string" != typeof i2) throw new Error("Input must be a string");
|
|
228
|
-
var n2 = i2.length, e = S.length, s2 = O.length, a2 = x.length, o2 = U(I), h2 = [], u2 = [], d2 = [], f2 = z = 0;
|
|
229
|
-
if (!i2) return w();
|
|
230
|
-
if (T || false !== T && -1 === i2.indexOf(F)) {
|
|
231
|
-
for (var l2 = i2.split(O), c2 = 0; c2 < l2.length; c2++) {
|
|
232
|
-
if (d2 = l2[c2], z += d2.length, c2 !== l2.length - 1) z += O.length;
|
|
233
|
-
else if (r2) return w();
|
|
234
|
-
if (!x || d2.substring(0, a2) !== x) {
|
|
235
|
-
if (o2) {
|
|
236
|
-
if (h2 = [], k(d2.split(S)), R(), M) return w();
|
|
237
|
-
} else k(d2.split(S));
|
|
238
|
-
if (A && A <= c2) return h2 = h2.slice(0, A), w(true);
|
|
254
|
+
var comparator = this._comparator;
|
|
255
|
+
var t = splay(key, this._root, comparator);
|
|
256
|
+
var cmp2 = comparator(key, t.key);
|
|
257
|
+
if (cmp2 === 0) this._root = t;
|
|
258
|
+
else {
|
|
259
|
+
if (cmp2 < 0) {
|
|
260
|
+
node.left = t.left;
|
|
261
|
+
node.right = t;
|
|
262
|
+
t.left = null;
|
|
263
|
+
} else if (cmp2 > 0) {
|
|
264
|
+
node.right = t.right;
|
|
265
|
+
node.left = t;
|
|
266
|
+
t.right = null;
|
|
239
267
|
}
|
|
268
|
+
this._size++;
|
|
269
|
+
this._root = node;
|
|
240
270
|
}
|
|
241
|
-
return
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
271
|
+
return this._root;
|
|
272
|
+
};
|
|
273
|
+
Tree2.prototype.remove = function(key) {
|
|
274
|
+
this._root = this._remove(key, this._root, this._comparator);
|
|
275
|
+
};
|
|
276
|
+
Tree2.prototype._remove = function(i, t, comparator) {
|
|
277
|
+
var x;
|
|
278
|
+
if (t === null) return null;
|
|
279
|
+
t = splay(i, t, comparator);
|
|
280
|
+
var cmp2 = comparator(i, t.key);
|
|
281
|
+
if (cmp2 === 0) {
|
|
282
|
+
if (t.left === null) {
|
|
283
|
+
x = t.right;
|
|
284
|
+
} else {
|
|
285
|
+
x = splay(i, t.left, comparator);
|
|
286
|
+
x.right = t.right;
|
|
253
287
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
288
|
+
this._size--;
|
|
289
|
+
return x;
|
|
290
|
+
}
|
|
291
|
+
return t;
|
|
292
|
+
};
|
|
293
|
+
Tree2.prototype.pop = function() {
|
|
294
|
+
var node = this._root;
|
|
295
|
+
if (node) {
|
|
296
|
+
while (node.left) node = node.left;
|
|
297
|
+
this._root = splay(node.key, this._root, this._comparator);
|
|
298
|
+
this._root = this._remove(node.key, this._root, this._comparator);
|
|
299
|
+
return {
|
|
300
|
+
key: node.key,
|
|
301
|
+
data: node.data
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
return null;
|
|
305
|
+
};
|
|
306
|
+
Tree2.prototype.findStatic = function(key) {
|
|
307
|
+
var current = this._root;
|
|
308
|
+
var compare = this._comparator;
|
|
309
|
+
while (current) {
|
|
310
|
+
var cmp2 = compare(key, current.key);
|
|
311
|
+
if (cmp2 === 0) return current;
|
|
312
|
+
else if (cmp2 < 0) current = current.left;
|
|
313
|
+
else current = current.right;
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
};
|
|
317
|
+
Tree2.prototype.find = function(key) {
|
|
318
|
+
if (this._root) {
|
|
319
|
+
this._root = splay(key, this._root, this._comparator);
|
|
320
|
+
if (this._comparator(key, this._root.key) !== 0) return null;
|
|
321
|
+
}
|
|
322
|
+
return this._root;
|
|
323
|
+
};
|
|
324
|
+
Tree2.prototype.contains = function(key) {
|
|
325
|
+
var current = this._root;
|
|
326
|
+
var compare = this._comparator;
|
|
327
|
+
while (current) {
|
|
328
|
+
var cmp2 = compare(key, current.key);
|
|
329
|
+
if (cmp2 === 0) return true;
|
|
330
|
+
else if (cmp2 < 0) current = current.left;
|
|
331
|
+
else current = current.right;
|
|
332
|
+
}
|
|
333
|
+
return false;
|
|
334
|
+
};
|
|
335
|
+
Tree2.prototype.forEach = function(visitor, ctx) {
|
|
336
|
+
var current = this._root;
|
|
337
|
+
var Q = [];
|
|
338
|
+
var done = false;
|
|
339
|
+
while (!done) {
|
|
340
|
+
if (current !== null) {
|
|
341
|
+
Q.push(current);
|
|
342
|
+
current = current.left;
|
|
343
|
+
} else {
|
|
344
|
+
if (Q.length !== 0) {
|
|
345
|
+
current = Q.pop();
|
|
346
|
+
visitor.call(ctx, current);
|
|
347
|
+
current = current.right;
|
|
348
|
+
} else done = true;
|
|
259
349
|
}
|
|
260
|
-
u2.push({ type: "Quotes", code: "InvalidQuotes", message: "Trailing quote on quoted field is malformed", row: h2.length, index: z }), m2++;
|
|
261
350
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
}
|
|
286
|
-
function
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
351
|
+
return this;
|
|
352
|
+
};
|
|
353
|
+
Tree2.prototype.range = function(low, high, fn, ctx) {
|
|
354
|
+
var Q = [];
|
|
355
|
+
var compare = this._comparator;
|
|
356
|
+
var node = this._root;
|
|
357
|
+
var cmp2;
|
|
358
|
+
while (Q.length !== 0 || node) {
|
|
359
|
+
if (node) {
|
|
360
|
+
Q.push(node);
|
|
361
|
+
node = node.left;
|
|
362
|
+
} else {
|
|
363
|
+
node = Q.pop();
|
|
364
|
+
cmp2 = compare(node.key, high);
|
|
365
|
+
if (cmp2 > 0) {
|
|
366
|
+
break;
|
|
367
|
+
} else if (compare(node.key, low) >= 0) {
|
|
368
|
+
if (fn.call(ctx, node)) return this;
|
|
369
|
+
}
|
|
370
|
+
node = node.right;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return this;
|
|
374
|
+
};
|
|
375
|
+
Tree2.prototype.keys = function() {
|
|
376
|
+
var keys = [];
|
|
377
|
+
this.forEach(function(_a) {
|
|
378
|
+
var key = _a.key;
|
|
379
|
+
return keys.push(key);
|
|
380
|
+
});
|
|
381
|
+
return keys;
|
|
382
|
+
};
|
|
383
|
+
Tree2.prototype.values = function() {
|
|
384
|
+
var values = [];
|
|
385
|
+
this.forEach(function(_a) {
|
|
386
|
+
var data = _a.data;
|
|
387
|
+
return values.push(data);
|
|
388
|
+
});
|
|
389
|
+
return values;
|
|
390
|
+
};
|
|
391
|
+
Tree2.prototype.min = function() {
|
|
392
|
+
if (this._root) return this.minNode(this._root).key;
|
|
393
|
+
return null;
|
|
394
|
+
};
|
|
395
|
+
Tree2.prototype.max = function() {
|
|
396
|
+
if (this._root) return this.maxNode(this._root).key;
|
|
397
|
+
return null;
|
|
398
|
+
};
|
|
399
|
+
Tree2.prototype.minNode = function(t) {
|
|
400
|
+
if (t === void 0) {
|
|
401
|
+
t = this._root;
|
|
402
|
+
}
|
|
403
|
+
if (t) while (t.left) t = t.left;
|
|
404
|
+
return t;
|
|
405
|
+
};
|
|
406
|
+
Tree2.prototype.maxNode = function(t) {
|
|
407
|
+
if (t === void 0) {
|
|
408
|
+
t = this._root;
|
|
409
|
+
}
|
|
410
|
+
if (t) while (t.right) t = t.right;
|
|
411
|
+
return t;
|
|
412
|
+
};
|
|
413
|
+
Tree2.prototype.at = function(index2) {
|
|
414
|
+
var current = this._root;
|
|
415
|
+
var done = false;
|
|
416
|
+
var i = 0;
|
|
417
|
+
var Q = [];
|
|
418
|
+
while (!done) {
|
|
419
|
+
if (current) {
|
|
420
|
+
Q.push(current);
|
|
421
|
+
current = current.left;
|
|
422
|
+
} else {
|
|
423
|
+
if (Q.length > 0) {
|
|
424
|
+
current = Q.pop();
|
|
425
|
+
if (i === index2) return current;
|
|
426
|
+
i++;
|
|
427
|
+
current = current.right;
|
|
428
|
+
} else done = true;
|
|
298
429
|
}
|
|
299
|
-
n3 && console.warn("Duplicate headers found and renamed."), L = true;
|
|
300
430
|
}
|
|
301
|
-
return
|
|
431
|
+
return null;
|
|
432
|
+
};
|
|
433
|
+
Tree2.prototype.next = function(d) {
|
|
434
|
+
var root = this._root;
|
|
435
|
+
var successor = null;
|
|
436
|
+
if (d.right) {
|
|
437
|
+
successor = d.right;
|
|
438
|
+
while (successor.left) successor = successor.left;
|
|
439
|
+
return successor;
|
|
440
|
+
}
|
|
441
|
+
var comparator = this._comparator;
|
|
442
|
+
while (root) {
|
|
443
|
+
var cmp2 = comparator(d.key, root.key);
|
|
444
|
+
if (cmp2 === 0) break;
|
|
445
|
+
else if (cmp2 < 0) {
|
|
446
|
+
successor = root;
|
|
447
|
+
root = root.left;
|
|
448
|
+
} else root = root.right;
|
|
449
|
+
}
|
|
450
|
+
return successor;
|
|
451
|
+
};
|
|
452
|
+
Tree2.prototype.prev = function(d) {
|
|
453
|
+
var root = this._root;
|
|
454
|
+
var predecessor = null;
|
|
455
|
+
if (d.left !== null) {
|
|
456
|
+
predecessor = d.left;
|
|
457
|
+
while (predecessor.right) predecessor = predecessor.right;
|
|
458
|
+
return predecessor;
|
|
459
|
+
}
|
|
460
|
+
var comparator = this._comparator;
|
|
461
|
+
while (root) {
|
|
462
|
+
var cmp2 = comparator(d.key, root.key);
|
|
463
|
+
if (cmp2 === 0) break;
|
|
464
|
+
else if (cmp2 < 0) root = root.left;
|
|
465
|
+
else {
|
|
466
|
+
predecessor = root;
|
|
467
|
+
root = root.right;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return predecessor;
|
|
471
|
+
};
|
|
472
|
+
Tree2.prototype.clear = function() {
|
|
473
|
+
this._root = null;
|
|
474
|
+
this._size = 0;
|
|
475
|
+
return this;
|
|
476
|
+
};
|
|
477
|
+
Tree2.prototype.toList = function() {
|
|
478
|
+
return toList(this._root);
|
|
479
|
+
};
|
|
480
|
+
Tree2.prototype.load = function(keys, values, presort) {
|
|
481
|
+
if (values === void 0) {
|
|
482
|
+
values = [];
|
|
483
|
+
}
|
|
484
|
+
if (presort === void 0) {
|
|
485
|
+
presort = false;
|
|
486
|
+
}
|
|
487
|
+
var size = keys.length;
|
|
488
|
+
var comparator = this._comparator;
|
|
489
|
+
if (presort) sort(keys, values, 0, size - 1, comparator);
|
|
490
|
+
if (this._root === null) {
|
|
491
|
+
this._root = loadRecursive(keys, values, 0, size);
|
|
492
|
+
this._size = size;
|
|
493
|
+
} else {
|
|
494
|
+
var mergedList = mergeLists(this.toList(), createList(keys, values), comparator);
|
|
495
|
+
size = this._size + size;
|
|
496
|
+
this._root = sortedListToBST({
|
|
497
|
+
head: mergedList
|
|
498
|
+
}, 0, size);
|
|
499
|
+
}
|
|
500
|
+
return this;
|
|
501
|
+
};
|
|
502
|
+
Tree2.prototype.isEmpty = function() {
|
|
503
|
+
return this._root === null;
|
|
504
|
+
};
|
|
505
|
+
Object.defineProperty(Tree2.prototype, "size", {
|
|
506
|
+
get: function() {
|
|
507
|
+
return this._size;
|
|
508
|
+
},
|
|
509
|
+
enumerable: true,
|
|
510
|
+
configurable: true
|
|
511
|
+
});
|
|
512
|
+
Object.defineProperty(Tree2.prototype, "root", {
|
|
513
|
+
get: function() {
|
|
514
|
+
return this._root;
|
|
515
|
+
},
|
|
516
|
+
enumerable: true,
|
|
517
|
+
configurable: true
|
|
518
|
+
});
|
|
519
|
+
Tree2.prototype.toString = function(printNode) {
|
|
520
|
+
if (printNode === void 0) {
|
|
521
|
+
printNode = function(n) {
|
|
522
|
+
return String(n.key);
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
var out = [];
|
|
526
|
+
printRow(this._root, "", true, function(v) {
|
|
527
|
+
return out.push(v);
|
|
528
|
+
}, printNode);
|
|
529
|
+
return out.join("");
|
|
530
|
+
};
|
|
531
|
+
Tree2.prototype.update = function(key, newKey, newData) {
|
|
532
|
+
var comparator = this._comparator;
|
|
533
|
+
var _a = split(key, this._root, comparator), left = _a.left, right = _a.right;
|
|
534
|
+
if (comparator(key, newKey) < 0) {
|
|
535
|
+
right = insert(newKey, newData, right, comparator);
|
|
536
|
+
} else {
|
|
537
|
+
left = insert(newKey, newData, left, comparator);
|
|
538
|
+
}
|
|
539
|
+
this._root = merge(left, right, comparator);
|
|
540
|
+
};
|
|
541
|
+
Tree2.prototype.split = function(key) {
|
|
542
|
+
return split(key, this._root, this._comparator);
|
|
543
|
+
};
|
|
544
|
+
Tree2.prototype[Symbol.iterator] = function() {
|
|
545
|
+
var current, Q, done;
|
|
546
|
+
return __generator(this, function(_a) {
|
|
547
|
+
switch (_a.label) {
|
|
548
|
+
case 0:
|
|
549
|
+
current = this._root;
|
|
550
|
+
Q = [];
|
|
551
|
+
done = false;
|
|
552
|
+
_a.label = 1;
|
|
553
|
+
case 1:
|
|
554
|
+
if (!!done) return [3, 6];
|
|
555
|
+
if (!(current !== null)) return [3, 2];
|
|
556
|
+
Q.push(current);
|
|
557
|
+
current = current.left;
|
|
558
|
+
return [3, 5];
|
|
559
|
+
case 2:
|
|
560
|
+
if (!(Q.length !== 0)) return [3, 4];
|
|
561
|
+
current = Q.pop();
|
|
562
|
+
return [4, current];
|
|
563
|
+
case 3:
|
|
564
|
+
_a.sent();
|
|
565
|
+
current = current.right;
|
|
566
|
+
return [3, 5];
|
|
567
|
+
case 4:
|
|
568
|
+
done = true;
|
|
569
|
+
_a.label = 5;
|
|
570
|
+
case 5:
|
|
571
|
+
return [3, 1];
|
|
572
|
+
case 6:
|
|
573
|
+
return [
|
|
574
|
+
2
|
|
575
|
+
/*return*/
|
|
576
|
+
];
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
};
|
|
580
|
+
return Tree2;
|
|
581
|
+
}()
|
|
582
|
+
);
|
|
583
|
+
function loadRecursive(keys, values, start, end) {
|
|
584
|
+
var size = end - start;
|
|
585
|
+
if (size > 0) {
|
|
586
|
+
var middle = start + Math.floor(size / 2);
|
|
587
|
+
var key = keys[middle];
|
|
588
|
+
var data = values[middle];
|
|
589
|
+
var node = new Node(key, data);
|
|
590
|
+
node.left = loadRecursive(keys, values, start, middle);
|
|
591
|
+
node.right = loadRecursive(keys, values, middle + 1, end);
|
|
592
|
+
return node;
|
|
593
|
+
}
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
function createList(keys, values) {
|
|
597
|
+
var head = new Node(null, null);
|
|
598
|
+
var p = head;
|
|
599
|
+
for (var i = 0; i < keys.length; i++) {
|
|
600
|
+
p = p.next = new Node(keys[i], values[i]);
|
|
601
|
+
}
|
|
602
|
+
p.next = null;
|
|
603
|
+
return head.next;
|
|
604
|
+
}
|
|
605
|
+
function toList(root) {
|
|
606
|
+
var current = root;
|
|
607
|
+
var Q = [];
|
|
608
|
+
var done = false;
|
|
609
|
+
var head = new Node(null, null);
|
|
610
|
+
var p = head;
|
|
611
|
+
while (!done) {
|
|
612
|
+
if (current) {
|
|
613
|
+
Q.push(current);
|
|
614
|
+
current = current.left;
|
|
615
|
+
} else {
|
|
616
|
+
if (Q.length > 0) {
|
|
617
|
+
current = p = p.next = Q.pop();
|
|
618
|
+
current = current.right;
|
|
619
|
+
} else done = true;
|
|
302
620
|
}
|
|
303
|
-
|
|
304
|
-
|
|
621
|
+
}
|
|
622
|
+
p.next = null;
|
|
623
|
+
return head.next;
|
|
624
|
+
}
|
|
625
|
+
function sortedListToBST(list, start, end) {
|
|
626
|
+
var size = end - start;
|
|
627
|
+
if (size > 0) {
|
|
628
|
+
var middle = start + Math.floor(size / 2);
|
|
629
|
+
var left = sortedListToBST(list, start, middle);
|
|
630
|
+
var root = list.head;
|
|
631
|
+
root.left = left;
|
|
632
|
+
list.head = list.head.next;
|
|
633
|
+
root.right = sortedListToBST(list, middle + 1, end);
|
|
634
|
+
return root;
|
|
635
|
+
}
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
function mergeLists(l1, l2, compare) {
|
|
639
|
+
var head = new Node(null, null);
|
|
640
|
+
var p = head;
|
|
641
|
+
var p1 = l1;
|
|
642
|
+
var p2 = l2;
|
|
643
|
+
while (p1 !== null && p2 !== null) {
|
|
644
|
+
if (compare(p1.key, p2.key) < 0) {
|
|
645
|
+
p.next = p1;
|
|
646
|
+
p1 = p1.next;
|
|
647
|
+
} else {
|
|
648
|
+
p.next = p2;
|
|
649
|
+
p2 = p2.next;
|
|
650
|
+
}
|
|
651
|
+
p = p.next;
|
|
652
|
+
}
|
|
653
|
+
if (p1 !== null) {
|
|
654
|
+
p.next = p1;
|
|
655
|
+
} else if (p2 !== null) {
|
|
656
|
+
p.next = p2;
|
|
657
|
+
}
|
|
658
|
+
return head.next;
|
|
659
|
+
}
|
|
660
|
+
function sort(keys, values, left, right, compare) {
|
|
661
|
+
if (left >= right) return;
|
|
662
|
+
var pivot = keys[left + right >> 1];
|
|
663
|
+
var i = left - 1;
|
|
664
|
+
var j = right + 1;
|
|
665
|
+
while (true) {
|
|
666
|
+
do
|
|
667
|
+
i++;
|
|
668
|
+
while (compare(keys[i], pivot) < 0);
|
|
669
|
+
do
|
|
670
|
+
j--;
|
|
671
|
+
while (compare(keys[j], pivot) > 0);
|
|
672
|
+
if (i >= j) break;
|
|
673
|
+
var tmp = keys[i];
|
|
674
|
+
keys[i] = keys[j];
|
|
675
|
+
keys[j] = tmp;
|
|
676
|
+
tmp = values[i];
|
|
677
|
+
values[i] = values[j];
|
|
678
|
+
values[j] = tmp;
|
|
679
|
+
}
|
|
680
|
+
sort(keys, values, left, j, compare);
|
|
681
|
+
sort(keys, values, j + 1, right, compare);
|
|
682
|
+
}
|
|
683
|
+
const isInBbox = (bbox, point) => {
|
|
684
|
+
return bbox.ll.x <= point.x && point.x <= bbox.ur.x && bbox.ll.y <= point.y && point.y <= bbox.ur.y;
|
|
685
|
+
};
|
|
686
|
+
const getBboxOverlap = (b1, b2) => {
|
|
687
|
+
if (b2.ur.x < b1.ll.x || b1.ur.x < b2.ll.x || b2.ur.y < b1.ll.y || b1.ur.y < b2.ll.y) return null;
|
|
688
|
+
const lowerX = b1.ll.x < b2.ll.x ? b2.ll.x : b1.ll.x;
|
|
689
|
+
const upperX = b1.ur.x < b2.ur.x ? b1.ur.x : b2.ur.x;
|
|
690
|
+
const lowerY = b1.ll.y < b2.ll.y ? b2.ll.y : b1.ll.y;
|
|
691
|
+
const upperY = b1.ur.y < b2.ur.y ? b1.ur.y : b2.ur.y;
|
|
692
|
+
return {
|
|
693
|
+
ll: {
|
|
694
|
+
x: lowerX,
|
|
695
|
+
y: lowerY
|
|
696
|
+
},
|
|
697
|
+
ur: {
|
|
698
|
+
x: upperX,
|
|
699
|
+
y: upperY
|
|
305
700
|
}
|
|
306
|
-
}, this.abort = function() {
|
|
307
|
-
M = true;
|
|
308
|
-
}, this.getCharIndex = function() {
|
|
309
|
-
return z;
|
|
310
701
|
};
|
|
702
|
+
};
|
|
703
|
+
let epsilon$1 = Number.EPSILON;
|
|
704
|
+
if (epsilon$1 === void 0) epsilon$1 = Math.pow(2, -52);
|
|
705
|
+
const EPSILON_SQ = epsilon$1 * epsilon$1;
|
|
706
|
+
const cmp = (a, b) => {
|
|
707
|
+
if (-epsilon$1 < a && a < epsilon$1) {
|
|
708
|
+
if (-epsilon$1 < b && b < epsilon$1) {
|
|
709
|
+
return 0;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const ab = a - b;
|
|
713
|
+
if (ab * ab < EPSILON_SQ * a * b) {
|
|
714
|
+
return 0;
|
|
715
|
+
}
|
|
716
|
+
return a < b ? -1 : 1;
|
|
717
|
+
};
|
|
718
|
+
class PtRounder {
|
|
719
|
+
constructor() {
|
|
720
|
+
this.reset();
|
|
721
|
+
}
|
|
722
|
+
reset() {
|
|
723
|
+
this.xRounder = new CoordRounder();
|
|
724
|
+
this.yRounder = new CoordRounder();
|
|
725
|
+
}
|
|
726
|
+
round(x, y) {
|
|
727
|
+
return {
|
|
728
|
+
x: this.xRounder.round(x),
|
|
729
|
+
y: this.yRounder.round(y)
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
class CoordRounder {
|
|
734
|
+
constructor() {
|
|
735
|
+
this.tree = new Tree();
|
|
736
|
+
this.round(0);
|
|
737
|
+
}
|
|
738
|
+
// Note: this can rounds input values backwards or forwards.
|
|
739
|
+
// You might ask, why not restrict this to just rounding
|
|
740
|
+
// forwards? Wouldn't that allow left endpoints to always
|
|
741
|
+
// remain left endpoints during splitting (never change to
|
|
742
|
+
// right). No - it wouldn't, because we snap intersections
|
|
743
|
+
// to endpoints (to establish independence from the segment
|
|
744
|
+
// angle for t-intersections).
|
|
745
|
+
round(coord) {
|
|
746
|
+
const node = this.tree.add(coord);
|
|
747
|
+
const prevNode = this.tree.prev(node);
|
|
748
|
+
if (prevNode !== null && cmp(node.key, prevNode.key) === 0) {
|
|
749
|
+
this.tree.remove(coord);
|
|
750
|
+
return prevNode.key;
|
|
751
|
+
}
|
|
752
|
+
const nextNode = this.tree.next(node);
|
|
753
|
+
if (nextNode !== null && cmp(node.key, nextNode.key) === 0) {
|
|
754
|
+
this.tree.remove(coord);
|
|
755
|
+
return nextNode.key;
|
|
756
|
+
}
|
|
757
|
+
return coord;
|
|
758
|
+
}
|
|
311
759
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
760
|
+
const rounder = new PtRounder();
|
|
761
|
+
const epsilon = 11102230246251565e-32;
|
|
762
|
+
const splitter = 134217729;
|
|
763
|
+
const resulterrbound = (3 + 8 * epsilon) * epsilon;
|
|
764
|
+
function sum(elen, e, flen, f, h) {
|
|
765
|
+
let Q, Qnew, hh, bvirt;
|
|
766
|
+
let enow = e[0];
|
|
767
|
+
let fnow = f[0];
|
|
768
|
+
let eindex = 0;
|
|
769
|
+
let findex = 0;
|
|
770
|
+
if (fnow > enow === fnow > -enow) {
|
|
771
|
+
Q = enow;
|
|
772
|
+
enow = e[++eindex];
|
|
773
|
+
} else {
|
|
774
|
+
Q = fnow;
|
|
775
|
+
fnow = f[++findex];
|
|
776
|
+
}
|
|
777
|
+
let hindex = 0;
|
|
778
|
+
if (eindex < elen && findex < flen) {
|
|
779
|
+
if (fnow > enow === fnow > -enow) {
|
|
780
|
+
Qnew = enow + Q;
|
|
781
|
+
hh = Q - (Qnew - enow);
|
|
782
|
+
enow = e[++eindex];
|
|
783
|
+
} else {
|
|
784
|
+
Qnew = fnow + Q;
|
|
785
|
+
hh = Q - (Qnew - fnow);
|
|
786
|
+
fnow = f[++findex];
|
|
787
|
+
}
|
|
788
|
+
Q = Qnew;
|
|
789
|
+
if (hh !== 0) {
|
|
790
|
+
h[hindex++] = hh;
|
|
791
|
+
}
|
|
792
|
+
while (eindex < elen && findex < flen) {
|
|
793
|
+
if (fnow > enow === fnow > -enow) {
|
|
794
|
+
Qnew = Q + enow;
|
|
795
|
+
bvirt = Qnew - Q;
|
|
796
|
+
hh = Q - (Qnew - bvirt) + (enow - bvirt);
|
|
797
|
+
enow = e[++eindex];
|
|
798
|
+
} else {
|
|
799
|
+
Qnew = Q + fnow;
|
|
800
|
+
bvirt = Qnew - Q;
|
|
801
|
+
hh = Q - (Qnew - bvirt) + (fnow - bvirt);
|
|
802
|
+
fnow = f[++findex];
|
|
803
|
+
}
|
|
804
|
+
Q = Qnew;
|
|
805
|
+
if (hh !== 0) {
|
|
806
|
+
h[hindex++] = hh;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
while (eindex < elen) {
|
|
811
|
+
Qnew = Q + enow;
|
|
812
|
+
bvirt = Qnew - Q;
|
|
813
|
+
hh = Q - (Qnew - bvirt) + (enow - bvirt);
|
|
814
|
+
enow = e[++eindex];
|
|
815
|
+
Q = Qnew;
|
|
816
|
+
if (hh !== 0) {
|
|
817
|
+
h[hindex++] = hh;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
while (findex < flen) {
|
|
821
|
+
Qnew = Q + fnow;
|
|
822
|
+
bvirt = Qnew - Q;
|
|
823
|
+
hh = Q - (Qnew - bvirt) + (fnow - bvirt);
|
|
824
|
+
fnow = f[++findex];
|
|
825
|
+
Q = Qnew;
|
|
826
|
+
if (hh !== 0) {
|
|
827
|
+
h[hindex++] = hh;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (Q !== 0 || hindex === 0) {
|
|
831
|
+
h[hindex++] = Q;
|
|
832
|
+
}
|
|
833
|
+
return hindex;
|
|
834
|
+
}
|
|
835
|
+
function estimate(elen, e) {
|
|
836
|
+
let Q = e[0];
|
|
837
|
+
for (let i = 1; i < elen; i++) Q += e[i];
|
|
838
|
+
return Q;
|
|
325
839
|
}
|
|
326
|
-
function
|
|
327
|
-
|
|
328
|
-
U(i2.userComplete) && i2.userComplete(t), i2.terminate(), delete o[e];
|
|
840
|
+
function vec(n) {
|
|
841
|
+
return new Float64Array(n);
|
|
329
842
|
}
|
|
330
|
-
|
|
331
|
-
|
|
843
|
+
const ccwerrboundA = (3 + 16 * epsilon) * epsilon;
|
|
844
|
+
const ccwerrboundB = (2 + 12 * epsilon) * epsilon;
|
|
845
|
+
const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon;
|
|
846
|
+
const B = vec(4);
|
|
847
|
+
const C1 = vec(8);
|
|
848
|
+
const C2 = vec(12);
|
|
849
|
+
const D = vec(16);
|
|
850
|
+
const u = vec(4);
|
|
851
|
+
function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) {
|
|
852
|
+
let acxtail, acytail, bcxtail, bcytail;
|
|
853
|
+
let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3;
|
|
854
|
+
const acx = ax - cx;
|
|
855
|
+
const bcx = bx - cx;
|
|
856
|
+
const acy = ay - cy;
|
|
857
|
+
const bcy = by - cy;
|
|
858
|
+
s1 = acx * bcy;
|
|
859
|
+
c = splitter * acx;
|
|
860
|
+
ahi = c - (c - acx);
|
|
861
|
+
alo = acx - ahi;
|
|
862
|
+
c = splitter * bcy;
|
|
863
|
+
bhi = c - (c - bcy);
|
|
864
|
+
blo = bcy - bhi;
|
|
865
|
+
s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
866
|
+
t1 = acy * bcx;
|
|
867
|
+
c = splitter * acy;
|
|
868
|
+
ahi = c - (c - acy);
|
|
869
|
+
alo = acy - ahi;
|
|
870
|
+
c = splitter * bcx;
|
|
871
|
+
bhi = c - (c - bcx);
|
|
872
|
+
blo = bcx - bhi;
|
|
873
|
+
t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
874
|
+
_i = s0 - t0;
|
|
875
|
+
bvirt = s0 - _i;
|
|
876
|
+
B[0] = s0 - (_i + bvirt) + (bvirt - t0);
|
|
877
|
+
_j = s1 + _i;
|
|
878
|
+
bvirt = _j - s1;
|
|
879
|
+
_0 = s1 - (_j - bvirt) + (_i - bvirt);
|
|
880
|
+
_i = _0 - t1;
|
|
881
|
+
bvirt = _0 - _i;
|
|
882
|
+
B[1] = _0 - (_i + bvirt) + (bvirt - t1);
|
|
883
|
+
u3 = _j + _i;
|
|
884
|
+
bvirt = u3 - _j;
|
|
885
|
+
B[2] = _j - (u3 - bvirt) + (_i - bvirt);
|
|
886
|
+
B[3] = u3;
|
|
887
|
+
let det = estimate(4, B);
|
|
888
|
+
let errbound = ccwerrboundB * detsum;
|
|
889
|
+
if (det >= errbound || -det >= errbound) {
|
|
890
|
+
return det;
|
|
891
|
+
}
|
|
892
|
+
bvirt = ax - acx;
|
|
893
|
+
acxtail = ax - (acx + bvirt) + (bvirt - cx);
|
|
894
|
+
bvirt = bx - bcx;
|
|
895
|
+
bcxtail = bx - (bcx + bvirt) + (bvirt - cx);
|
|
896
|
+
bvirt = ay - acy;
|
|
897
|
+
acytail = ay - (acy + bvirt) + (bvirt - cy);
|
|
898
|
+
bvirt = by - bcy;
|
|
899
|
+
bcytail = by - (bcy + bvirt) + (bvirt - cy);
|
|
900
|
+
if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) {
|
|
901
|
+
return det;
|
|
902
|
+
}
|
|
903
|
+
errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det);
|
|
904
|
+
det += acx * bcytail + bcy * acxtail - (acy * bcxtail + bcx * acytail);
|
|
905
|
+
if (det >= errbound || -det >= errbound) return det;
|
|
906
|
+
s1 = acxtail * bcy;
|
|
907
|
+
c = splitter * acxtail;
|
|
908
|
+
ahi = c - (c - acxtail);
|
|
909
|
+
alo = acxtail - ahi;
|
|
910
|
+
c = splitter * bcy;
|
|
911
|
+
bhi = c - (c - bcy);
|
|
912
|
+
blo = bcy - bhi;
|
|
913
|
+
s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
914
|
+
t1 = acytail * bcx;
|
|
915
|
+
c = splitter * acytail;
|
|
916
|
+
ahi = c - (c - acytail);
|
|
917
|
+
alo = acytail - ahi;
|
|
918
|
+
c = splitter * bcx;
|
|
919
|
+
bhi = c - (c - bcx);
|
|
920
|
+
blo = bcx - bhi;
|
|
921
|
+
t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
922
|
+
_i = s0 - t0;
|
|
923
|
+
bvirt = s0 - _i;
|
|
924
|
+
u[0] = s0 - (_i + bvirt) + (bvirt - t0);
|
|
925
|
+
_j = s1 + _i;
|
|
926
|
+
bvirt = _j - s1;
|
|
927
|
+
_0 = s1 - (_j - bvirt) + (_i - bvirt);
|
|
928
|
+
_i = _0 - t1;
|
|
929
|
+
bvirt = _0 - _i;
|
|
930
|
+
u[1] = _0 - (_i + bvirt) + (bvirt - t1);
|
|
931
|
+
u3 = _j + _i;
|
|
932
|
+
bvirt = u3 - _j;
|
|
933
|
+
u[2] = _j - (u3 - bvirt) + (_i - bvirt);
|
|
934
|
+
u[3] = u3;
|
|
935
|
+
const C1len = sum(4, B, 4, u, C1);
|
|
936
|
+
s1 = acx * bcytail;
|
|
937
|
+
c = splitter * acx;
|
|
938
|
+
ahi = c - (c - acx);
|
|
939
|
+
alo = acx - ahi;
|
|
940
|
+
c = splitter * bcytail;
|
|
941
|
+
bhi = c - (c - bcytail);
|
|
942
|
+
blo = bcytail - bhi;
|
|
943
|
+
s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
944
|
+
t1 = acy * bcxtail;
|
|
945
|
+
c = splitter * acy;
|
|
946
|
+
ahi = c - (c - acy);
|
|
947
|
+
alo = acy - ahi;
|
|
948
|
+
c = splitter * bcxtail;
|
|
949
|
+
bhi = c - (c - bcxtail);
|
|
950
|
+
blo = bcxtail - bhi;
|
|
951
|
+
t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
952
|
+
_i = s0 - t0;
|
|
953
|
+
bvirt = s0 - _i;
|
|
954
|
+
u[0] = s0 - (_i + bvirt) + (bvirt - t0);
|
|
955
|
+
_j = s1 + _i;
|
|
956
|
+
bvirt = _j - s1;
|
|
957
|
+
_0 = s1 - (_j - bvirt) + (_i - bvirt);
|
|
958
|
+
_i = _0 - t1;
|
|
959
|
+
bvirt = _0 - _i;
|
|
960
|
+
u[1] = _0 - (_i + bvirt) + (bvirt - t1);
|
|
961
|
+
u3 = _j + _i;
|
|
962
|
+
bvirt = u3 - _j;
|
|
963
|
+
u[2] = _j - (u3 - bvirt) + (_i - bvirt);
|
|
964
|
+
u[3] = u3;
|
|
965
|
+
const C2len = sum(C1len, C1, 4, u, C2);
|
|
966
|
+
s1 = acxtail * bcytail;
|
|
967
|
+
c = splitter * acxtail;
|
|
968
|
+
ahi = c - (c - acxtail);
|
|
969
|
+
alo = acxtail - ahi;
|
|
970
|
+
c = splitter * bcytail;
|
|
971
|
+
bhi = c - (c - bcytail);
|
|
972
|
+
blo = bcytail - bhi;
|
|
973
|
+
s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
974
|
+
t1 = acytail * bcxtail;
|
|
975
|
+
c = splitter * acytail;
|
|
976
|
+
ahi = c - (c - acytail);
|
|
977
|
+
alo = acytail - ahi;
|
|
978
|
+
c = splitter * bcxtail;
|
|
979
|
+
bhi = c - (c - bcxtail);
|
|
980
|
+
blo = bcxtail - bhi;
|
|
981
|
+
t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo);
|
|
982
|
+
_i = s0 - t0;
|
|
983
|
+
bvirt = s0 - _i;
|
|
984
|
+
u[0] = s0 - (_i + bvirt) + (bvirt - t0);
|
|
985
|
+
_j = s1 + _i;
|
|
986
|
+
bvirt = _j - s1;
|
|
987
|
+
_0 = s1 - (_j - bvirt) + (_i - bvirt);
|
|
988
|
+
_i = _0 - t1;
|
|
989
|
+
bvirt = _0 - _i;
|
|
990
|
+
u[1] = _0 - (_i + bvirt) + (bvirt - t1);
|
|
991
|
+
u3 = _j + _i;
|
|
992
|
+
bvirt = u3 - _j;
|
|
993
|
+
u[2] = _j - (u3 - bvirt) + (_i - bvirt);
|
|
994
|
+
u[3] = u3;
|
|
995
|
+
const Dlen = sum(C2len, C2, 4, u, D);
|
|
996
|
+
return D[Dlen - 1];
|
|
332
997
|
}
|
|
333
|
-
function
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
998
|
+
function orient2d(ax, ay, bx, by, cx, cy) {
|
|
999
|
+
const detleft = (ay - cy) * (bx - cx);
|
|
1000
|
+
const detright = (ax - cx) * (by - cy);
|
|
1001
|
+
const det = detleft - detright;
|
|
1002
|
+
const detsum = Math.abs(detleft + detright);
|
|
1003
|
+
if (Math.abs(det) >= ccwerrboundA * detsum) return det;
|
|
1004
|
+
return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum);
|
|
338
1005
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
1006
|
+
const crossProduct = (a, b) => a.x * b.y - a.y * b.x;
|
|
1007
|
+
const dotProduct = (a, b) => a.x * b.x + a.y * b.y;
|
|
1008
|
+
const compareVectorAngles = (basePt, endPt1, endPt2) => {
|
|
1009
|
+
const res = orient2d(basePt.x, basePt.y, endPt1.x, endPt1.y, endPt2.x, endPt2.y);
|
|
1010
|
+
if (res > 0) return -1;
|
|
1011
|
+
if (res < 0) return 1;
|
|
1012
|
+
return 0;
|
|
1013
|
+
};
|
|
1014
|
+
const length = (v) => Math.sqrt(dotProduct(v, v));
|
|
1015
|
+
const sineOfAngle = (pShared, pBase, pAngle) => {
|
|
1016
|
+
const vBase = {
|
|
1017
|
+
x: pBase.x - pShared.x,
|
|
1018
|
+
y: pBase.y - pShared.y
|
|
1019
|
+
};
|
|
1020
|
+
const vAngle = {
|
|
1021
|
+
x: pAngle.x - pShared.x,
|
|
1022
|
+
y: pAngle.y - pShared.y
|
|
342
1023
|
};
|
|
1024
|
+
return crossProduct(vAngle, vBase) / length(vAngle) / length(vBase);
|
|
1025
|
+
};
|
|
1026
|
+
const cosineOfAngle = (pShared, pBase, pAngle) => {
|
|
1027
|
+
const vBase = {
|
|
1028
|
+
x: pBase.x - pShared.x,
|
|
1029
|
+
y: pBase.y - pShared.y
|
|
1030
|
+
};
|
|
1031
|
+
const vAngle = {
|
|
1032
|
+
x: pAngle.x - pShared.x,
|
|
1033
|
+
y: pAngle.y - pShared.y
|
|
1034
|
+
};
|
|
1035
|
+
return dotProduct(vAngle, vBase) / length(vAngle) / length(vBase);
|
|
1036
|
+
};
|
|
1037
|
+
const horizontalIntersection = (pt, v, y) => {
|
|
1038
|
+
if (v.y === 0) return null;
|
|
1039
|
+
return {
|
|
1040
|
+
x: pt.x + v.x / v.y * (y - pt.y),
|
|
1041
|
+
y
|
|
1042
|
+
};
|
|
1043
|
+
};
|
|
1044
|
+
const verticalIntersection = (pt, v, x) => {
|
|
1045
|
+
if (v.x === 0) return null;
|
|
1046
|
+
return {
|
|
1047
|
+
x,
|
|
1048
|
+
y: pt.y + v.y / v.x * (x - pt.x)
|
|
1049
|
+
};
|
|
1050
|
+
};
|
|
1051
|
+
const intersection$1 = (pt1, v1, pt2, v2) => {
|
|
1052
|
+
if (v1.x === 0) return verticalIntersection(pt2, v2, pt1.x);
|
|
1053
|
+
if (v2.x === 0) return verticalIntersection(pt1, v1, pt2.x);
|
|
1054
|
+
if (v1.y === 0) return horizontalIntersection(pt2, v2, pt1.y);
|
|
1055
|
+
if (v2.y === 0) return horizontalIntersection(pt1, v1, pt2.y);
|
|
1056
|
+
const kross = crossProduct(v1, v2);
|
|
1057
|
+
if (kross == 0) return null;
|
|
1058
|
+
const ve = {
|
|
1059
|
+
x: pt2.x - pt1.x,
|
|
1060
|
+
y: pt2.y - pt1.y
|
|
1061
|
+
};
|
|
1062
|
+
const d1 = crossProduct(ve, v1) / kross;
|
|
1063
|
+
const d2 = crossProduct(ve, v2) / kross;
|
|
1064
|
+
const x1 = pt1.x + d2 * v1.x, x2 = pt2.x + d1 * v2.x;
|
|
1065
|
+
const y1 = pt1.y + d2 * v1.y, y2 = pt2.y + d1 * v2.y;
|
|
1066
|
+
const x = (x1 + x2) / 2;
|
|
1067
|
+
const y = (y1 + y2) / 2;
|
|
1068
|
+
return {
|
|
1069
|
+
x,
|
|
1070
|
+
y
|
|
1071
|
+
};
|
|
1072
|
+
};
|
|
1073
|
+
class SweepEvent {
|
|
1074
|
+
// for ordering sweep events in the sweep event queue
|
|
1075
|
+
static compare(a, b) {
|
|
1076
|
+
const ptCmp = SweepEvent.comparePoints(a.point, b.point);
|
|
1077
|
+
if (ptCmp !== 0) return ptCmp;
|
|
1078
|
+
if (a.point !== b.point) a.link(b);
|
|
1079
|
+
if (a.isLeft !== b.isLeft) return a.isLeft ? 1 : -1;
|
|
1080
|
+
return Segment.compare(a.segment, b.segment);
|
|
1081
|
+
}
|
|
1082
|
+
// for ordering points in sweep line order
|
|
1083
|
+
static comparePoints(aPt, bPt) {
|
|
1084
|
+
if (aPt.x < bPt.x) return -1;
|
|
1085
|
+
if (aPt.x > bPt.x) return 1;
|
|
1086
|
+
if (aPt.y < bPt.y) return -1;
|
|
1087
|
+
if (aPt.y > bPt.y) return 1;
|
|
1088
|
+
return 0;
|
|
1089
|
+
}
|
|
1090
|
+
// Warning: 'point' input will be modified and re-used (for performance)
|
|
1091
|
+
constructor(point, isLeft) {
|
|
1092
|
+
if (point.events === void 0) point.events = [this];
|
|
1093
|
+
else point.events.push(this);
|
|
1094
|
+
this.point = point;
|
|
1095
|
+
this.isLeft = isLeft;
|
|
1096
|
+
}
|
|
1097
|
+
link(other) {
|
|
1098
|
+
if (other.point === this.point) {
|
|
1099
|
+
throw new Error("Tried to link already linked events");
|
|
1100
|
+
}
|
|
1101
|
+
const otherEvents = other.point.events;
|
|
1102
|
+
for (let i = 0, iMax = otherEvents.length; i < iMax; i++) {
|
|
1103
|
+
const evt = otherEvents[i];
|
|
1104
|
+
this.point.events.push(evt);
|
|
1105
|
+
evt.point = this.point;
|
|
1106
|
+
}
|
|
1107
|
+
this.checkForConsuming();
|
|
1108
|
+
}
|
|
1109
|
+
/* Do a pass over our linked events and check to see if any pair
|
|
1110
|
+
* of segments match, and should be consumed. */
|
|
1111
|
+
checkForConsuming() {
|
|
1112
|
+
const numEvents = this.point.events.length;
|
|
1113
|
+
for (let i = 0; i < numEvents; i++) {
|
|
1114
|
+
const evt1 = this.point.events[i];
|
|
1115
|
+
if (evt1.segment.consumedBy !== void 0) continue;
|
|
1116
|
+
for (let j = i + 1; j < numEvents; j++) {
|
|
1117
|
+
const evt2 = this.point.events[j];
|
|
1118
|
+
if (evt2.consumedBy !== void 0) continue;
|
|
1119
|
+
if (evt1.otherSE.point.events !== evt2.otherSE.point.events) continue;
|
|
1120
|
+
evt1.segment.consume(evt2.segment);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
getAvailableLinkedEvents() {
|
|
1125
|
+
const events = [];
|
|
1126
|
+
for (let i = 0, iMax = this.point.events.length; i < iMax; i++) {
|
|
1127
|
+
const evt = this.point.events[i];
|
|
1128
|
+
if (evt !== this && !evt.segment.ringOut && evt.segment.isInResult()) {
|
|
1129
|
+
events.push(evt);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
return events;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Returns a comparator function for sorting linked events that will
|
|
1136
|
+
* favor the event that will give us the smallest left-side angle.
|
|
1137
|
+
* All ring construction starts as low as possible heading to the right,
|
|
1138
|
+
* so by always turning left as sharp as possible we'll get polygons
|
|
1139
|
+
* without uncessary loops & holes.
|
|
1140
|
+
*
|
|
1141
|
+
* The comparator function has a compute cache such that it avoids
|
|
1142
|
+
* re-computing already-computed values.
|
|
1143
|
+
*/
|
|
1144
|
+
getLeftmostComparator(baseEvent) {
|
|
1145
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1146
|
+
const fillCache = (linkedEvent) => {
|
|
1147
|
+
const nextEvent = linkedEvent.otherSE;
|
|
1148
|
+
cache.set(linkedEvent, {
|
|
1149
|
+
sine: sineOfAngle(this.point, baseEvent.point, nextEvent.point),
|
|
1150
|
+
cosine: cosineOfAngle(this.point, baseEvent.point, nextEvent.point)
|
|
1151
|
+
});
|
|
1152
|
+
};
|
|
1153
|
+
return (a, b) => {
|
|
1154
|
+
if (!cache.has(a)) fillCache(a);
|
|
1155
|
+
if (!cache.has(b)) fillCache(b);
|
|
1156
|
+
const {
|
|
1157
|
+
sine: asine,
|
|
1158
|
+
cosine: acosine
|
|
1159
|
+
} = cache.get(a);
|
|
1160
|
+
const {
|
|
1161
|
+
sine: bsine,
|
|
1162
|
+
cosine: bcosine
|
|
1163
|
+
} = cache.get(b);
|
|
1164
|
+
if (asine >= 0 && bsine >= 0) {
|
|
1165
|
+
if (acosine < bcosine) return 1;
|
|
1166
|
+
if (acosine > bcosine) return -1;
|
|
1167
|
+
return 0;
|
|
1168
|
+
}
|
|
1169
|
+
if (asine < 0 && bsine < 0) {
|
|
1170
|
+
if (acosine < bcosine) return -1;
|
|
1171
|
+
if (acosine > bcosine) return 1;
|
|
1172
|
+
return 0;
|
|
1173
|
+
}
|
|
1174
|
+
if (bsine < asine) return -1;
|
|
1175
|
+
if (bsine > asine) return 1;
|
|
1176
|
+
return 0;
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
let segmentId = 0;
|
|
1181
|
+
class Segment {
|
|
1182
|
+
/* This compare() function is for ordering segments in the sweep
|
|
1183
|
+
* line tree, and does so according to the following criteria:
|
|
1184
|
+
*
|
|
1185
|
+
* Consider the vertical line that lies an infinestimal step to the
|
|
1186
|
+
* right of the right-more of the two left endpoints of the input
|
|
1187
|
+
* segments. Imagine slowly moving a point up from negative infinity
|
|
1188
|
+
* in the increasing y direction. Which of the two segments will that
|
|
1189
|
+
* point intersect first? That segment comes 'before' the other one.
|
|
1190
|
+
*
|
|
1191
|
+
* If neither segment would be intersected by such a line, (if one
|
|
1192
|
+
* or more of the segments are vertical) then the line to be considered
|
|
1193
|
+
* is directly on the right-more of the two left inputs.
|
|
1194
|
+
*/
|
|
1195
|
+
static compare(a, b) {
|
|
1196
|
+
const alx = a.leftSE.point.x;
|
|
1197
|
+
const blx = b.leftSE.point.x;
|
|
1198
|
+
const arx = a.rightSE.point.x;
|
|
1199
|
+
const brx = b.rightSE.point.x;
|
|
1200
|
+
if (brx < alx) return 1;
|
|
1201
|
+
if (arx < blx) return -1;
|
|
1202
|
+
const aly = a.leftSE.point.y;
|
|
1203
|
+
const bly = b.leftSE.point.y;
|
|
1204
|
+
const ary = a.rightSE.point.y;
|
|
1205
|
+
const bry = b.rightSE.point.y;
|
|
1206
|
+
if (alx < blx) {
|
|
1207
|
+
if (bly < aly && bly < ary) return 1;
|
|
1208
|
+
if (bly > aly && bly > ary) return -1;
|
|
1209
|
+
const aCmpBLeft = a.comparePoint(b.leftSE.point);
|
|
1210
|
+
if (aCmpBLeft < 0) return 1;
|
|
1211
|
+
if (aCmpBLeft > 0) return -1;
|
|
1212
|
+
const bCmpARight = b.comparePoint(a.rightSE.point);
|
|
1213
|
+
if (bCmpARight !== 0) return bCmpARight;
|
|
1214
|
+
return -1;
|
|
1215
|
+
}
|
|
1216
|
+
if (alx > blx) {
|
|
1217
|
+
if (aly < bly && aly < bry) return -1;
|
|
1218
|
+
if (aly > bly && aly > bry) return 1;
|
|
1219
|
+
const bCmpALeft = b.comparePoint(a.leftSE.point);
|
|
1220
|
+
if (bCmpALeft !== 0) return bCmpALeft;
|
|
1221
|
+
const aCmpBRight = a.comparePoint(b.rightSE.point);
|
|
1222
|
+
if (aCmpBRight < 0) return 1;
|
|
1223
|
+
if (aCmpBRight > 0) return -1;
|
|
1224
|
+
return 1;
|
|
1225
|
+
}
|
|
1226
|
+
if (aly < bly) return -1;
|
|
1227
|
+
if (aly > bly) return 1;
|
|
1228
|
+
if (arx < brx) {
|
|
1229
|
+
const bCmpARight = b.comparePoint(a.rightSE.point);
|
|
1230
|
+
if (bCmpARight !== 0) return bCmpARight;
|
|
1231
|
+
}
|
|
1232
|
+
if (arx > brx) {
|
|
1233
|
+
const aCmpBRight = a.comparePoint(b.rightSE.point);
|
|
1234
|
+
if (aCmpBRight < 0) return 1;
|
|
1235
|
+
if (aCmpBRight > 0) return -1;
|
|
1236
|
+
}
|
|
1237
|
+
if (arx !== brx) {
|
|
1238
|
+
const ay = ary - aly;
|
|
1239
|
+
const ax = arx - alx;
|
|
1240
|
+
const by = bry - bly;
|
|
1241
|
+
const bx = brx - blx;
|
|
1242
|
+
if (ay > ax && by < bx) return 1;
|
|
1243
|
+
if (ay < ax && by > bx) return -1;
|
|
1244
|
+
}
|
|
1245
|
+
if (arx > brx) return 1;
|
|
1246
|
+
if (arx < brx) return -1;
|
|
1247
|
+
if (ary < bry) return -1;
|
|
1248
|
+
if (ary > bry) return 1;
|
|
1249
|
+
if (a.id < b.id) return -1;
|
|
1250
|
+
if (a.id > b.id) return 1;
|
|
1251
|
+
return 0;
|
|
1252
|
+
}
|
|
1253
|
+
/* Warning: a reference to ringWindings input will be stored,
|
|
1254
|
+
* and possibly will be later modified */
|
|
1255
|
+
constructor(leftSE, rightSE, rings, windings) {
|
|
1256
|
+
this.id = ++segmentId;
|
|
1257
|
+
this.leftSE = leftSE;
|
|
1258
|
+
leftSE.segment = this;
|
|
1259
|
+
leftSE.otherSE = rightSE;
|
|
1260
|
+
this.rightSE = rightSE;
|
|
1261
|
+
rightSE.segment = this;
|
|
1262
|
+
rightSE.otherSE = leftSE;
|
|
1263
|
+
this.rings = rings;
|
|
1264
|
+
this.windings = windings;
|
|
1265
|
+
}
|
|
1266
|
+
static fromRing(pt1, pt2, ring) {
|
|
1267
|
+
let leftPt, rightPt, winding;
|
|
1268
|
+
const cmpPts = SweepEvent.comparePoints(pt1, pt2);
|
|
1269
|
+
if (cmpPts < 0) {
|
|
1270
|
+
leftPt = pt1;
|
|
1271
|
+
rightPt = pt2;
|
|
1272
|
+
winding = 1;
|
|
1273
|
+
} else if (cmpPts > 0) {
|
|
1274
|
+
leftPt = pt2;
|
|
1275
|
+
rightPt = pt1;
|
|
1276
|
+
winding = -1;
|
|
1277
|
+
} else throw new Error(`Tried to create degenerate segment at [${pt1.x}, ${pt1.y}]`);
|
|
1278
|
+
const leftSE = new SweepEvent(leftPt, true);
|
|
1279
|
+
const rightSE = new SweepEvent(rightPt, false);
|
|
1280
|
+
return new Segment(leftSE, rightSE, [ring], [winding]);
|
|
1281
|
+
}
|
|
1282
|
+
/* When a segment is split, the rightSE is replaced with a new sweep event */
|
|
1283
|
+
replaceRightSE(newRightSE) {
|
|
1284
|
+
this.rightSE = newRightSE;
|
|
1285
|
+
this.rightSE.segment = this;
|
|
1286
|
+
this.rightSE.otherSE = this.leftSE;
|
|
1287
|
+
this.leftSE.otherSE = this.rightSE;
|
|
1288
|
+
}
|
|
1289
|
+
bbox() {
|
|
1290
|
+
const y1 = this.leftSE.point.y;
|
|
1291
|
+
const y2 = this.rightSE.point.y;
|
|
1292
|
+
return {
|
|
1293
|
+
ll: {
|
|
1294
|
+
x: this.leftSE.point.x,
|
|
1295
|
+
y: y1 < y2 ? y1 : y2
|
|
1296
|
+
},
|
|
1297
|
+
ur: {
|
|
1298
|
+
x: this.rightSE.point.x,
|
|
1299
|
+
y: y1 > y2 ? y1 : y2
|
|
1300
|
+
}
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
/* A vector from the left point to the right */
|
|
1304
|
+
vector() {
|
|
1305
|
+
return {
|
|
1306
|
+
x: this.rightSE.point.x - this.leftSE.point.x,
|
|
1307
|
+
y: this.rightSE.point.y - this.leftSE.point.y
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
isAnEndpoint(pt) {
|
|
1311
|
+
return pt.x === this.leftSE.point.x && pt.y === this.leftSE.point.y || pt.x === this.rightSE.point.x && pt.y === this.rightSE.point.y;
|
|
1312
|
+
}
|
|
1313
|
+
/* Compare this segment with a point.
|
|
1314
|
+
*
|
|
1315
|
+
* A point P is considered to be colinear to a segment if there
|
|
1316
|
+
* exists a distance D such that if we travel along the segment
|
|
1317
|
+
* from one * endpoint towards the other a distance D, we find
|
|
1318
|
+
* ourselves at point P.
|
|
1319
|
+
*
|
|
1320
|
+
* Return value indicates:
|
|
1321
|
+
*
|
|
1322
|
+
* 1: point lies above the segment (to the left of vertical)
|
|
1323
|
+
* 0: point is colinear to segment
|
|
1324
|
+
* -1: point lies below the segment (to the right of vertical)
|
|
1325
|
+
*/
|
|
1326
|
+
comparePoint(point) {
|
|
1327
|
+
if (this.isAnEndpoint(point)) return 0;
|
|
1328
|
+
const lPt = this.leftSE.point;
|
|
1329
|
+
const rPt = this.rightSE.point;
|
|
1330
|
+
const v = this.vector();
|
|
1331
|
+
if (lPt.x === rPt.x) {
|
|
1332
|
+
if (point.x === lPt.x) return 0;
|
|
1333
|
+
return point.x < lPt.x ? 1 : -1;
|
|
1334
|
+
}
|
|
1335
|
+
const yDist = (point.y - lPt.y) / v.y;
|
|
1336
|
+
const xFromYDist = lPt.x + yDist * v.x;
|
|
1337
|
+
if (point.x === xFromYDist) return 0;
|
|
1338
|
+
const xDist = (point.x - lPt.x) / v.x;
|
|
1339
|
+
const yFromXDist = lPt.y + xDist * v.y;
|
|
1340
|
+
if (point.y === yFromXDist) return 0;
|
|
1341
|
+
return point.y < yFromXDist ? -1 : 1;
|
|
1342
|
+
}
|
|
1343
|
+
/**
|
|
1344
|
+
* Given another segment, returns the first non-trivial intersection
|
|
1345
|
+
* between the two segments (in terms of sweep line ordering), if it exists.
|
|
1346
|
+
*
|
|
1347
|
+
* A 'non-trivial' intersection is one that will cause one or both of the
|
|
1348
|
+
* segments to be split(). As such, 'trivial' vs. 'non-trivial' intersection:
|
|
1349
|
+
*
|
|
1350
|
+
* * endpoint of segA with endpoint of segB --> trivial
|
|
1351
|
+
* * endpoint of segA with point along segB --> non-trivial
|
|
1352
|
+
* * endpoint of segB with point along segA --> non-trivial
|
|
1353
|
+
* * point along segA with point along segB --> non-trivial
|
|
1354
|
+
*
|
|
1355
|
+
* If no non-trivial intersection exists, return null
|
|
1356
|
+
* Else, return null.
|
|
1357
|
+
*/
|
|
1358
|
+
getIntersection(other) {
|
|
1359
|
+
const tBbox = this.bbox();
|
|
1360
|
+
const oBbox = other.bbox();
|
|
1361
|
+
const bboxOverlap = getBboxOverlap(tBbox, oBbox);
|
|
1362
|
+
if (bboxOverlap === null) return null;
|
|
1363
|
+
const tlp = this.leftSE.point;
|
|
1364
|
+
const trp = this.rightSE.point;
|
|
1365
|
+
const olp = other.leftSE.point;
|
|
1366
|
+
const orp = other.rightSE.point;
|
|
1367
|
+
const touchesOtherLSE = isInBbox(tBbox, olp) && this.comparePoint(olp) === 0;
|
|
1368
|
+
const touchesThisLSE = isInBbox(oBbox, tlp) && other.comparePoint(tlp) === 0;
|
|
1369
|
+
const touchesOtherRSE = isInBbox(tBbox, orp) && this.comparePoint(orp) === 0;
|
|
1370
|
+
const touchesThisRSE = isInBbox(oBbox, trp) && other.comparePoint(trp) === 0;
|
|
1371
|
+
if (touchesThisLSE && touchesOtherLSE) {
|
|
1372
|
+
if (touchesThisRSE && !touchesOtherRSE) return trp;
|
|
1373
|
+
if (!touchesThisRSE && touchesOtherRSE) return orp;
|
|
1374
|
+
return null;
|
|
1375
|
+
}
|
|
1376
|
+
if (touchesThisLSE) {
|
|
1377
|
+
if (touchesOtherRSE) {
|
|
1378
|
+
if (tlp.x === orp.x && tlp.y === orp.y) return null;
|
|
1379
|
+
}
|
|
1380
|
+
return tlp;
|
|
1381
|
+
}
|
|
1382
|
+
if (touchesOtherLSE) {
|
|
1383
|
+
if (touchesThisRSE) {
|
|
1384
|
+
if (trp.x === olp.x && trp.y === olp.y) return null;
|
|
1385
|
+
}
|
|
1386
|
+
return olp;
|
|
1387
|
+
}
|
|
1388
|
+
if (touchesThisRSE && touchesOtherRSE) return null;
|
|
1389
|
+
if (touchesThisRSE) return trp;
|
|
1390
|
+
if (touchesOtherRSE) return orp;
|
|
1391
|
+
const pt = intersection$1(tlp, this.vector(), olp, other.vector());
|
|
1392
|
+
if (pt === null) return null;
|
|
1393
|
+
if (!isInBbox(bboxOverlap, pt)) return null;
|
|
1394
|
+
return rounder.round(pt.x, pt.y);
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Split the given segment into multiple segments on the given points.
|
|
1398
|
+
* * Each existing segment will retain its leftSE and a new rightSE will be
|
|
1399
|
+
* generated for it.
|
|
1400
|
+
* * A new segment will be generated which will adopt the original segment's
|
|
1401
|
+
* rightSE, and a new leftSE will be generated for it.
|
|
1402
|
+
* * If there are more than two points given to split on, new segments
|
|
1403
|
+
* in the middle will be generated with new leftSE and rightSE's.
|
|
1404
|
+
* * An array of the newly generated SweepEvents will be returned.
|
|
1405
|
+
*
|
|
1406
|
+
* Warning: input array of points is modified
|
|
1407
|
+
*/
|
|
1408
|
+
split(point) {
|
|
1409
|
+
const newEvents = [];
|
|
1410
|
+
const alreadyLinked = point.events !== void 0;
|
|
1411
|
+
const newLeftSE = new SweepEvent(point, true);
|
|
1412
|
+
const newRightSE = new SweepEvent(point, false);
|
|
1413
|
+
const oldRightSE = this.rightSE;
|
|
1414
|
+
this.replaceRightSE(newRightSE);
|
|
1415
|
+
newEvents.push(newRightSE);
|
|
1416
|
+
newEvents.push(newLeftSE);
|
|
1417
|
+
const newSeg = new Segment(newLeftSE, oldRightSE, this.rings.slice(), this.windings.slice());
|
|
1418
|
+
if (SweepEvent.comparePoints(newSeg.leftSE.point, newSeg.rightSE.point) > 0) {
|
|
1419
|
+
newSeg.swapEvents();
|
|
1420
|
+
}
|
|
1421
|
+
if (SweepEvent.comparePoints(this.leftSE.point, this.rightSE.point) > 0) {
|
|
1422
|
+
this.swapEvents();
|
|
1423
|
+
}
|
|
1424
|
+
if (alreadyLinked) {
|
|
1425
|
+
newLeftSE.checkForConsuming();
|
|
1426
|
+
newRightSE.checkForConsuming();
|
|
1427
|
+
}
|
|
1428
|
+
return newEvents;
|
|
1429
|
+
}
|
|
1430
|
+
/* Swap which event is left and right */
|
|
1431
|
+
swapEvents() {
|
|
1432
|
+
const tmpEvt = this.rightSE;
|
|
1433
|
+
this.rightSE = this.leftSE;
|
|
1434
|
+
this.leftSE = tmpEvt;
|
|
1435
|
+
this.leftSE.isLeft = true;
|
|
1436
|
+
this.rightSE.isLeft = false;
|
|
1437
|
+
for (let i = 0, iMax = this.windings.length; i < iMax; i++) {
|
|
1438
|
+
this.windings[i] *= -1;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
/* Consume another segment. We take their rings under our wing
|
|
1442
|
+
* and mark them as consumed. Use for perfectly overlapping segments */
|
|
1443
|
+
consume(other) {
|
|
1444
|
+
let consumer = this;
|
|
1445
|
+
let consumee = other;
|
|
1446
|
+
while (consumer.consumedBy) consumer = consumer.consumedBy;
|
|
1447
|
+
while (consumee.consumedBy) consumee = consumee.consumedBy;
|
|
1448
|
+
const cmp2 = Segment.compare(consumer, consumee);
|
|
1449
|
+
if (cmp2 === 0) return;
|
|
1450
|
+
if (cmp2 > 0) {
|
|
1451
|
+
const tmp = consumer;
|
|
1452
|
+
consumer = consumee;
|
|
1453
|
+
consumee = tmp;
|
|
1454
|
+
}
|
|
1455
|
+
if (consumer.prev === consumee) {
|
|
1456
|
+
const tmp = consumer;
|
|
1457
|
+
consumer = consumee;
|
|
1458
|
+
consumee = tmp;
|
|
1459
|
+
}
|
|
1460
|
+
for (let i = 0, iMax = consumee.rings.length; i < iMax; i++) {
|
|
1461
|
+
const ring = consumee.rings[i];
|
|
1462
|
+
const winding = consumee.windings[i];
|
|
1463
|
+
const index2 = consumer.rings.indexOf(ring);
|
|
1464
|
+
if (index2 === -1) {
|
|
1465
|
+
consumer.rings.push(ring);
|
|
1466
|
+
consumer.windings.push(winding);
|
|
1467
|
+
} else consumer.windings[index2] += winding;
|
|
1468
|
+
}
|
|
1469
|
+
consumee.rings = null;
|
|
1470
|
+
consumee.windings = null;
|
|
1471
|
+
consumee.consumedBy = consumer;
|
|
1472
|
+
consumee.leftSE.consumedBy = consumer.leftSE;
|
|
1473
|
+
consumee.rightSE.consumedBy = consumer.rightSE;
|
|
1474
|
+
}
|
|
1475
|
+
/* The first segment previous segment chain that is in the result */
|
|
1476
|
+
prevInResult() {
|
|
1477
|
+
if (this._prevInResult !== void 0) return this._prevInResult;
|
|
1478
|
+
if (!this.prev) this._prevInResult = null;
|
|
1479
|
+
else if (this.prev.isInResult()) this._prevInResult = this.prev;
|
|
1480
|
+
else this._prevInResult = this.prev.prevInResult();
|
|
1481
|
+
return this._prevInResult;
|
|
1482
|
+
}
|
|
1483
|
+
beforeState() {
|
|
1484
|
+
if (this._beforeState !== void 0) return this._beforeState;
|
|
1485
|
+
if (!this.prev) this._beforeState = {
|
|
1486
|
+
rings: [],
|
|
1487
|
+
windings: [],
|
|
1488
|
+
multiPolys: []
|
|
1489
|
+
};
|
|
1490
|
+
else {
|
|
1491
|
+
const seg = this.prev.consumedBy || this.prev;
|
|
1492
|
+
this._beforeState = seg.afterState();
|
|
1493
|
+
}
|
|
1494
|
+
return this._beforeState;
|
|
1495
|
+
}
|
|
1496
|
+
afterState() {
|
|
1497
|
+
if (this._afterState !== void 0) return this._afterState;
|
|
1498
|
+
const beforeState = this.beforeState();
|
|
1499
|
+
this._afterState = {
|
|
1500
|
+
rings: beforeState.rings.slice(0),
|
|
1501
|
+
windings: beforeState.windings.slice(0),
|
|
1502
|
+
multiPolys: []
|
|
1503
|
+
};
|
|
1504
|
+
const ringsAfter = this._afterState.rings;
|
|
1505
|
+
const windingsAfter = this._afterState.windings;
|
|
1506
|
+
const mpsAfter = this._afterState.multiPolys;
|
|
1507
|
+
for (let i = 0, iMax = this.rings.length; i < iMax; i++) {
|
|
1508
|
+
const ring = this.rings[i];
|
|
1509
|
+
const winding = this.windings[i];
|
|
1510
|
+
const index2 = ringsAfter.indexOf(ring);
|
|
1511
|
+
if (index2 === -1) {
|
|
1512
|
+
ringsAfter.push(ring);
|
|
1513
|
+
windingsAfter.push(winding);
|
|
1514
|
+
} else windingsAfter[index2] += winding;
|
|
1515
|
+
}
|
|
1516
|
+
const polysAfter = [];
|
|
1517
|
+
const polysExclude = [];
|
|
1518
|
+
for (let i = 0, iMax = ringsAfter.length; i < iMax; i++) {
|
|
1519
|
+
if (windingsAfter[i] === 0) continue;
|
|
1520
|
+
const ring = ringsAfter[i];
|
|
1521
|
+
const poly = ring.poly;
|
|
1522
|
+
if (polysExclude.indexOf(poly) !== -1) continue;
|
|
1523
|
+
if (ring.isExterior) polysAfter.push(poly);
|
|
1524
|
+
else {
|
|
1525
|
+
if (polysExclude.indexOf(poly) === -1) polysExclude.push(poly);
|
|
1526
|
+
const index2 = polysAfter.indexOf(ring.poly);
|
|
1527
|
+
if (index2 !== -1) polysAfter.splice(index2, 1);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
for (let i = 0, iMax = polysAfter.length; i < iMax; i++) {
|
|
1531
|
+
const mp = polysAfter[i].multiPoly;
|
|
1532
|
+
if (mpsAfter.indexOf(mp) === -1) mpsAfter.push(mp);
|
|
1533
|
+
}
|
|
1534
|
+
return this._afterState;
|
|
1535
|
+
}
|
|
1536
|
+
/* Is this segment part of the final result? */
|
|
1537
|
+
isInResult() {
|
|
1538
|
+
if (this.consumedBy) return false;
|
|
1539
|
+
if (this._isInResult !== void 0) return this._isInResult;
|
|
1540
|
+
const mpsBefore = this.beforeState().multiPolys;
|
|
1541
|
+
const mpsAfter = this.afterState().multiPolys;
|
|
1542
|
+
switch (operation.type) {
|
|
1543
|
+
case "union": {
|
|
1544
|
+
const noBefores = mpsBefore.length === 0;
|
|
1545
|
+
const noAfters = mpsAfter.length === 0;
|
|
1546
|
+
this._isInResult = noBefores !== noAfters;
|
|
1547
|
+
break;
|
|
1548
|
+
}
|
|
1549
|
+
case "intersection": {
|
|
1550
|
+
let least;
|
|
1551
|
+
let most;
|
|
1552
|
+
if (mpsBefore.length < mpsAfter.length) {
|
|
1553
|
+
least = mpsBefore.length;
|
|
1554
|
+
most = mpsAfter.length;
|
|
1555
|
+
} else {
|
|
1556
|
+
least = mpsAfter.length;
|
|
1557
|
+
most = mpsBefore.length;
|
|
1558
|
+
}
|
|
1559
|
+
this._isInResult = most === operation.numMultiPolys && least < most;
|
|
1560
|
+
break;
|
|
1561
|
+
}
|
|
1562
|
+
case "xor": {
|
|
1563
|
+
const diff = Math.abs(mpsBefore.length - mpsAfter.length);
|
|
1564
|
+
this._isInResult = diff % 2 === 1;
|
|
1565
|
+
break;
|
|
1566
|
+
}
|
|
1567
|
+
case "difference": {
|
|
1568
|
+
const isJustSubject = (mps) => mps.length === 1 && mps[0].isSubject;
|
|
1569
|
+
this._isInResult = isJustSubject(mpsBefore) !== isJustSubject(mpsAfter);
|
|
1570
|
+
break;
|
|
1571
|
+
}
|
|
1572
|
+
default:
|
|
1573
|
+
throw new Error(`Unrecognized operation type found ${operation.type}`);
|
|
1574
|
+
}
|
|
1575
|
+
return this._isInResult;
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
class RingIn {
|
|
1579
|
+
constructor(geomRing, poly, isExterior) {
|
|
1580
|
+
if (!Array.isArray(geomRing) || geomRing.length === 0) {
|
|
1581
|
+
throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
|
|
1582
|
+
}
|
|
1583
|
+
this.poly = poly;
|
|
1584
|
+
this.isExterior = isExterior;
|
|
1585
|
+
this.segments = [];
|
|
1586
|
+
if (typeof geomRing[0][0] !== "number" || typeof geomRing[0][1] !== "number") {
|
|
1587
|
+
throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
|
|
1588
|
+
}
|
|
1589
|
+
const firstPoint = rounder.round(geomRing[0][0], geomRing[0][1]);
|
|
1590
|
+
this.bbox = {
|
|
1591
|
+
ll: {
|
|
1592
|
+
x: firstPoint.x,
|
|
1593
|
+
y: firstPoint.y
|
|
1594
|
+
},
|
|
1595
|
+
ur: {
|
|
1596
|
+
x: firstPoint.x,
|
|
1597
|
+
y: firstPoint.y
|
|
1598
|
+
}
|
|
1599
|
+
};
|
|
1600
|
+
let prevPoint = firstPoint;
|
|
1601
|
+
for (let i = 1, iMax = geomRing.length; i < iMax; i++) {
|
|
1602
|
+
if (typeof geomRing[i][0] !== "number" || typeof geomRing[i][1] !== "number") {
|
|
1603
|
+
throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
|
|
1604
|
+
}
|
|
1605
|
+
let point = rounder.round(geomRing[i][0], geomRing[i][1]);
|
|
1606
|
+
if (point.x === prevPoint.x && point.y === prevPoint.y) continue;
|
|
1607
|
+
this.segments.push(Segment.fromRing(prevPoint, point, this));
|
|
1608
|
+
if (point.x < this.bbox.ll.x) this.bbox.ll.x = point.x;
|
|
1609
|
+
if (point.y < this.bbox.ll.y) this.bbox.ll.y = point.y;
|
|
1610
|
+
if (point.x > this.bbox.ur.x) this.bbox.ur.x = point.x;
|
|
1611
|
+
if (point.y > this.bbox.ur.y) this.bbox.ur.y = point.y;
|
|
1612
|
+
prevPoint = point;
|
|
1613
|
+
}
|
|
1614
|
+
if (firstPoint.x !== prevPoint.x || firstPoint.y !== prevPoint.y) {
|
|
1615
|
+
this.segments.push(Segment.fromRing(prevPoint, firstPoint, this));
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
getSweepEvents() {
|
|
1619
|
+
const sweepEvents = [];
|
|
1620
|
+
for (let i = 0, iMax = this.segments.length; i < iMax; i++) {
|
|
1621
|
+
const segment = this.segments[i];
|
|
1622
|
+
sweepEvents.push(segment.leftSE);
|
|
1623
|
+
sweepEvents.push(segment.rightSE);
|
|
1624
|
+
}
|
|
1625
|
+
return sweepEvents;
|
|
1626
|
+
}
|
|
343
1627
|
}
|
|
344
|
-
|
|
345
|
-
|
|
1628
|
+
class PolyIn {
|
|
1629
|
+
constructor(geomPoly, multiPoly) {
|
|
1630
|
+
if (!Array.isArray(geomPoly)) {
|
|
1631
|
+
throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
|
|
1632
|
+
}
|
|
1633
|
+
this.exteriorRing = new RingIn(geomPoly[0], this, true);
|
|
1634
|
+
this.bbox = {
|
|
1635
|
+
ll: {
|
|
1636
|
+
x: this.exteriorRing.bbox.ll.x,
|
|
1637
|
+
y: this.exteriorRing.bbox.ll.y
|
|
1638
|
+
},
|
|
1639
|
+
ur: {
|
|
1640
|
+
x: this.exteriorRing.bbox.ur.x,
|
|
1641
|
+
y: this.exteriorRing.bbox.ur.y
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
this.interiorRings = [];
|
|
1645
|
+
for (let i = 1, iMax = geomPoly.length; i < iMax; i++) {
|
|
1646
|
+
const ring = new RingIn(geomPoly[i], this, false);
|
|
1647
|
+
if (ring.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = ring.bbox.ll.x;
|
|
1648
|
+
if (ring.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = ring.bbox.ll.y;
|
|
1649
|
+
if (ring.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = ring.bbox.ur.x;
|
|
1650
|
+
if (ring.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = ring.bbox.ur.y;
|
|
1651
|
+
this.interiorRings.push(ring);
|
|
1652
|
+
}
|
|
1653
|
+
this.multiPoly = multiPoly;
|
|
1654
|
+
}
|
|
1655
|
+
getSweepEvents() {
|
|
1656
|
+
const sweepEvents = this.exteriorRing.getSweepEvents();
|
|
1657
|
+
for (let i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
|
|
1658
|
+
const ringSweepEvents = this.interiorRings[i].getSweepEvents();
|
|
1659
|
+
for (let j = 0, jMax = ringSweepEvents.length; j < jMax; j++) {
|
|
1660
|
+
sweepEvents.push(ringSweepEvents[j]);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
return sweepEvents;
|
|
1664
|
+
}
|
|
346
1665
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
1666
|
+
class MultiPolyIn {
|
|
1667
|
+
constructor(geom, isSubject) {
|
|
1668
|
+
if (!Array.isArray(geom)) {
|
|
1669
|
+
throw new Error("Input geometry is not a valid Polygon or MultiPolygon");
|
|
1670
|
+
}
|
|
1671
|
+
try {
|
|
1672
|
+
if (typeof geom[0][0][0] === "number") geom = [geom];
|
|
1673
|
+
} catch (ex) {
|
|
1674
|
+
}
|
|
1675
|
+
this.polys = [];
|
|
1676
|
+
this.bbox = {
|
|
1677
|
+
ll: {
|
|
1678
|
+
x: Number.POSITIVE_INFINITY,
|
|
1679
|
+
y: Number.POSITIVE_INFINITY
|
|
1680
|
+
},
|
|
1681
|
+
ur: {
|
|
1682
|
+
x: Number.NEGATIVE_INFINITY,
|
|
1683
|
+
y: Number.NEGATIVE_INFINITY
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
for (let i = 0, iMax = geom.length; i < iMax; i++) {
|
|
1687
|
+
const poly = new PolyIn(geom[i], this);
|
|
1688
|
+
if (poly.bbox.ll.x < this.bbox.ll.x) this.bbox.ll.x = poly.bbox.ll.x;
|
|
1689
|
+
if (poly.bbox.ll.y < this.bbox.ll.y) this.bbox.ll.y = poly.bbox.ll.y;
|
|
1690
|
+
if (poly.bbox.ur.x > this.bbox.ur.x) this.bbox.ur.x = poly.bbox.ur.x;
|
|
1691
|
+
if (poly.bbox.ur.y > this.bbox.ur.y) this.bbox.ur.y = poly.bbox.ur.y;
|
|
1692
|
+
this.polys.push(poly);
|
|
1693
|
+
}
|
|
1694
|
+
this.isSubject = isSubject;
|
|
1695
|
+
}
|
|
1696
|
+
getSweepEvents() {
|
|
1697
|
+
const sweepEvents = [];
|
|
1698
|
+
for (let i = 0, iMax = this.polys.length; i < iMax; i++) {
|
|
1699
|
+
const polySweepEvents = this.polys[i].getSweepEvents();
|
|
1700
|
+
for (let j = 0, jMax = polySweepEvents.length; j < jMax; j++) {
|
|
1701
|
+
sweepEvents.push(polySweepEvents[j]);
|
|
366
1702
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
1703
|
+
}
|
|
1704
|
+
return sweepEvents;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
class RingOut {
|
|
1708
|
+
/* Given the segments from the sweep line pass, compute & return a series
|
|
1709
|
+
* of closed rings from all the segments marked to be part of the result */
|
|
1710
|
+
static factory(allSegments) {
|
|
1711
|
+
const ringsOut = [];
|
|
1712
|
+
for (let i = 0, iMax = allSegments.length; i < iMax; i++) {
|
|
1713
|
+
const segment = allSegments[i];
|
|
1714
|
+
if (!segment.isInResult() || segment.ringOut) continue;
|
|
1715
|
+
let prevEvent = null;
|
|
1716
|
+
let event = segment.leftSE;
|
|
1717
|
+
let nextEvent = segment.rightSE;
|
|
1718
|
+
const events = [event];
|
|
1719
|
+
const startingPoint = event.point;
|
|
1720
|
+
const intersectionLEs = [];
|
|
1721
|
+
while (true) {
|
|
1722
|
+
prevEvent = event;
|
|
1723
|
+
event = nextEvent;
|
|
1724
|
+
events.push(event);
|
|
1725
|
+
if (event.point === startingPoint) break;
|
|
1726
|
+
while (true) {
|
|
1727
|
+
const availableLEs = event.getAvailableLinkedEvents();
|
|
1728
|
+
if (availableLEs.length === 0) {
|
|
1729
|
+
const firstPt = events[0].point;
|
|
1730
|
+
const lastPt = events[events.length - 1].point;
|
|
1731
|
+
throw new Error(`Unable to complete output ring starting at [${firstPt.x}, ${firstPt.y}]. Last matching segment found ends at [${lastPt.x}, ${lastPt.y}].`);
|
|
1732
|
+
}
|
|
1733
|
+
if (availableLEs.length === 1) {
|
|
1734
|
+
nextEvent = availableLEs[0].otherSE;
|
|
1735
|
+
break;
|
|
1736
|
+
}
|
|
1737
|
+
let indexLE = null;
|
|
1738
|
+
for (let j = 0, jMax = intersectionLEs.length; j < jMax; j++) {
|
|
1739
|
+
if (intersectionLEs[j].point === event.point) {
|
|
1740
|
+
indexLE = j;
|
|
1741
|
+
break;
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
if (indexLE !== null) {
|
|
1745
|
+
const intersectionLE = intersectionLEs.splice(indexLE)[0];
|
|
1746
|
+
const ringEvents = events.splice(intersectionLE.index);
|
|
1747
|
+
ringEvents.unshift(ringEvents[0].otherSE);
|
|
1748
|
+
ringsOut.push(new RingOut(ringEvents.reverse()));
|
|
1749
|
+
continue;
|
|
1750
|
+
}
|
|
1751
|
+
intersectionLEs.push({
|
|
1752
|
+
index: events.length,
|
|
1753
|
+
point: event.point
|
|
1754
|
+
});
|
|
1755
|
+
const comparator = event.getLeftmostComparator(prevEvent);
|
|
1756
|
+
nextEvent = availableLEs.sort(comparator)[0].otherSE;
|
|
1757
|
+
break;
|
|
388
1758
|
}
|
|
389
|
-
u3 = "" === f2.join("").trim();
|
|
390
1759
|
}
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
1760
|
+
ringsOut.push(new RingOut(events));
|
|
1761
|
+
}
|
|
1762
|
+
return ringsOut;
|
|
1763
|
+
}
|
|
1764
|
+
constructor(events) {
|
|
1765
|
+
this.events = events;
|
|
1766
|
+
for (let i = 0, iMax = events.length; i < iMax; i++) {
|
|
1767
|
+
events[i].segment.ringOut = this;
|
|
1768
|
+
}
|
|
1769
|
+
this.poly = null;
|
|
1770
|
+
}
|
|
1771
|
+
getGeom() {
|
|
1772
|
+
let prevPt = this.events[0].point;
|
|
1773
|
+
const points = [prevPt];
|
|
1774
|
+
for (let i = 1, iMax = this.events.length - 1; i < iMax; i++) {
|
|
1775
|
+
const pt2 = this.events[i].point;
|
|
1776
|
+
const nextPt2 = this.events[i + 1].point;
|
|
1777
|
+
if (compareVectorAngles(pt2, prevPt, nextPt2) === 0) continue;
|
|
1778
|
+
points.push(pt2);
|
|
1779
|
+
prevPt = pt2;
|
|
1780
|
+
}
|
|
1781
|
+
if (points.length === 1) return null;
|
|
1782
|
+
const pt = points[0];
|
|
1783
|
+
const nextPt = points[1];
|
|
1784
|
+
if (compareVectorAngles(pt, prevPt, nextPt) === 0) points.shift();
|
|
1785
|
+
points.push(points[0]);
|
|
1786
|
+
const step = this.isExteriorRing() ? 1 : -1;
|
|
1787
|
+
const iStart = this.isExteriorRing() ? 0 : points.length - 1;
|
|
1788
|
+
const iEnd = this.isExteriorRing() ? points.length : -1;
|
|
1789
|
+
const orderedPoints = [];
|
|
1790
|
+
for (let i = iStart; i != iEnd; i += step) orderedPoints.push([points[i].x, points[i].y]);
|
|
1791
|
+
return orderedPoints;
|
|
1792
|
+
}
|
|
1793
|
+
isExteriorRing() {
|
|
1794
|
+
if (this._isExteriorRing === void 0) {
|
|
1795
|
+
const enclosing = this.enclosingRing();
|
|
1796
|
+
this._isExteriorRing = enclosing ? !enclosing.isExteriorRing() : true;
|
|
1797
|
+
}
|
|
1798
|
+
return this._isExteriorRing;
|
|
1799
|
+
}
|
|
1800
|
+
enclosingRing() {
|
|
1801
|
+
if (this._enclosingRing === void 0) {
|
|
1802
|
+
this._enclosingRing = this._calcEnclosingRing();
|
|
1803
|
+
}
|
|
1804
|
+
return this._enclosingRing;
|
|
1805
|
+
}
|
|
1806
|
+
/* Returns the ring that encloses this one, if any */
|
|
1807
|
+
_calcEnclosingRing() {
|
|
1808
|
+
let leftMostEvt = this.events[0];
|
|
1809
|
+
for (let i = 1, iMax = this.events.length; i < iMax; i++) {
|
|
1810
|
+
const evt = this.events[i];
|
|
1811
|
+
if (SweepEvent.compare(leftMostEvt, evt) > 0) leftMostEvt = evt;
|
|
1812
|
+
}
|
|
1813
|
+
let prevSeg = leftMostEvt.segment.prevInResult();
|
|
1814
|
+
let prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
|
|
1815
|
+
while (true) {
|
|
1816
|
+
if (!prevSeg) return null;
|
|
1817
|
+
if (!prevPrevSeg) return prevSeg.ringOut;
|
|
1818
|
+
if (prevPrevSeg.ringOut !== prevSeg.ringOut) {
|
|
1819
|
+
if (prevPrevSeg.ringOut.enclosingRing() !== prevSeg.ringOut) {
|
|
1820
|
+
return prevSeg.ringOut;
|
|
1821
|
+
} else return prevSeg.ringOut.enclosingRing();
|
|
1822
|
+
}
|
|
1823
|
+
prevSeg = prevPrevSeg.prevInResult();
|
|
1824
|
+
prevPrevSeg = prevSeg ? prevSeg.prevInResult() : null;
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
class PolyOut {
|
|
1829
|
+
constructor(exteriorRing) {
|
|
1830
|
+
this.exteriorRing = exteriorRing;
|
|
1831
|
+
exteriorRing.poly = this;
|
|
1832
|
+
this.interiorRings = [];
|
|
1833
|
+
}
|
|
1834
|
+
addInterior(ring) {
|
|
1835
|
+
this.interiorRings.push(ring);
|
|
1836
|
+
ring.poly = this;
|
|
1837
|
+
}
|
|
1838
|
+
getGeom() {
|
|
1839
|
+
const geom = [this.exteriorRing.getGeom()];
|
|
1840
|
+
if (geom[0] === null) return null;
|
|
1841
|
+
for (let i = 0, iMax = this.interiorRings.length; i < iMax; i++) {
|
|
1842
|
+
const ringGeom = this.interiorRings[i].getGeom();
|
|
1843
|
+
if (ringGeom === null) continue;
|
|
1844
|
+
geom.push(ringGeom);
|
|
1845
|
+
}
|
|
1846
|
+
return geom;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
class MultiPolyOut {
|
|
1850
|
+
constructor(rings) {
|
|
1851
|
+
this.rings = rings;
|
|
1852
|
+
this.polys = this._composePolys(rings);
|
|
1853
|
+
}
|
|
1854
|
+
getGeom() {
|
|
1855
|
+
const geom = [];
|
|
1856
|
+
for (let i = 0, iMax = this.polys.length; i < iMax; i++) {
|
|
1857
|
+
const polyGeom = this.polys[i].getGeom();
|
|
1858
|
+
if (polyGeom === null) continue;
|
|
1859
|
+
geom.push(polyGeom);
|
|
1860
|
+
}
|
|
1861
|
+
return geom;
|
|
1862
|
+
}
|
|
1863
|
+
_composePolys(rings) {
|
|
1864
|
+
const polys = [];
|
|
1865
|
+
for (let i = 0, iMax = rings.length; i < iMax; i++) {
|
|
1866
|
+
const ring = rings[i];
|
|
1867
|
+
if (ring.poly) continue;
|
|
1868
|
+
if (ring.isExteriorRing()) polys.push(new PolyOut(ring));
|
|
1869
|
+
else {
|
|
1870
|
+
const enclosingRing = ring.enclosingRing();
|
|
1871
|
+
if (!enclosingRing.poly) polys.push(new PolyOut(enclosingRing));
|
|
1872
|
+
enclosingRing.poly.addInterior(ring);
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
return polys;
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
class SweepLine {
|
|
1879
|
+
constructor(queue) {
|
|
1880
|
+
let comparator = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : Segment.compare;
|
|
1881
|
+
this.queue = queue;
|
|
1882
|
+
this.tree = new Tree(comparator);
|
|
1883
|
+
this.segments = [];
|
|
1884
|
+
}
|
|
1885
|
+
process(event) {
|
|
1886
|
+
const segment = event.segment;
|
|
1887
|
+
const newEvents = [];
|
|
1888
|
+
if (event.consumedBy) {
|
|
1889
|
+
if (event.isLeft) this.queue.remove(event.otherSE);
|
|
1890
|
+
else this.tree.remove(segment);
|
|
1891
|
+
return newEvents;
|
|
1892
|
+
}
|
|
1893
|
+
const node = event.isLeft ? this.tree.add(segment) : this.tree.find(segment);
|
|
1894
|
+
if (!node) throw new Error(`Unable to find segment #${segment.id} [${segment.leftSE.point.x}, ${segment.leftSE.point.y}] -> [${segment.rightSE.point.x}, ${segment.rightSE.point.y}] in SweepLine tree.`);
|
|
1895
|
+
let prevNode = node;
|
|
1896
|
+
let nextNode = node;
|
|
1897
|
+
let prevSeg = void 0;
|
|
1898
|
+
let nextSeg = void 0;
|
|
1899
|
+
while (prevSeg === void 0) {
|
|
1900
|
+
prevNode = this.tree.prev(prevNode);
|
|
1901
|
+
if (prevNode === null) prevSeg = null;
|
|
1902
|
+
else if (prevNode.key.consumedBy === void 0) prevSeg = prevNode.key;
|
|
1903
|
+
}
|
|
1904
|
+
while (nextSeg === void 0) {
|
|
1905
|
+
nextNode = this.tree.next(nextNode);
|
|
1906
|
+
if (nextNode === null) nextSeg = null;
|
|
1907
|
+
else if (nextNode.key.consumedBy === void 0) nextSeg = nextNode.key;
|
|
1908
|
+
}
|
|
1909
|
+
if (event.isLeft) {
|
|
1910
|
+
let prevMySplitter = null;
|
|
1911
|
+
if (prevSeg) {
|
|
1912
|
+
const prevInter = prevSeg.getIntersection(segment);
|
|
1913
|
+
if (prevInter !== null) {
|
|
1914
|
+
if (!segment.isAnEndpoint(prevInter)) prevMySplitter = prevInter;
|
|
1915
|
+
if (!prevSeg.isAnEndpoint(prevInter)) {
|
|
1916
|
+
const newEventsFromSplit = this._splitSafely(prevSeg, prevInter);
|
|
1917
|
+
for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
|
|
1918
|
+
newEvents.push(newEventsFromSplit[i]);
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
let nextMySplitter = null;
|
|
1924
|
+
if (nextSeg) {
|
|
1925
|
+
const nextInter = nextSeg.getIntersection(segment);
|
|
1926
|
+
if (nextInter !== null) {
|
|
1927
|
+
if (!segment.isAnEndpoint(nextInter)) nextMySplitter = nextInter;
|
|
1928
|
+
if (!nextSeg.isAnEndpoint(nextInter)) {
|
|
1929
|
+
const newEventsFromSplit = this._splitSafely(nextSeg, nextInter);
|
|
1930
|
+
for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
|
|
1931
|
+
newEvents.push(newEventsFromSplit[i]);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
if (prevMySplitter !== null || nextMySplitter !== null) {
|
|
1937
|
+
let mySplitter = null;
|
|
1938
|
+
if (prevMySplitter === null) mySplitter = nextMySplitter;
|
|
1939
|
+
else if (nextMySplitter === null) mySplitter = prevMySplitter;
|
|
1940
|
+
else {
|
|
1941
|
+
const cmpSplitters = SweepEvent.comparePoints(prevMySplitter, nextMySplitter);
|
|
1942
|
+
mySplitter = cmpSplitters <= 0 ? prevMySplitter : nextMySplitter;
|
|
1943
|
+
}
|
|
1944
|
+
this.queue.remove(segment.rightSE);
|
|
1945
|
+
newEvents.push(segment.rightSE);
|
|
1946
|
+
const newEventsFromSplit = segment.split(mySplitter);
|
|
1947
|
+
for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
|
|
1948
|
+
newEvents.push(newEventsFromSplit[i]);
|
|
396
1949
|
}
|
|
397
|
-
o3 < t2.length - 1 && (!i3 || 0 < h3 && !d2) && (r3 += y2);
|
|
398
1950
|
}
|
|
1951
|
+
if (newEvents.length > 0) {
|
|
1952
|
+
this.tree.remove(segment);
|
|
1953
|
+
newEvents.push(event);
|
|
1954
|
+
} else {
|
|
1955
|
+
this.segments.push(segment);
|
|
1956
|
+
segment.prev = prevSeg;
|
|
1957
|
+
}
|
|
1958
|
+
} else {
|
|
1959
|
+
if (prevSeg && nextSeg) {
|
|
1960
|
+
const inter = prevSeg.getIntersection(nextSeg);
|
|
1961
|
+
if (inter !== null) {
|
|
1962
|
+
if (!prevSeg.isAnEndpoint(inter)) {
|
|
1963
|
+
const newEventsFromSplit = this._splitSafely(prevSeg, inter);
|
|
1964
|
+
for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
|
|
1965
|
+
newEvents.push(newEventsFromSplit[i]);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
if (!nextSeg.isAnEndpoint(inter)) {
|
|
1969
|
+
const newEventsFromSplit = this._splitSafely(nextSeg, inter);
|
|
1970
|
+
for (let i = 0, iMax = newEventsFromSplit.length; i < iMax; i++) {
|
|
1971
|
+
newEvents.push(newEventsFromSplit[i]);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
this.tree.remove(segment);
|
|
399
1977
|
}
|
|
400
|
-
return
|
|
1978
|
+
return newEvents;
|
|
401
1979
|
}
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
1980
|
+
/* Safely split a segment that is currently in the datastructures
|
|
1981
|
+
* IE - a segment other than the one that is currently being processed. */
|
|
1982
|
+
_splitSafely(seg, pt) {
|
|
1983
|
+
this.tree.remove(seg);
|
|
1984
|
+
const rightSE = seg.rightSE;
|
|
1985
|
+
this.queue.remove(rightSE);
|
|
1986
|
+
const newEvents = seg.split(pt);
|
|
1987
|
+
newEvents.push(rightSE);
|
|
1988
|
+
if (seg.consumedBy === void 0) this.tree.add(seg);
|
|
1989
|
+
return newEvents;
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
const POLYGON_CLIPPING_MAX_QUEUE_SIZE = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE || 1e6;
|
|
1993
|
+
const POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS = typeof process !== "undefined" && process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS || 1e6;
|
|
1994
|
+
class Operation {
|
|
1995
|
+
run(type, geom, moreGeoms) {
|
|
1996
|
+
operation.type = type;
|
|
1997
|
+
rounder.reset();
|
|
1998
|
+
const multipolys = [new MultiPolyIn(geom, true)];
|
|
1999
|
+
for (let i = 0, iMax = moreGeoms.length; i < iMax; i++) {
|
|
2000
|
+
multipolys.push(new MultiPolyIn(moreGeoms[i], false));
|
|
2001
|
+
}
|
|
2002
|
+
operation.numMultiPolys = multipolys.length;
|
|
2003
|
+
if (operation.type === "difference") {
|
|
2004
|
+
const subject = multipolys[0];
|
|
2005
|
+
let i = 1;
|
|
2006
|
+
while (i < multipolys.length) {
|
|
2007
|
+
if (getBboxOverlap(multipolys[i].bbox, subject.bbox) !== null) i++;
|
|
2008
|
+
else multipolys.splice(i, 1);
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
if (operation.type === "intersection") {
|
|
2012
|
+
for (let i = 0, iMax = multipolys.length; i < iMax; i++) {
|
|
2013
|
+
const mpA = multipolys[i];
|
|
2014
|
+
for (let j = i + 1, jMax = multipolys.length; j < jMax; j++) {
|
|
2015
|
+
if (getBboxOverlap(mpA.bbox, multipolys[j].bbox) === null) return [];
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
const queue = new Tree(SweepEvent.compare);
|
|
2020
|
+
for (let i = 0, iMax = multipolys.length; i < iMax; i++) {
|
|
2021
|
+
const sweepEvents = multipolys[i].getSweepEvents();
|
|
2022
|
+
for (let j = 0, jMax = sweepEvents.length; j < jMax; j++) {
|
|
2023
|
+
queue.insert(sweepEvents[j]);
|
|
2024
|
+
if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {
|
|
2025
|
+
throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).");
|
|
2026
|
+
}
|
|
426
2027
|
}
|
|
427
|
-
var a2 = n2.instanceConfig.complete;
|
|
428
|
-
n2.instanceConfig.complete = function(e3) {
|
|
429
|
-
U(a2) && a2(e3, n2.file, n2.inputElem), u2();
|
|
430
|
-
}, v.parse(n2.file, n2.instanceConfig);
|
|
431
2028
|
}
|
|
2029
|
+
const sweepLine = new SweepLine(queue);
|
|
2030
|
+
let prevQueueSize = queue.size;
|
|
2031
|
+
let node = queue.pop();
|
|
2032
|
+
while (node) {
|
|
2033
|
+
const evt = node.key;
|
|
2034
|
+
if (queue.size === prevQueueSize) {
|
|
2035
|
+
const seg = evt.segment;
|
|
2036
|
+
throw new Error(`Unable to pop() ${evt.isLeft ? "left" : "right"} SweepEvent [${evt.point.x}, ${evt.point.y}] from segment #${seg.id} [${seg.leftSE.point.x}, ${seg.leftSE.point.y}] -> [${seg.rightSE.point.x}, ${seg.rightSE.point.y}] from queue.`);
|
|
2037
|
+
}
|
|
2038
|
+
if (queue.size > POLYGON_CLIPPING_MAX_QUEUE_SIZE) {
|
|
2039
|
+
throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");
|
|
2040
|
+
}
|
|
2041
|
+
if (sweepLine.segments.length > POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS) {
|
|
2042
|
+
throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");
|
|
2043
|
+
}
|
|
2044
|
+
const newEvents = sweepLine.process(evt);
|
|
2045
|
+
for (let i = 0, iMax = newEvents.length; i < iMax; i++) {
|
|
2046
|
+
const evt2 = newEvents[i];
|
|
2047
|
+
if (evt2.consumedBy === void 0) queue.insert(evt2);
|
|
2048
|
+
}
|
|
2049
|
+
prevQueueSize = queue.size;
|
|
2050
|
+
node = queue.pop();
|
|
2051
|
+
}
|
|
2052
|
+
rounder.reset();
|
|
2053
|
+
const ringsOut = RingOut.factory(sweepLine.segments);
|
|
2054
|
+
const result = new MultiPolyOut(ringsOut);
|
|
2055
|
+
return result.getGeom();
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
const operation = new Operation();
|
|
2059
|
+
const union = function(geom) {
|
|
2060
|
+
for (var _len = arguments.length, moreGeoms = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
|
2061
|
+
moreGeoms[_key - 1] = arguments[_key];
|
|
2062
|
+
}
|
|
2063
|
+
return operation.run("union", geom, moreGeoms);
|
|
2064
|
+
};
|
|
2065
|
+
const intersection = function(geom) {
|
|
2066
|
+
for (var _len2 = arguments.length, moreGeoms = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
|
|
2067
|
+
moreGeoms[_key2 - 1] = arguments[_key2];
|
|
2068
|
+
}
|
|
2069
|
+
return operation.run("intersection", geom, moreGeoms);
|
|
2070
|
+
};
|
|
2071
|
+
const xor = function(geom) {
|
|
2072
|
+
for (var _len3 = arguments.length, moreGeoms = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
|
|
2073
|
+
moreGeoms[_key3 - 1] = arguments[_key3];
|
|
432
2074
|
}
|
|
433
|
-
|
|
434
|
-
|
|
2075
|
+
return operation.run("xor", geom, moreGeoms);
|
|
2076
|
+
};
|
|
2077
|
+
const difference = function(subjectGeom) {
|
|
2078
|
+
for (var _len4 = arguments.length, clippingGeoms = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
|
|
2079
|
+
clippingGeoms[_key4 - 1] = arguments[_key4];
|
|
435
2080
|
}
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
2081
|
+
return operation.run("difference", subjectGeom, clippingGeoms);
|
|
2082
|
+
};
|
|
2083
|
+
var index = {
|
|
2084
|
+
union,
|
|
2085
|
+
intersection,
|
|
2086
|
+
xor,
|
|
2087
|
+
difference
|
|
2088
|
+
};
|
|
2089
|
+
return index;
|
|
441
2090
|
});
|
|
442
2091
|
}
|
|
443
2092
|
});
|
|
444
2093
|
|
|
445
|
-
// ../hem-target-runtime/src/hem/
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
2094
|
+
// ../hem-target-runtime/src/hem/epc_design_heat_loss.py?raw
|
|
2095
|
+
var require_epc_design_heat_loss = __commonJS({
|
|
2096
|
+
"../hem-target-runtime/src/hem/epc_design_heat_loss.py?raw"(exports, module) {
|
|
2097
|
+
module.exports = `# SPDX-FileCopyrightText: 2026 Home Energy Foundry Limited and contributors
|
|
2098
|
+
# SPDX-License-Identifier: AGPL-3.0-only
|
|
2099
|
+
# This file is subject to Vulcan Origin Terms v1.0; see scripts/hem-targets/licensing/ADDITIONAL_TERMS.md.
|
|
2100
|
+
"""Static design heat loss of a HEM:EPC core input (the wrapper's preproc.json).
|
|
2101
|
+
|
|
2102
|
+
The Python HEM Core's own calc_HTC_HLP (hem_core/project.py), the function behind the
|
|
2103
|
+
results_static "Heat transfer coefficient" row. No simulation runs. Same contract and method as
|
|
2104
|
+
hem-target-core/src/design_heat_loss.rs: the engine only returns a total per zone, so thermal
|
|
2105
|
+
bridging and fabric are isolated by rerunning it with each zeroed (ventilation reads element
|
|
2106
|
+
geometry, never U-values or resistances).
|
|
2107
|
+
"""
|
|
2108
|
+
import copy
|
|
2109
|
+
import json
|
|
2110
|
+
|
|
2111
|
+
from hem_core.project import calc_HTC_HLP
|
|
2112
|
+
|
|
2113
|
+
|
|
2114
|
+
def _zone_htcs(model):
|
|
2115
|
+
# calc_HTC_HLP writes derived values into the elements it reads.
|
|
2116
|
+
return calc_HTC_HLP(copy.deepcopy(model))[2]
|
|
2117
|
+
|
|
2118
|
+
|
|
2119
|
+
def vulcan_design_heat_loss(model):
|
|
2120
|
+
temperatures = (model.get("ExternalConditions") or {}).get("air_temperatures")
|
|
2121
|
+
if not temperatures:
|
|
2122
|
+
raise ValueError("No weather data: the core input has no air temperatures")
|
|
2123
|
+
if "temp_internal_air_static_calcs" not in model:
|
|
2124
|
+
raise ValueError("The core input has no temp_internal_air_static_calcs")
|
|
2125
|
+
# The internal air temperature of the engine's own static calculation. The EPC wrapper sets
|
|
2126
|
+
# it to 21 (epc_wrapper/models/input.py temp_internal_air_static_calcs), as FHS's 21/20 max.
|
|
2127
|
+
setpoint = model["temp_internal_air_static_calcs"]
|
|
2128
|
+
coldest = min(temperatures)
|
|
2129
|
+
|
|
2130
|
+
total = _zone_htcs(model)
|
|
2131
|
+
model = copy.deepcopy(model)
|
|
2132
|
+
for zone in model["Zone"].values():
|
|
2133
|
+
zone["ThermalBridging"] = 0.0
|
|
2134
|
+
without_bridges = _zone_htcs(model)
|
|
2135
|
+
for zone in model["Zone"].values():
|
|
2136
|
+
for element in zone["BuildingElement"].values():
|
|
2137
|
+
if element["type"] == "BuildingElementGround":
|
|
2138
|
+
# Ground loss is area x u_value; the Core also converts u_value to a resistance,
|
|
2139
|
+
# so it cannot be exactly 0.
|
|
2140
|
+
element["u_value"] = 1e-300
|
|
2141
|
+
elif element.pop("u_value", None) is not None or "thermal_resistance_construction" in element:
|
|
2142
|
+
# U = 1/(R + Rsi + Rse) ~ 1e-300 W/m2K: fabric loss vanishes.
|
|
2143
|
+
element["thermal_resistance_construction"] = 1e300
|
|
2144
|
+
ventilation_only = _zone_htcs(model)
|
|
2145
|
+
|
|
2146
|
+
return {
|
|
2147
|
+
"coldestHourC": coldest,
|
|
2148
|
+
"setpointC": setpoint,
|
|
2149
|
+
"zones": {
|
|
2150
|
+
name: {
|
|
2151
|
+
"htcWPerK": htc,
|
|
2152
|
+
"fabricWPerK": without_bridges[name] - ventilation_only[name],
|
|
2153
|
+
"thermalBridgesWPerK": htc - without_bridges[name],
|
|
2154
|
+
"ventilationWPerK": ventilation_only[name],
|
|
2155
|
+
"designLossKw": htc * (setpoint - coldest) / 1000.0,
|
|
2156
|
+
}
|
|
2157
|
+
for name, htc in total.items()
|
|
2158
|
+
},
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
|
|
2162
|
+
def vulcan_design_heat_loss_file(path):
|
|
2163
|
+
"""The JSON contract for the core input at \`path\`."""
|
|
2164
|
+
with open(path) as file:
|
|
2165
|
+
return json.dumps(vulcan_design_heat_loss(json.load(file)))
|
|
2166
|
+
`;
|
|
2167
|
+
}
|
|
2168
|
+
});
|
|
2169
|
+
|
|
2170
|
+
// ../community/packages/geometry-editor/src/lib/issueTarget.ts
|
|
2171
|
+
var issuePathSegments = (path) => (path ?? "").split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
2172
|
+
|
|
2173
|
+
// ../community/packages/geometry-editor/src/lib/hemieFabric.ts
|
|
2174
|
+
var ENGLAND_AREAS = new Set("AL B BA BB BD BH BL BN BR BS CB CM CO CR CT CV CW DA DE DH DL DN DT DY E EC EN EX FY GL GU HA HD HG HP HU HX IG IP KT L LA LE LN LS LU M ME MK N NE NG NN NR NW OL OX PE PL PO PR RG RH RM S SE SG SK SL SM SN SO SP SR SS ST SW TA TF TN TQ TR TS TW UB W WA WC WD WF WN WR WS WV YO".split(" "));
|
|
2175
|
+
var HEMIE_NATION = "HEMIE_nation";
|
|
2176
|
+
var ROOF_DETAILS = ["ceiling_thickness", "ceiling_thermal_conductivity", "joist_depth", "percentage_area_of_timber_joists", "insulation_thermal_conductivity"];
|
|
2177
|
+
var LOFT_DETAILS = [...ROOF_DETAILS, "rafter_depth", "percentage_area_of_timber_rafters", "roof_characteristics", "air_gap_thermal_resistance"];
|
|
2178
|
+
var WALL_FINISHES = {
|
|
2179
|
+
Brick: "BrickFinish",
|
|
2180
|
+
Render: "RenderFinish",
|
|
2181
|
+
Timber: "TimberFinish",
|
|
2182
|
+
"Metal (uncoated)": "MetalUncoatedFinish",
|
|
2183
|
+
"Metal (coated)": "MetalCoatedFinish",
|
|
2184
|
+
"Fibre-cement": "FibreCementWallFinish",
|
|
2185
|
+
"Composite panels (metal skins)": "CompositePanelsFinish"
|
|
2186
|
+
};
|
|
2187
|
+
var ROOF_FINISHES = {
|
|
2188
|
+
"Concrete roof tile": "ConcreteRoofTileFinish",
|
|
2189
|
+
"Clay tile": "ClayTileFinish",
|
|
2190
|
+
Slate: "SlateFinish",
|
|
2191
|
+
Asphalt: "AsphaltFinish",
|
|
2192
|
+
Timber: "TimberFinish",
|
|
2193
|
+
"Metal (uncoated)": "MetalUncoatedFinish",
|
|
2194
|
+
"Metal (coated)": "MetalCoatedFinish",
|
|
2195
|
+
"Fibre-cement": "FibreCementRoofFinish",
|
|
2196
|
+
"Composite panels (metal skins)": "CompositePanelsFinish"
|
|
2197
|
+
};
|
|
2198
|
+
var DOOR_FINISHES = {
|
|
2199
|
+
Timber: "TimberFinish",
|
|
2200
|
+
"Metal (uncoated)": "MetalUncoatedFinish",
|
|
2201
|
+
"Metal (coated)": "MetalCoatedFinish",
|
|
2202
|
+
"Composite panels (metal skins)": "CompositePanelsFinish"
|
|
2203
|
+
};
|
|
2204
|
+
var PARK_HOME_WALL_FINISHES = {
|
|
2205
|
+
"uPVC vinyl / Plastic": "ParkHomePlasticFinish",
|
|
2206
|
+
"Stucco / Aggregate paint": "ParkHomePaintFinish",
|
|
2207
|
+
"Timber / Wood cladding": "ParkHomeTimberFinish",
|
|
2208
|
+
"CanExel / Engineered HDF": "ParkHomeHDFFinish"
|
|
2209
|
+
};
|
|
2210
|
+
var SURFACE_FINISHES = {
|
|
2211
|
+
external_wall: WALL_FINISHES,
|
|
2212
|
+
external_door: DOOR_FINISHES,
|
|
2213
|
+
park_home_wall: PARK_HOME_WALL_FINISHES,
|
|
2214
|
+
flat_roof: ROOF_FINISHES,
|
|
2215
|
+
unheated_pitched_roof: ROOF_FINISHES,
|
|
2216
|
+
heated_pitched_roof: ROOF_FINISHES,
|
|
2217
|
+
mini_flat_roof: ROOF_FINISHES,
|
|
2218
|
+
mini_pitched_roof: ROOF_FINISHES,
|
|
2219
|
+
park_home_flat_roof: ROOF_FINISHES,
|
|
2220
|
+
park_home_pitched_roof: ROOF_FINISHES
|
|
2221
|
+
};
|
|
2222
|
+
var OUTSIDE_SURFACE_TYPES = /* @__PURE__ */ new Set([...Object.keys(SURFACE_FINISHES), "above_external_area_floor", "park_home_floor", "thatched_roof"]);
|
|
2223
|
+
var words = (value) => value.charAt(0).toUpperCase() + value.slice(1).replace(/_/g, " ");
|
|
2224
|
+
var CONSTRUCTION_TYPE_LABELS = {
|
|
2225
|
+
not_edge_insulated_ground_attached_floor: "Ground floor, no edge insulation",
|
|
2226
|
+
edge_insulated_ground_attached_floor: "Ground floor, edge insulated"
|
|
2227
|
+
};
|
|
2228
|
+
var hemieConstructionTypeLabel = (type) => CONSTRUCTION_TYPE_LABELS[type] ?? words(type);
|
|
2229
|
+
|
|
2230
|
+
// ../community/packages/geometry-editor/src/lib/zoneDerivation.ts
|
|
2231
|
+
var import_polygon_clipping2 = __toESM(require_polygon_clipping_umd(), 1);
|
|
2232
|
+
|
|
2233
|
+
// ../community/packages/geometry-editor/src/lib/polygonSync.ts
|
|
2234
|
+
var import_polygon_clipping = __toESM(require_polygon_clipping_umd(), 1);
|
|
2235
|
+
|
|
2236
|
+
// ../community/packages/geometry-editor/src/lib/roofCutouts.ts
|
|
2237
|
+
var import_polygon_clipping4 = __toESM(require_polygon_clipping_umd(), 1);
|
|
2238
|
+
|
|
2239
|
+
// ../community/packages/geometry-editor/src/lib/geometry3dMapper.ts
|
|
2240
|
+
var import_polygon_clipping3 = __toESM(require_polygon_clipping_umd(), 1);
|
|
2241
|
+
|
|
2242
|
+
// ../community/packages/geometry-editor/src/lib/assemblyCalculator.ts
|
|
2243
|
+
var H_RI = 5.13;
|
|
2244
|
+
var H_CI_UPWARDS = 5;
|
|
2245
|
+
var H_CI_HORIZONTAL = 2.5;
|
|
2246
|
+
var H_CI_DOWNWARDS = 0.7;
|
|
2247
|
+
var H_CE = 20;
|
|
2248
|
+
var H_RE = 4.14;
|
|
2249
|
+
var R_SI_HORIZONTAL = 1 / (H_RI + H_CI_HORIZONTAL);
|
|
2250
|
+
var R_SI_UPWARDS = 1 / (H_RI + H_CI_UPWARDS);
|
|
2251
|
+
var R_SI_DOWNWARDS = 1 / (H_RI + H_CI_DOWNWARDS);
|
|
2252
|
+
var R_SE = 1 / (H_CE + H_RE);
|
|
2253
|
+
|
|
2254
|
+
// ../community/packages/geometry-editor/src/lib/assemblyMassHeuristic.ts
|
|
2255
|
+
var FHS_MASS_DISTRIBUTION_CLASS_BY_CODE = {
|
|
2256
|
+
I: "I: Mass concentrated at internal side",
|
|
2257
|
+
E: "E: Mass concentrated at external side",
|
|
2258
|
+
IE: "IE: Mass divided over internal and external side",
|
|
2259
|
+
D: "D: Mass equally distributed",
|
|
2260
|
+
M: "M: Mass concentrated inside"
|
|
2261
|
+
};
|
|
2262
|
+
var FHS_MASS_DISTRIBUTION_CLASS_VALUES = new Set(
|
|
2263
|
+
Object.values(FHS_MASS_DISTRIBUTION_CLASS_BY_CODE)
|
|
2264
|
+
);
|
|
2265
|
+
|
|
2266
|
+
// ../community/packages/geometry-editor/src/lib/assemblyAppliedUi.ts
|
|
2267
|
+
var MASS_CLASS_MEANINGS = {
|
|
2268
|
+
I: "Mass mainly on the room side (e.g. external insulation).",
|
|
2269
|
+
E: "Mass mainly on the external side (e.g. internal insulation).",
|
|
2270
|
+
IE: "Mass on both sides of the insulation (e.g. filled cavity).",
|
|
2271
|
+
D: "Evenly distributed or negligible mass (e.g. uninsulated solid, lightweight).",
|
|
2272
|
+
M: "Mass near the middle (insulation both sides of the structural leaf)."
|
|
2273
|
+
};
|
|
2274
|
+
var FHS_MASS_CLASS_COMMENTARY = {
|
|
2275
|
+
"I: Mass concentrated at internal side": MASS_CLASS_MEANINGS.I,
|
|
2276
|
+
"E: Mass concentrated at external side": MASS_CLASS_MEANINGS.E,
|
|
2277
|
+
"IE: Mass divided over internal and external side": MASS_CLASS_MEANINGS.IE,
|
|
2278
|
+
"D: Mass equally distributed": MASS_CLASS_MEANINGS.D,
|
|
2279
|
+
"M: Mass concentrated inside": MASS_CLASS_MEANINGS.M
|
|
2280
|
+
};
|
|
2281
|
+
|
|
2282
|
+
// ../community/packages/geometry-editor-host/src/schemaPort.ts
|
|
2283
|
+
var A7_AREAL_HEAT_CAPACITY_INPUT = Object.freeze({ classes: "surface", numberTypes: Object.freeze([]) });
|
|
2284
|
+
function unavailable(operation) {
|
|
2285
|
+
throw new Error(`Geometry schema ${operation} is unavailable`);
|
|
2286
|
+
}
|
|
2287
|
+
var unavailableGeometrySchemaPort = Object.freeze({
|
|
2288
|
+
availability: "unavailable",
|
|
2289
|
+
preload: async () => unavailable("preload"),
|
|
2290
|
+
getRootSchema: () => unavailable("root lookup"),
|
|
2291
|
+
getElementSubschema: () => unavailable("element lookup"),
|
|
2292
|
+
getBaseFieldsForElementType: () => unavailable("base-field lookup"),
|
|
2293
|
+
getApplianceKeys: () => unavailable("appliance-key lookup"),
|
|
2294
|
+
getStrictestIntegerKeysForElementType: () => unavailable("numeric-typing lookup"),
|
|
2295
|
+
getSchemaSubtypeForElementData: () => unavailable("subtype lookup"),
|
|
2296
|
+
getConditionalRequiredFields: () => unavailable("conditional-required lookup"),
|
|
2297
|
+
validateProperty: () => unavailable("property validation"),
|
|
2298
|
+
findParameter: () => unavailable("parameter lookup")
|
|
2299
|
+
});
|
|
2300
|
+
|
|
2301
|
+
// ../community/packages/geometry-editor/src/lib/overrideProvenance.ts
|
|
2302
|
+
var SLOPED_WIDTH_OVERRIDE_DESCRIPTOR = {
|
|
2303
|
+
flag: "_widthUserOverride",
|
|
2304
|
+
key: "_width_user_override",
|
|
2305
|
+
positiveSense: true,
|
|
2306
|
+
since: 1
|
|
2307
|
+
};
|
|
2308
|
+
var SLOPED_HEIGHT_OVERRIDE_DESCRIPTOR = {
|
|
2309
|
+
flag: "_heightUserOverride",
|
|
2310
|
+
key: "_height_user_override",
|
|
2311
|
+
positiveSense: true,
|
|
2312
|
+
since: 1
|
|
2313
|
+
};
|
|
2314
|
+
var PV_BASE_HEIGHT_OVERRIDE_DESCRIPTOR = {
|
|
2315
|
+
flag: "_baseHeightUserOverride",
|
|
2316
|
+
key: "_pv_base_height_user_override",
|
|
2317
|
+
positiveSense: true,
|
|
2318
|
+
since: 1
|
|
2319
|
+
};
|
|
2320
|
+
var PV_PITCH_OVERRIDE_DESCRIPTOR = {
|
|
2321
|
+
flag: "_pitchUserOverride",
|
|
2322
|
+
key: "_pv_pitch_user_override",
|
|
2323
|
+
positiveSense: true,
|
|
2324
|
+
since: 1
|
|
2325
|
+
};
|
|
2326
|
+
var PV_ORIENTATION_OVERRIDE_DESCRIPTOR = {
|
|
2327
|
+
flag: "_orientationUserOverride",
|
|
2328
|
+
key: "_pv_orientation_user_override",
|
|
2329
|
+
positiveSense: true,
|
|
2330
|
+
since: 1
|
|
2331
|
+
};
|
|
2332
|
+
var ELEMENT_NAME_AUTO_SYNC_DESCRIPTOR = {
|
|
2333
|
+
flag: "_nameAutoSync",
|
|
2334
|
+
key: "_name_auto_sync",
|
|
2335
|
+
positiveSense: false,
|
|
2336
|
+
since: 1,
|
|
2337
|
+
absentIsAuthoritative: false
|
|
2338
|
+
};
|
|
2339
|
+
var GROUND_TOTAL_AREA_OVERRIDE_DESCRIPTOR = {
|
|
2340
|
+
flag: "_totalAreaUserOverride",
|
|
2341
|
+
key: "_ground_total_area_manual",
|
|
2342
|
+
positiveSense: true,
|
|
2343
|
+
since: 2
|
|
2344
|
+
};
|
|
2345
|
+
var WINDOW_SECURITY_RISK_OVERRIDE_DESCRIPTOR = {
|
|
2346
|
+
flag: "_windowSecurityRiskUserOverride",
|
|
2347
|
+
key: "_window_security_risk_user_override",
|
|
2348
|
+
positiveSense: true,
|
|
2349
|
+
since: 3
|
|
2350
|
+
};
|
|
2351
|
+
var ZONE_FLOOR_AREA_OVERRIDE_DESCRIPTOR = {
|
|
2352
|
+
flag: "_floorAreaUserOverride",
|
|
2353
|
+
key: "_floor_area_user_override",
|
|
2354
|
+
positiveSense: true,
|
|
2355
|
+
since: 1
|
|
2356
|
+
};
|
|
2357
|
+
var ZONE_HEIGHT_OVERRIDE_DESCRIPTOR = {
|
|
2358
|
+
flag: "_heightUserOverride",
|
|
2359
|
+
key: "_height_user_override",
|
|
2360
|
+
positiveSense: true,
|
|
2361
|
+
since: 1
|
|
2362
|
+
};
|
|
2363
|
+
var FLOOR_HEIGHT_OVERRIDE_DESCRIPTOR = {
|
|
2364
|
+
flag: "heightUserOverride",
|
|
2365
|
+
key: "FloorHeightOverride",
|
|
2366
|
+
positiveSense: true,
|
|
2367
|
+
since: 0
|
|
2368
|
+
};
|
|
2369
|
+
var FLOOR_BASE_HEIGHT_OVERRIDE_DESCRIPTOR = {
|
|
2370
|
+
flag: "baseHeightUserOverride",
|
|
2371
|
+
key: "FloorBaseHeightOverride",
|
|
2372
|
+
positiveSense: true,
|
|
2373
|
+
since: 0
|
|
2374
|
+
};
|
|
2375
|
+
var SPACE_LABEL_NAME_AUTO_SYNC_DESCRIPTOR = {
|
|
2376
|
+
flag: "_nameAutoSync",
|
|
2377
|
+
key: "_name_auto_sync",
|
|
2378
|
+
positiveSense: false,
|
|
2379
|
+
since: 1,
|
|
2380
|
+
absentIsAuthoritative: false
|
|
2381
|
+
};
|
|
2382
|
+
var OVERRIDE_PROVENANCE_REGISTRY = {
|
|
2383
|
+
element: [
|
|
2384
|
+
SLOPED_WIDTH_OVERRIDE_DESCRIPTOR,
|
|
2385
|
+
SLOPED_HEIGHT_OVERRIDE_DESCRIPTOR,
|
|
2386
|
+
PV_BASE_HEIGHT_OVERRIDE_DESCRIPTOR,
|
|
2387
|
+
PV_PITCH_OVERRIDE_DESCRIPTOR,
|
|
2388
|
+
PV_ORIENTATION_OVERRIDE_DESCRIPTOR,
|
|
2389
|
+
ELEMENT_NAME_AUTO_SYNC_DESCRIPTOR,
|
|
2390
|
+
GROUND_TOTAL_AREA_OVERRIDE_DESCRIPTOR,
|
|
2391
|
+
WINDOW_SECURITY_RISK_OVERRIDE_DESCRIPTOR
|
|
2392
|
+
],
|
|
2393
|
+
zone: [
|
|
2394
|
+
ZONE_FLOOR_AREA_OVERRIDE_DESCRIPTOR,
|
|
2395
|
+
ZONE_HEIGHT_OVERRIDE_DESCRIPTOR
|
|
2396
|
+
],
|
|
2397
|
+
floor: [FLOOR_HEIGHT_OVERRIDE_DESCRIPTOR, FLOOR_BASE_HEIGHT_OVERRIDE_DESCRIPTOR],
|
|
2398
|
+
spaceLabel: [SPACE_LABEL_NAME_AUTO_SYNC_DESCRIPTOR]
|
|
2399
|
+
};
|
|
2400
|
+
var EXTRA_JSON_OVERRIDE_MARKER_KEYS = [
|
|
2401
|
+
...new Set([
|
|
2402
|
+
...OVERRIDE_PROVENANCE_REGISTRY.element,
|
|
2403
|
+
...OVERRIDE_PROVENANCE_REGISTRY.spaceLabel
|
|
2404
|
+
].map((descriptor) => descriptor.key))
|
|
2405
|
+
];
|
|
2406
|
+
|
|
2407
|
+
// ../community/packages/geometry-editor/src/lib/globalSettingsValidation.ts
|
|
2408
|
+
var R_SI_UPWARDS2 = 1 / (5.13 + 5);
|
|
2409
|
+
var R_SE2 = 1 / (20 + 4.14);
|
|
2410
|
+
var DWELLING_FIELD_KEYS = /* @__PURE__ */ new Set([
|
|
2411
|
+
"Postcode",
|
|
2412
|
+
"PartO_active_cooling_required",
|
|
2413
|
+
"GroundFloorArea",
|
|
2414
|
+
"HeatingControlType",
|
|
2415
|
+
"PartGcompliance",
|
|
2416
|
+
"ColdWaterSource",
|
|
2417
|
+
"BuildingLength",
|
|
2418
|
+
"BuildingWidth",
|
|
2419
|
+
"KitchenExtractorHoodExternal",
|
|
2420
|
+
"HasElectricitySmartMeter",
|
|
2421
|
+
"ElectricitySmartMeterGUID"
|
|
2422
|
+
]);
|
|
2423
|
+
function globalSettingsFieldSection(key) {
|
|
2424
|
+
if (key === "DefaultsPath" || key.startsWith("DefaultAssembly") || key.startsWith("FabricRow_") || key === "HEMIE_age_band" || key.startsWith("HEMIE_construction_")) return "fabric";
|
|
2425
|
+
if (key === "TargetBundleId" || key === "IsExistingBuilding" || key.startsWith("HEMIE_")) return "target";
|
|
2426
|
+
if (key.startsWith("AirPermeability_test_")) return "airTightness";
|
|
2427
|
+
if (key.startsWith("Ventilation_") || key === "AirPermeability_ventilation_zone_height") return "ventilation";
|
|
2428
|
+
if (key === "JunctionPsiDefaultsPath" || key.startsWith("DetailedBridgePsiProfile")) return "thermalBridging";
|
|
2429
|
+
if (key.startsWith("General_") || key.startsWith("NumberOf") || key.startsWith("Appliances_") || DWELLING_FIELD_KEYS.has(key)) return "dwelling";
|
|
2430
|
+
return null;
|
|
457
2431
|
}
|
|
2432
|
+
var METADATA_INPUT_LABELS = {
|
|
2433
|
+
NumberOfBedrooms: "Number of bedrooms",
|
|
2434
|
+
NumberOfWetRooms: "Number of wet rooms",
|
|
2435
|
+
GroundFloorArea: "Ground floor area (m\xB2)",
|
|
2436
|
+
HeatingControlType: "Heating control type",
|
|
2437
|
+
PartGcompliance: "Part G compliance",
|
|
2438
|
+
PartO_active_cooling_required: "Part O active cooling required",
|
|
2439
|
+
AirPermeability_test_pressure: "Test pressure",
|
|
2440
|
+
AirPermeability_test_result: "Test result",
|
|
2441
|
+
AirPermeability_ventilation_zone_height: "Ventilation zone height (m)",
|
|
2442
|
+
Ventilation_shield_class: "Shield class",
|
|
2443
|
+
Ventilation_terrain_class: "Terrain class",
|
|
2444
|
+
Ventilation_altitude: "Altitude (m)",
|
|
2445
|
+
Ventilation_ventilation_zone_base_height: "Ventilation zone base height (m)",
|
|
2446
|
+
Ventilation_noise_nuisance: "Noise nuisance",
|
|
2447
|
+
BuildingLength: "Building length (m)",
|
|
2448
|
+
BuildingWidth: "Building width (m)",
|
|
2449
|
+
NumberOfHotTappedRooms: "Number of hot-tapped rooms",
|
|
2450
|
+
NumberOfUtilityRooms: "Number of utility rooms",
|
|
2451
|
+
NumberOfBathrooms: "Number of bathrooms",
|
|
2452
|
+
NumberOfSanitaryAccommodations: "Number of sanitary accommodations",
|
|
2453
|
+
NumberOfHabitableRooms: "Number of habitable rooms",
|
|
2454
|
+
KitchenExtractorHoodExternal: "Kitchen cooker hood extracts to outside",
|
|
2455
|
+
General_build_type: "Build type",
|
|
2456
|
+
General_built_form: "SAP built form",
|
|
2457
|
+
General_storeys_in_dwelling: "Storeys in dwelling",
|
|
2458
|
+
General_storey_of_dwelling: "Storey of dwelling",
|
|
2459
|
+
General_storeys_in_building: "Storeys in building",
|
|
2460
|
+
HasElectricitySmartMeter: "Electricity smart meter",
|
|
2461
|
+
ElectricitySmartMeterGUID: "Smart meter GUID",
|
|
2462
|
+
IsExistingBuilding: "Existing building",
|
|
2463
|
+
Ventilation_cross_vent_possible: "Cross ventilation possible",
|
|
2464
|
+
Appliances_has_dryer: "Has a clothes dryer",
|
|
2465
|
+
Appliances_has_dishwasher: "Has a dishwasher",
|
|
2466
|
+
Appliances_has_separate_fridge_or_freezer: "Has a separate fridge or freezer"
|
|
2467
|
+
};
|
|
2468
|
+
var TARGET_INPUT_ROWS = [
|
|
2469
|
+
"HasElectricitySmartMeter",
|
|
2470
|
+
"IsExistingBuilding",
|
|
2471
|
+
"Ventilation_cross_vent_possible",
|
|
2472
|
+
"Appliances_has_dryer",
|
|
2473
|
+
"Appliances_has_dishwasher",
|
|
2474
|
+
"Appliances_has_separate_fridge_or_freezer"
|
|
2475
|
+
];
|
|
2476
|
+
var TARGET_INPUT_ROW_SET = new Set(TARGET_INPUT_ROWS);
|
|
2477
|
+
|
|
2478
|
+
// ../community/packages/geometry-editor/src/lib/buildErrorDisplay.ts
|
|
2479
|
+
var SECTION_LOCATIONS = {
|
|
2480
|
+
fabric: "Global Settings > Fabric",
|
|
2481
|
+
target: "Global Settings",
|
|
2482
|
+
dwelling: "Global Settings > Dwelling details",
|
|
2483
|
+
airTightness: "Global Settings > Air Tightness",
|
|
2484
|
+
ventilation: "Global Settings > Ventilation environment",
|
|
2485
|
+
thermalBridging: "Global Settings > Thermal bridging"
|
|
2486
|
+
};
|
|
2487
|
+
var VENTILATION_SETTINGS = /* @__PURE__ */ new Set(["cross_vent_possible", "terrain_class", "altitude", "shield_class", "noise_nuisance", "ventilation_zone_base_height"]);
|
|
2488
|
+
var settingsRow = (segments) => {
|
|
2489
|
+
if (segments[0] === "Metadata") return segments[1];
|
|
2490
|
+
if (segments[0] !== "InfiltrationVentilation") return void 0;
|
|
2491
|
+
if (segments[1] === "Leaks") {
|
|
2492
|
+
return segments[2] === "ventilation_zone_height" ? "AirPermeability_ventilation_zone_height" : "AirPermeability_test_result";
|
|
2493
|
+
}
|
|
2494
|
+
return segments[1] && VENTILATION_SETTINGS.has(segments[1]) ? `Ventilation_${segments[1]}` : void 0;
|
|
2495
|
+
};
|
|
2496
|
+
var titleCaseToken = (token) => token.replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/\s+/g, " ").trim().replace(/\b\w/g, (c) => c.toUpperCase());
|
|
2497
|
+
var pointerSegments = issuePathSegments;
|
|
2498
|
+
var buildErrorLocation = (path) => {
|
|
2499
|
+
const segments = pointerSegments(path);
|
|
2500
|
+
const zoneIdx = segments.indexOf("Zone");
|
|
2501
|
+
const elementIdx = segments.indexOf("BuildingElement");
|
|
2502
|
+
if (zoneIdx >= 0 && segments[zoneIdx + 1]) {
|
|
2503
|
+
const zone = segments[zoneIdx + 1];
|
|
2504
|
+
if (elementIdx >= 0 && segments[elementIdx + 1]) {
|
|
2505
|
+
return {
|
|
2506
|
+
location: `${zone} > ${segments[elementIdx + 1]}`,
|
|
2507
|
+
field: segments[elementIdx + 2]
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
return {
|
|
2511
|
+
location: zone,
|
|
2512
|
+
field: segments[zoneIdx + 2]
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
if (segments[0] === "Metadata" && segments[1]?.startsWith("HEMIE_")) {
|
|
2516
|
+
const constructionType = segments[1].match(/^HEMIE_construction_(.+)$/)?.[1];
|
|
2517
|
+
return {
|
|
2518
|
+
location: segments[1] === HEMIE_NATION ? "Global Settings > Dwelling details" : `Global Settings > Fabric${constructionType ? ` > ${hemieConstructionTypeLabel(constructionType)}` : ""}`
|
|
2519
|
+
};
|
|
2520
|
+
}
|
|
2521
|
+
const row = settingsRow(segments);
|
|
2522
|
+
const section = row ? globalSettingsFieldSection(row) : null;
|
|
2523
|
+
if (section) return { location: SECTION_LOCATIONS[section] };
|
|
2524
|
+
if (segments.length >= 2) {
|
|
2525
|
+
return {
|
|
2526
|
+
location: `${titleCaseToken(segments[0])} > ${titleCaseToken(segments[1])}`,
|
|
2527
|
+
field: segments[2]
|
|
2528
|
+
};
|
|
2529
|
+
}
|
|
2530
|
+
if (segments.length === 1) {
|
|
2531
|
+
return { location: titleCaseToken(segments[0]) };
|
|
2532
|
+
}
|
|
2533
|
+
return { location: "Model" };
|
|
2534
|
+
};
|
|
2535
|
+
var compactPathLabel = (segments) => {
|
|
2536
|
+
if (segments.length === 0) return "model";
|
|
2537
|
+
return segments.map(titleCaseToken).join(" > ");
|
|
2538
|
+
};
|
|
2539
|
+
var requiredFieldFromMessage = (message) => {
|
|
2540
|
+
const match = message.match(/^"([^"]+)" is a required property$/);
|
|
2541
|
+
return match?.[1] ? titleCaseToken(match[1]) : null;
|
|
2542
|
+
};
|
|
2543
|
+
var minimumFromMessage = (message) => {
|
|
2544
|
+
const match = message.match(/^(.+?) is less than the minimum of (.+)$/);
|
|
2545
|
+
return match?.[2]?.trim() || null;
|
|
2546
|
+
};
|
|
2547
|
+
var maximumFromMessage = (message) => {
|
|
2548
|
+
const match = message.match(/^(.+?) is greater than the maximum of (.+)$/);
|
|
2549
|
+
return match?.[2]?.trim() || null;
|
|
2550
|
+
};
|
|
2551
|
+
var unexpectedFieldsFromMessage = (message) => {
|
|
2552
|
+
const match = message.match(/were unexpected\)$/);
|
|
2553
|
+
if (!match) return null;
|
|
2554
|
+
const fields = [...message.matchAll(/'([^']+)'/g)].flatMap((m) => m[1] ? [m[1]] : []);
|
|
2555
|
+
if (fields.length === 0) return null;
|
|
2556
|
+
const shown = fields.slice(0, 5).map(titleCaseToken).join(", ");
|
|
2557
|
+
return fields.length > 5 ? `${shown}, and ${fields.length - 5} more` : shown;
|
|
2558
|
+
};
|
|
2559
|
+
var isSchemaKeywordError = (item) => Boolean(item.keyword || item.schemaPath);
|
|
2560
|
+
var formatBuildErrorForDisplay = (item) => {
|
|
2561
|
+
const pathSegments = pointerSegments(item.path);
|
|
2562
|
+
const { location, field } = buildErrorLocation(item.path);
|
|
2563
|
+
const fieldLabel = field ? titleCaseToken(field) : void 0;
|
|
2564
|
+
const keyword = item.keyword || "";
|
|
2565
|
+
const requiredField = requiredFieldFromMessage(item.message);
|
|
2566
|
+
const minimum = minimumFromMessage(item.message);
|
|
2567
|
+
const maximum = maximumFromMessage(item.message);
|
|
2568
|
+
const unexpectedFields = unexpectedFieldsFromMessage(item.message);
|
|
2569
|
+
const explicitUserMessage = item.userMessage?.trim();
|
|
2570
|
+
const unstatedInput = item.code === "E_EPC_REQUIRED_INPUT" && pathSegments[0] === "Metadata" && pathSegments[1] ? METADATA_INPUT_LABELS[pathSegments[1]] : void 0;
|
|
2571
|
+
let userMessage;
|
|
2572
|
+
if (explicitUserMessage) {
|
|
2573
|
+
userMessage = explicitUserMessage;
|
|
2574
|
+
} else if (unstatedInput) {
|
|
2575
|
+
const label = /^[A-Z][a-z]/.test(unstatedInput) && !/^Part\b/.test(unstatedInput) ? unstatedInput[0].toLowerCase() + unstatedInput.slice(1) : unstatedInput;
|
|
2576
|
+
userMessage = TARGET_INPUT_ROW_SET.has(pathSegments[1]) ? `Choose yes or no for ${label}.` : `Enter ${label}.`;
|
|
2577
|
+
} else if (location === "Appliances" && (item.message.includes("is not allowed for {}") || item.message.includes("has less than"))) {
|
|
2578
|
+
userMessage = "Add at least one appliance entry.";
|
|
2579
|
+
} else if (pathSegments[0] === "HotWaterDemand" && (item.message.includes("has less than") || keyword === "minProperties")) {
|
|
2580
|
+
userMessage = "Add at least one hot water outlet.";
|
|
2581
|
+
} else if (pathSegments[0] === "Zone" && pathSegments[2] === "Lighting" && pathSegments.length === 3 && item.message.startsWith("null ")) {
|
|
2582
|
+
userMessage = "Add at least one light to this zone.";
|
|
2583
|
+
} else if (pathSegments[0] === "InfiltrationVentilation" && pathSegments[1] === "MechanicalVentilation" && (item.message.includes("schemas listed in the 'oneOf' keyword") || keyword === "oneOf" || keyword === "anyOf")) {
|
|
2584
|
+
userMessage = "Add ventilation position details: height, orientation, and pitch.";
|
|
2585
|
+
} else if (requiredField || keyword === "required") {
|
|
2586
|
+
userMessage = requiredField ? `Add ${requiredField}.` : "Add the missing required field.";
|
|
2587
|
+
} else if (minimum || keyword === "minimum" || keyword === "exclusiveMinimum") {
|
|
2588
|
+
userMessage = `${fieldLabel || "Value"} must be at least ${minimum || "the allowed minimum"}.`;
|
|
2589
|
+
} else if (maximum || keyword === "maximum" || keyword === "exclusiveMaximum") {
|
|
2590
|
+
userMessage = `${fieldLabel || "Value"} must be no more than ${maximum || "the allowed maximum"}.`;
|
|
2591
|
+
} else if (item.message.includes("has less than") || keyword === "minProperties") {
|
|
2592
|
+
userMessage = `Add at least one entry for ${compactPathLabel(pathSegments)}.`;
|
|
2593
|
+
} else if (item.message.includes("schemas listed in the 'oneOf' keyword") || keyword === "oneOf" || keyword === "anyOf") {
|
|
2594
|
+
userMessage = fieldLabel ? `${fieldLabel} does not match an allowed option.` : `${compactPathLabel(pathSegments)} matches none of the forms this HEM version takes. Check its type and the inputs it states.`;
|
|
2595
|
+
} else if (unexpectedFields || keyword === "unevaluatedProperties" || keyword === "additionalProperties") {
|
|
2596
|
+
userMessage = unexpectedFields ? `Remove fields not allowed here: ${unexpectedFields}.` : "Remove fields that are not allowed here.";
|
|
2597
|
+
} else if (keyword === "const" || keyword === "allOf" || item.message.includes("is not allowed for")) {
|
|
2598
|
+
userMessage = location === "Appliances" ? "Check the appliance entries against the selected schema." : "These settings conflict with the selected schema.";
|
|
2599
|
+
} else if (!isSchemaKeywordError(item)) {
|
|
2600
|
+
userMessage = item.message.split("\n")[0];
|
|
2601
|
+
} else {
|
|
2602
|
+
userMessage = fieldLabel ? `Check ${fieldLabel}.` : "Check this section.";
|
|
2603
|
+
}
|
|
2604
|
+
return { item, location, field, userMessage, pathSegments };
|
|
2605
|
+
};
|
|
2606
|
+
var isNoisyUnexpectedPropertiesError = (error) => error.item.keyword === "unevaluatedProperties" || error.item.keyword === "additionalProperties" || error.item.message.includes("Unevaluated properties are not allowed") || error.item.message.includes("Additional properties are not allowed");
|
|
2607
|
+
var filterDisplayBuildErrors = (errors) => {
|
|
2608
|
+
const concreteErrorParents = /* @__PURE__ */ new Set();
|
|
2609
|
+
for (const error of errors) {
|
|
2610
|
+
if (isNoisyUnexpectedPropertiesError(error)) continue;
|
|
2611
|
+
if (error.pathSegments.length > 1) {
|
|
2612
|
+
concreteErrorParents.add(error.pathSegments.slice(0, -1).join("/"));
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
const converterFailed = errors.some((error) => !isSchemaKeywordError(error.item) && !error.item.severity);
|
|
2616
|
+
return errors.filter((error) => {
|
|
2617
|
+
if (converterFailed && isSchemaKeywordError(error.item) && error.pathSegments.length <= 1 && (error.item.keyword === "anyOf" || error.item.keyword === "oneOf")) return false;
|
|
2618
|
+
if (!isNoisyUnexpectedPropertiesError(error)) return true;
|
|
2619
|
+
return !concreteErrorParents.has(error.pathSegments.join("/"));
|
|
2620
|
+
});
|
|
2621
|
+
};
|
|
2622
|
+
var collapseDerivedBuildErrors = (errors, resolve) => {
|
|
2623
|
+
const rows = errors.map((error) => ({ ...error, target: resolve(error.item.path), derived: [] }));
|
|
2624
|
+
const sourceRowByOwner = /* @__PURE__ */ new Map();
|
|
2625
|
+
for (const row of rows) {
|
|
2626
|
+
if (!isSchemaKeywordError(row.item) && !row.item.severity && row.target.section === "Zone" && !sourceRowByOwner.has(row.target.ownerKey)) {
|
|
2627
|
+
sourceRowByOwner.set(row.target.ownerKey, row);
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
return rows.filter((row) => {
|
|
2631
|
+
const sourceRow = isSchemaKeywordError(row.item) ? sourceRowByOwner.get(row.target.ownerKey) : void 0;
|
|
2632
|
+
if (!sourceRow) return true;
|
|
2633
|
+
sourceRow.derived.push(row);
|
|
2634
|
+
return false;
|
|
2635
|
+
});
|
|
2636
|
+
};
|
|
2637
|
+
var displayBuildErrorRows = (items, resolve) => collapseDerivedBuildErrors(filterDisplayBuildErrors(items.map(formatBuildErrorForDisplay)), resolve);
|
|
2638
|
+
|
|
2639
|
+
// ../hem-target-runtime/src/hem/pythonFailureMessage.ts
|
|
458
2640
|
var MAX_DETAIL_LINE = 200;
|
|
459
2641
|
function pythonFailureMessage(text) {
|
|
460
2642
|
const lastFrame = text.lastIndexOf('\n File "');
|
|
@@ -465,228 +2647,347 @@ function pythonFailureMessage(text) {
|
|
|
465
2647
|
const exception = lines.slice(header).map((line) => line.trim().replace(/, input_value=.*$/, "]")).filter((line) => line && !line.startsWith("For further information visit")).map((line) => line.length > MAX_DETAIL_LINE ? `${line.slice(0, MAX_DETAIL_LINE - 1)}\u2026` : line);
|
|
466
2648
|
return `HEM could not calculate this model. ${exception.join(" ")}`;
|
|
467
2649
|
}
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
if (Object.keys(profile).some((key) => !keys.includes(key))) throw new Error("Unknown heating profile field");
|
|
475
|
-
if (profile.type === "reference") return { type: "reference" };
|
|
476
|
-
if (profile.type !== "weekly") throw new Error("Heating profile type must be reference or weekly");
|
|
477
|
-
if (typeof profile.setback !== "number" || !Number.isFinite(profile.setback) || profile.setback < 0 || profile.setback > 30) throw new Error("Heating setback must be between 0 and 30 C");
|
|
478
|
-
for (const day of ["weekday", "weekend"]) {
|
|
479
|
-
const periods = profile[day];
|
|
480
|
-
if (!Array.isArray(periods) || !periods.length) throw new Error(`Heating ${day} needs at least one period`);
|
|
481
|
-
let end = 0;
|
|
482
|
-
for (const period of periods) {
|
|
483
|
-
if (!Array.isArray(period) || period.length !== 2 || period.some((time) => typeof time !== "number" || !Number.isFinite(time)) || period[0] < 0 || period[1] > 24 || period[0] >= period[1]) throw new Error("Heating periods must be [start, end] within 0\u201324 hours");
|
|
484
|
-
if (period[0] < end) throw new Error("Heating periods must be ordered without overlap");
|
|
485
|
-
end = period[1];
|
|
486
|
-
}
|
|
2650
|
+
var TargetRunError = class extends Error {
|
|
2651
|
+
constructor(message, failure, traceback, report) {
|
|
2652
|
+
super(message);
|
|
2653
|
+
this.failure = failure;
|
|
2654
|
+
this.traceback = traceback;
|
|
2655
|
+
this.report = report;
|
|
487
2656
|
}
|
|
488
|
-
|
|
2657
|
+
};
|
|
2658
|
+
function targetRunFailureOf(error) {
|
|
2659
|
+
for (let current = error; current instanceof Error; current = current.cause) {
|
|
2660
|
+
if (current instanceof TargetRunError) return current.failure;
|
|
2661
|
+
}
|
|
2662
|
+
return void 0;
|
|
489
2663
|
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
if (typeof system.Control !== "string") throw new Error("Space heating system has no generated setpoint control");
|
|
497
|
-
names.add(system.Control);
|
|
2664
|
+
var pointer = (segments) => segments.map((segment) => `/${segment.replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
|
|
2665
|
+
var segmentsOf = (path) => path.split("/").slice(1).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
2666
|
+
function authored(segments, provenance) {
|
|
2667
|
+
for (let length = segments.length; length >= Math.max(segments.length - 1, 1); length -= 1) {
|
|
2668
|
+
const source = provenance[pointer(segments.slice(0, length))];
|
|
2669
|
+
if (source !== void 0) return [...segmentsOf(source), ...segments.slice(length)];
|
|
498
2670
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
return
|
|
524
|
-
};
|
|
525
|
-
control.schedule = {
|
|
526
|
-
main: [{ value: "week", repeat: Math.ceil(model.SimulationTime.end / 168) + 1 }],
|
|
527
|
-
week: [{ value: "weekday", repeat: 5 }, { value: "weekend", repeat: 2 }],
|
|
528
|
-
weekday: day(profile.weekday),
|
|
529
|
-
weekend: day(profile.weekend)
|
|
530
|
-
};
|
|
531
|
-
control.advanced_start = 0;
|
|
532
|
-
control.setpoint_min = profile.setback;
|
|
2671
|
+
return void 0;
|
|
2672
|
+
}
|
|
2673
|
+
function wallNamed(model, message) {
|
|
2674
|
+
const [, storey, edge] = message.match(/for wall 'storey(\d+)_wall(\d+)'/) ?? [];
|
|
2675
|
+
if (storey === void 0) return void 0;
|
|
2676
|
+
const parts = model.Zone?.building_parts ?? {};
|
|
2677
|
+
const found = Object.entries(parts).flatMap(([part, { walls = [] }]) => walls.flatMap((wall, index) => wall.storey_index === Number(storey) && wall.floorplan_index === Number(edge) ? [pointer(["Zone", "building_parts", part, "walls", String(index)])] : []));
|
|
2678
|
+
return found.length === 1 ? found[0] : void 0;
|
|
2679
|
+
}
|
|
2680
|
+
var SYSTEM_SECTIONS = /* @__PURE__ */ new Set(["HotWaterSource", "HeatSourceWet", "SpaceHeatSystem", "SpaceCoolSystem"]);
|
|
2681
|
+
function walk(input, loc, type) {
|
|
2682
|
+
const segments = [];
|
|
2683
|
+
let node = input;
|
|
2684
|
+
let building = false;
|
|
2685
|
+
let arm;
|
|
2686
|
+
for (const [index, raw] of loc.entries()) {
|
|
2687
|
+
const key = String(raw);
|
|
2688
|
+
const present = node !== null && typeof node === "object" && Object.prototype.hasOwnProperty.call(node, key);
|
|
2689
|
+
if (present) {
|
|
2690
|
+
segments.push(key);
|
|
2691
|
+
node = node[key];
|
|
2692
|
+
if (node?.model_type === "hemie" && !SYSTEM_SECTIONS.has(segments[0])) building = true;
|
|
2693
|
+
} else if (index === loc.length - 1) {
|
|
2694
|
+
segments.push(key);
|
|
2695
|
+
return { segments, building, arm, missing: type === "missing" };
|
|
2696
|
+
} else arm ?? (arm = { place: pointer(segments), tag: key, hemieInput: node?.model_type !== void 0 });
|
|
533
2697
|
}
|
|
534
|
-
return
|
|
2698
|
+
return { segments, building, arm, missing: false };
|
|
535
2699
|
}
|
|
536
|
-
|
|
537
|
-
const
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
const
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
2700
|
+
function chosenArms(all) {
|
|
2701
|
+
const key = (error) => `${pointer(error.segments)}
|
|
2702
|
+
${error.msg}`;
|
|
2703
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
2704
|
+
for (const [index, error] of all.entries()) {
|
|
2705
|
+
if (error.type !== "extra_forbidden" || error.segments[error.segments.length - 1] !== "model_type") continue;
|
|
2706
|
+
dropped.add(index);
|
|
2707
|
+
const parent = pointer(error.segments.slice(0, -1));
|
|
2708
|
+
for (let previous = index - 1; previous >= 0; previous -= 1) {
|
|
2709
|
+
const candidate = all[previous];
|
|
2710
|
+
if (!pointer(candidate.segments).startsWith(parent) || candidate.arm?.tag !== error.arm?.tag) break;
|
|
2711
|
+
const copyElsewhere = all.some((other, at) => at !== previous && !dropped.has(at) && key(other) === key(candidate));
|
|
2712
|
+
if (!candidate.missing && !copyElsewhere) break;
|
|
2713
|
+
dropped.add(previous);
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2717
|
+
const kept = all.filter((_, index) => !dropped.has(index));
|
|
2718
|
+
const walked = (kept.length ? kept : all).filter((error) => !seen.has(key(error)) && seen.add(key(error)));
|
|
2719
|
+
const arms = /* @__PURE__ */ new Map();
|
|
2720
|
+
for (const { arm } of walked) {
|
|
2721
|
+
if (!arm) continue;
|
|
2722
|
+
const place = arms.get(arm.place) ?? /* @__PURE__ */ new Map();
|
|
2723
|
+
const container = /^(dict|list)\[/.test(arm.tag);
|
|
2724
|
+
const entry = place.get(arm.tag) ?? { count: 0, stated: arm.hemieInput !== container };
|
|
2725
|
+
entry.count += 1;
|
|
2726
|
+
place.set(arm.tag, entry);
|
|
2727
|
+
arms.set(arm.place, place);
|
|
2728
|
+
}
|
|
2729
|
+
const best = new Map([...arms].map(([place, tags]) => [place, [...tags].sort(([, a], [, b]) => Number(b.stated) - Number(a.stated) || a.count - b.count)[0][0]]));
|
|
2730
|
+
return walked.filter(({ arm }) => !arm || best.get(arm.place) === arm.tag);
|
|
546
2731
|
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
2732
|
+
var STAGE_TEXT = {
|
|
2733
|
+
input_check: "the input check",
|
|
2734
|
+
product_lookup: "the product lookup",
|
|
2735
|
+
existing_building_conversion: "the existing building conversion",
|
|
2736
|
+
preprocessing: "preparation",
|
|
2737
|
+
core: "the simulation",
|
|
2738
|
+
metrics: "the rating calculation",
|
|
2739
|
+
unclassified: "the calculation"
|
|
2740
|
+
};
|
|
2741
|
+
var firstLine = (text) => (text.trim().split("\n")[0] ?? "").replace(/^Value error, /, "").slice(0, MAX_DETAIL_LINE);
|
|
2742
|
+
var SYNTHESISED_FIELDS = /* @__PURE__ */ new Set(["model_type", "reference_building_part", "storey_index", "floorplan_index"]);
|
|
2743
|
+
var CODE_FAULTS = /* @__PURE__ */ new Set(["TypeError", "KeyError", "AttributeError", "IndexError", "NameError", "AssertionError", "UnboundLocalError"]);
|
|
2744
|
+
var VULCAN_FAULT = "Vulcan could not convert this existing building for the EPC calculation. This is a fault in Vulcan, not in your model. Report it to Vulcan support with this model.";
|
|
2745
|
+
var BUILDING_SECTIONS = { Zone: "the building", InfiltrationVentilation: "ventilation and air tightness", ExternalConditions: "shading" };
|
|
2746
|
+
function buildingPlace(segments) {
|
|
2747
|
+
const parts = [];
|
|
2748
|
+
for (let i = 1; i < segments.length - 1; i += 1) {
|
|
2749
|
+
const [key, next] = [segments[i], segments[i + 1]];
|
|
2750
|
+
if (key === "building_parts") {
|
|
2751
|
+
parts.push(`building part ${next}`);
|
|
2752
|
+
i += 1;
|
|
2753
|
+
} else if (/^\d+$/.test(next)) {
|
|
2754
|
+
parts.push(`${key.replace(/_/g, " ").replace(/s$/, "")} ${Number(next) + 1}`);
|
|
2755
|
+
i += 1;
|
|
563
2756
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
});
|
|
2757
|
+
}
|
|
2758
|
+
return parts.length ? parts.join(", ") : BUILDING_SECTIONS[segments[0]] ?? segments[0];
|
|
567
2759
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
const
|
|
581
|
-
if (
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
const
|
|
588
|
-
const
|
|
589
|
-
const
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
emission_rate_compliant: dwelling_emission_rate <= target_emission_rate,
|
|
603
|
-
dwelling_primary_energy_rate,
|
|
604
|
-
target_primary_energy_rate,
|
|
605
|
-
primary_energy_rate_compliant: dwelling_primary_energy_rate <= target_primary_energy_rate,
|
|
606
|
-
dwelling_fabric_energy_efficiency,
|
|
607
|
-
target_fabric_energy_efficiency,
|
|
608
|
-
fabric_energy_efficiency_compliant: dwelling_fabric_energy_efficiency <= target_fabric_energy_efficiency
|
|
609
|
-
};
|
|
2760
|
+
var readable = (field, text) => text.replace(
|
|
2761
|
+
/^Input should be (.*?)\.?$/,
|
|
2762
|
+
(_, rule) => `${field.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase())} must be ${rule}.`
|
|
2763
|
+
);
|
|
2764
|
+
function targetRunError(report, input, provenance = {}) {
|
|
2765
|
+
const model = JSON.parse(input);
|
|
2766
|
+
const walked = chosenArms((report.errors ?? []).map((error) => ({ ...walk(model, error.loc, error.type), type: error.type, msg: error.msg })));
|
|
2767
|
+
const notes = /* @__PURE__ */ new Set();
|
|
2768
|
+
const issues = [];
|
|
2769
|
+
for (const { segments: converted, building, missing, msg } of walked) {
|
|
2770
|
+
const field = converted[converted.length - 1] ?? "";
|
|
2771
|
+
const segments = building && !SYNTHESISED_FIELDS.has(field) ? authored(converted, provenance) ?? converted : converted;
|
|
2772
|
+
const located = segments !== converted;
|
|
2773
|
+
if (building && SYNTHESISED_FIELDS.has(field)) notes.add(VULCAN_FAULT);
|
|
2774
|
+
else if (building && !located) {
|
|
2775
|
+
const reason = missing ? `${field.replace(/_/g, " ")} is missing` : readable(field, firstLine(msg ?? "")).replace(/\.$/, "");
|
|
2776
|
+
notes.add(`The EPC calculation could not use this existing building: ${reason} (${buildingPlace(segments)}). Check the elements it is built from; if they are correct, report it to Vulcan support.`);
|
|
2777
|
+
} else issues.push(missing ? { path: pointer(segments.slice(0, -1)), keyword: "required", message: `"${field}" is a required property` } : { path: pointer(segments), message: readable(field, firstLine(msg ?? "")) });
|
|
2778
|
+
}
|
|
2779
|
+
const conversionStage = report.stage === "existing_building_conversion";
|
|
2780
|
+
const wall = !walked.length && conversionStage ? wallNamed(model, report.message) : void 0;
|
|
2781
|
+
const wallSource = wall && provenance[wall];
|
|
2782
|
+
if (wallSource && /wall area is less than zero/.test(report.message)) {
|
|
2783
|
+
issues.push({ path: wallSource, message: "The windows, doors and bay in this wall take more than its area. Make them smaller, or check the wall length and height." });
|
|
2784
|
+
} else if (!walked.length && conversionStage) {
|
|
2785
|
+
notes.add(CODE_FAULTS.has(report.kind) ? VULCAN_FAULT : `The EPC calculation could not use this existing building: ${firstLine(report.message)}. Check the elements it is built from; if they are correct, report it to Vulcan support.`);
|
|
2786
|
+
}
|
|
2787
|
+
const cause = notes.size ? "conversion" : issues.length || ["input_check", "product_lookup"].includes(report.stage) ? "input" : "simulation";
|
|
2788
|
+
if (!notes.size && !issues.length) {
|
|
2789
|
+
notes.add(cause === "input" ? `The EPC calculation stopped at ${STAGE_TEXT[report.stage]}: ${firstLine(report.message)}` : `The EPC calculation stopped during ${STAGE_TEXT[report.stage]}: ${firstLine(report.message)}. Report it to Vulcan support with this model if it happens again.`);
|
|
2790
|
+
}
|
|
2791
|
+
const rows = displayBuildErrorRows(issues.map((issue) => ({ source: "schema", ...issue })), () => ({ ownerKey: "" }));
|
|
2792
|
+
const message = [...notes, ...rows.length ? [`The EPC calculation found ${rows.length === 1 ? "an error" : `${rows.length} errors`} in the model. ${rows.map((row) => `${row.location}: ${row.userMessage}`).join(" ")}`] : []].join(" ");
|
|
2793
|
+
return new TargetRunError(message, { stage: report.stage, kind: report.kind, cause, issues, notes: [...notes] }, report.traceback, report);
|
|
610
2794
|
}
|
|
611
2795
|
|
|
2796
|
+
// ../hem-target-runtime/src/hem/epcAssumptions.ts
|
|
2797
|
+
var EPC_ASSUMPTIONS_PYTHON = `
|
|
2798
|
+
def vulcan_epc_estimated_leaks(model):
|
|
2799
|
+
"""Assumption pending DESNZ E17. An existing building with no air test states only HEMIE's
|
|
2800
|
+
three leakage-estimate inputs (GeometryInfiltrationProperties). The wrapper resolves them from
|
|
2801
|
+
the Geometry, but the pinned Orchestrator parses Leaks before that step and rejects the form. This makes the same calls on
|
|
2802
|
+
the same Zone and hands the Orchestrator the result: HEMIE's estimated Pulse test. If DESNZ
|
|
2803
|
+
fixes the Orchestrator, delete this function and its call; the input is unchanged."""
|
|
2804
|
+
from hemie.models.geometry import Geometry
|
|
2805
|
+
from hemie.models.infiltration_properties import infiltration_properties_from_geometry
|
|
2806
|
+
from hemie.models.leaks import GeometryInfiltrationProperties, Leaks
|
|
2807
|
+
zone = model.get('Zone')
|
|
2808
|
+
leaks = (model.get('InfiltrationVentilation') or {}).get('Leaks')
|
|
2809
|
+
if not (isinstance(zone, dict) and zone.get('model_type') == 'hemie' and isinstance(leaks, dict)
|
|
2810
|
+
and isinstance(leaks.get('infiltration_properties'), dict)):
|
|
2811
|
+
return model
|
|
2812
|
+
# The mechanical ventilation system still names its products here (the Orchestrator
|
|
2813
|
+
# substitutes them later), and none of HEMIE's infiltration properties reads it.
|
|
2814
|
+
geometry = Geometry.model_validate({key: value for key, value in zone.items() if key != 'mechanical_ventilation_system'})
|
|
2815
|
+
stated = {key: value for key, value in leaks.items() if key != 'infiltration_properties'}
|
|
2816
|
+
manual = GeometryInfiltrationProperties.model_validate(leaks['infiltration_properties'])
|
|
2817
|
+
properties = infiltration_properties_from_geometry(geometry,
|
|
2818
|
+
number_of_open_fireplaces=manual.number_of_open_fireplaces, heat_loss_corridor=manual.heat_loss_corridor,
|
|
2819
|
+
double_glazing_installation_period=manual.double_glazing_installation_period)
|
|
2820
|
+
estimated = Leaks.model_validate({**stated, 'infiltration_properties': properties})
|
|
2821
|
+
model['InfiltrationVentilation']['Leaks'] = {**stated, 'test_pressure': estimated.test_pressure, 'test_result': estimated.test_result}
|
|
2822
|
+
return model
|
|
2823
|
+
`;
|
|
2824
|
+
|
|
2825
|
+
// ../hem-target-runtime/src/hem/designHeatLoss.ts
|
|
2826
|
+
var PINNED_WEATHER_NAME = "Bedford";
|
|
2827
|
+
|
|
612
2828
|
// ../hem-target-runtime/src/hem/targets.ts
|
|
613
2829
|
var WRAPPERS = {
|
|
614
2830
|
fhs: {
|
|
2831
|
+
/** Wire name the target preparation artifacts accept. */
|
|
615
2832
|
profile: "fhs",
|
|
2833
|
+
/** Community defaults template the family's bundles pin for preparation. */
|
|
2834
|
+
preparationDefaults: "defaults_template.json",
|
|
2835
|
+
/** Schema dialect the editor reads; separate from the wire profile. */
|
|
2836
|
+
schemaMode: "fhs",
|
|
616
2837
|
modes: ["actual", "actual-fee", "notional", "notional-fee"],
|
|
2838
|
+
/** Modes of a scenario that selects no model wrapper. */
|
|
2839
|
+
defaultModes: ["actual"],
|
|
617
2840
|
scenarioModes: {
|
|
618
2841
|
fhs_assumptions: ["actual"],
|
|
619
2842
|
fhs_compliance: ["actual", "actual-fee", "notional", "notional-fee"]
|
|
620
2843
|
},
|
|
621
|
-
|
|
2844
|
+
/** The run-mode name users see, per scenario wrapper. */
|
|
2845
|
+
scenarioLabels: { fhs_assumptions: "Single run", fhs_compliance: "Compliance" },
|
|
2846
|
+
/** How the run's results are read; written to target-run.json. */
|
|
2847
|
+
resultsKind: "fhs",
|
|
2848
|
+
coreDistribution: "hem-core",
|
|
2849
|
+
wrapperDistribution: "hem-fhs-wrapper",
|
|
2850
|
+
/** Further pinned distributions; each target pins their version and commit in `components`. */
|
|
2851
|
+
componentDistributions: [],
|
|
2852
|
+
/** Systems take HEM Database products, picked in the editor's product slots. */
|
|
2853
|
+
hemDatabaseProducts: false,
|
|
2854
|
+
/** The scenario wrapper an agent's single-model run uses when the caller names none. */
|
|
2855
|
+
singleRunWrapper: "fhs_compliance",
|
|
2856
|
+
/** Fabric from construction bands on an existing building (the editor's `constructionBands` rule). */
|
|
2857
|
+
constructionBands: false,
|
|
2858
|
+
/** A scenario may pick its own weather file. */
|
|
2859
|
+
customWeather: true
|
|
2860
|
+
},
|
|
2861
|
+
epc: {
|
|
2862
|
+
/** vulcan-model-transform `ModelProfile::Epc`. */
|
|
2863
|
+
profile: "epc",
|
|
2864
|
+
/** The shared template plus the HEM:EPC fields with no Vulcan source. */
|
|
2865
|
+
preparationDefaults: "defaults_template_epc.json",
|
|
2866
|
+
/** The full-input schema is a Core-shaped input (pydantic unions), not the FHS dialect. */
|
|
2867
|
+
schemaMode: "core",
|
|
2868
|
+
/** `quick` is the main EPC run only (upstream --skip-smart-metric --skip-fees-metric); `full` adds the smart and FEES runs. */
|
|
2869
|
+
modes: ["quick", "full"],
|
|
2870
|
+
defaultModes: ["quick"],
|
|
2871
|
+
scenarioModes: {
|
|
2872
|
+
epc_quick: ["quick"],
|
|
2873
|
+
epc_full: ["full"]
|
|
2874
|
+
},
|
|
2875
|
+
scenarioLabels: { epc_quick: "Rating and energy", epc_full: "Full EPC" },
|
|
2876
|
+
resultsKind: "epc",
|
|
622
2877
|
coreDistribution: "hem-core",
|
|
623
|
-
wrapperDistribution: "hem-
|
|
2878
|
+
wrapperDistribution: "hem-epc-wrapper",
|
|
2879
|
+
componentDistributions: ["hem-epc-orchestrator", "hemie", "hem-db-client"],
|
|
2880
|
+
hemDatabaseProducts: true,
|
|
2881
|
+
singleRunWrapper: "epc_quick",
|
|
2882
|
+
// An existing building converts to HEMIE, whose fabric is the age band and constructions.
|
|
2883
|
+
constructionBands: true,
|
|
2884
|
+
// The Orchestrator runs on its pinned weather (pythonTarget.ts).
|
|
2885
|
+
customWeather: false
|
|
624
2886
|
}
|
|
625
2887
|
};
|
|
626
|
-
function targetWrapper(
|
|
627
|
-
const wrapper = WRAPPERS[
|
|
628
|
-
if (!wrapper) throw new Error(`Unsupported HEM wrapper: ${
|
|
2888
|
+
function targetWrapper(target2) {
|
|
2889
|
+
const wrapper = WRAPPERS[target2.wrapper];
|
|
2890
|
+
if (!wrapper) throw new Error(`Unsupported HEM wrapper: ${target2.wrapper}`);
|
|
629
2891
|
return wrapper;
|
|
630
2892
|
}
|
|
631
2893
|
var HEM_TARGETS = [
|
|
2894
|
+
// The Rust a9 that ECaaS runs in production (epb-ecaas-api e1c090e, lambda/Cargo.lock). Its wrapper
|
|
2895
|
+
// schema equals the Python a9 one, so it keeps that conversion profile's wire name. It is built
|
|
2896
|
+
// with the carried patch set fhs-a9-schema-v1 (targetSchemaCorrections.ts); build and parity:
|
|
2897
|
+
// docs/development/HEM_Rust_A9_Target.md. v2: v1's pins and patch set plus the design_heat_loss export.
|
|
632
2898
|
{
|
|
633
|
-
id: "rust-fhs-
|
|
634
|
-
label: "
|
|
2899
|
+
id: "rust-fhs-a9-9e41af89-f2c2425f-v2",
|
|
2900
|
+
label: "HEM:FHS 1.0.0a9",
|
|
635
2901
|
runtime: "rust",
|
|
636
|
-
version: "1.0.0a7",
|
|
637
|
-
engineVersion: "1.0.0a7",
|
|
638
|
-
wrapperVersion: "1.0.0a7",
|
|
639
|
-
wrapper: "fhs",
|
|
640
|
-
engineCommit: "62d3df705690f33b3fc3e905c9971d4f3743bf2e",
|
|
641
|
-
wrapperCommit: "c5ba2673fbd886cfe4fb528f61b376bdf406ebbd",
|
|
642
|
-
conversionProfile: "current_rust_fhs"
|
|
643
|
-
},
|
|
644
|
-
{
|
|
645
|
-
id: "python-fhs-a9-918addad-b9b90138-v1",
|
|
646
|
-
label: "Python HEM:FHS 1.0.0a9",
|
|
647
|
-
runtime: "python",
|
|
648
2902
|
version: "1.0.0a9",
|
|
649
2903
|
engineVersion: "1.0.0a9",
|
|
650
2904
|
wrapperVersion: "1.0.0a9",
|
|
651
2905
|
wrapper: "fhs",
|
|
652
|
-
engineCommit: "
|
|
653
|
-
wrapperCommit: "
|
|
654
|
-
conversionProfile: "python_fhs_a9"
|
|
2906
|
+
engineCommit: "9e41af890cc62a1cec08957340231c3591956dac",
|
|
2907
|
+
wrapperCommit: "f2c2425f00870e1611750bd2ac1be20132301e0d",
|
|
2908
|
+
conversionProfile: "python_fhs_a9",
|
|
2909
|
+
arealHeatCapacity: { classes: "full_depth", numberTypes: ["BuildingElementAdjacentConditionedSpace", "BuildingElementAdjacentUnconditionedSpace_Simple"] },
|
|
2910
|
+
// Measured, example_semi_detached at load 15-21 (15 November): Quick sim click to headline in
|
|
2911
|
+
// the app 7.1-8.6 s (engine 4.9 s, results write 0.7 s); wasm-browser-cli 5.2-7.1 s.
|
|
2912
|
+
// Compliance, all four modes: 48.3-48.6 s in wasm-browser-cli at load 13-19 (13 November).
|
|
2913
|
+
// Method: docs/development/HEM_Rust_A9_Target.md, "Run time".
|
|
2914
|
+
status: "provisional",
|
|
2915
|
+
typicalRunMinutes: { fhs_assumptions: 0.15, fhs_compliance: 0.8 }
|
|
655
2916
|
},
|
|
656
2917
|
{
|
|
657
|
-
id: "
|
|
658
|
-
label: "
|
|
659
|
-
runtime: "
|
|
660
|
-
version: "1.0.
|
|
661
|
-
engineVersion: "1.0.
|
|
662
|
-
wrapperVersion: "1.0.
|
|
2918
|
+
id: "rust-fhs-a7-62d3df70-c5ba2673-v1",
|
|
2919
|
+
label: "HEM:FHS 1.0.0a7",
|
|
2920
|
+
runtime: "rust",
|
|
2921
|
+
version: "1.0.0a7",
|
|
2922
|
+
engineVersion: "1.0.0a7",
|
|
2923
|
+
wrapperVersion: "1.0.0a7",
|
|
663
2924
|
wrapper: "fhs",
|
|
664
|
-
engineCommit: "
|
|
665
|
-
wrapperCommit: "
|
|
666
|
-
conversionProfile: "
|
|
2925
|
+
engineCommit: "62d3df705690f33b3fc3e905c9971d4f3743bf2e",
|
|
2926
|
+
wrapperCommit: "c5ba2673fbd886cfe4fb528f61b376bdf406ebbd",
|
|
2927
|
+
conversionProfile: "current_rust_fhs",
|
|
2928
|
+
arealHeatCapacity: { classes: "surface", numberTypes: [] },
|
|
2929
|
+
// Actual mode, example_semi_detached at load 17-22 (15 November): Quick sim click to headline in
|
|
2930
|
+
// the app 7.9-8.7 s; wasm-browser-cli 6.1-7.1 s. Compliance not measured.
|
|
2931
|
+
status: "legacy",
|
|
2932
|
+
typicalRunMinutes: { fhs_assumptions: 0.12 }
|
|
667
2933
|
}
|
|
668
2934
|
];
|
|
669
2935
|
var RECOMMENDED_HEM_TARGET = HEM_TARGETS[0].id;
|
|
2936
|
+
var HEM_EPC_0_13_2 = {
|
|
2937
|
+
id: "python-epc-0.13.2-6367f1ec-18032feb-v1",
|
|
2938
|
+
label: "HEM:EPC 0.13.2",
|
|
2939
|
+
runtime: "python",
|
|
2940
|
+
version: "0.13.2",
|
|
2941
|
+
engineVersion: "2.0.0a4",
|
|
2942
|
+
wrapperVersion: "0.13.2",
|
|
2943
|
+
wrapper: "epc",
|
|
2944
|
+
engineCommit: "6367f1ecb101c7f72a2006a921c732c790b0d338",
|
|
2945
|
+
wrapperCommit: "18032feb59294b323fc28af4fb032d34bd44bf67",
|
|
2946
|
+
conversionProfile: "epc_full_input_v1",
|
|
2947
|
+
arealHeatCapacity: { classes: "full_depth", numberTypes: "all" },
|
|
2948
|
+
components: {
|
|
2949
|
+
"hem-epc-orchestrator": { version: "0.13.2a0", commit: "993463233ad0c416e83c4de3b84889280d3c4619" },
|
|
2950
|
+
hemie: { version: "0.18.1", commit: "2876e2ec1c7bad2b738c9c3b3685d86860a91f41" },
|
|
2951
|
+
"hem-db-client": { version: "1.0.0a10", commit: "9eeb026dd52a612197b5552ca113d8121fa72679" }
|
|
2952
|
+
},
|
|
2953
|
+
// db-client/data/*.csv at the hem-db-client commit.
|
|
2954
|
+
productDataSha256: "d0acf4ebf050e80f3dc576ffbb1295ebeb1176e9fd4a9ec1d151a9e8f4df7457",
|
|
2955
|
+
// Quick, measured in wasm-browser-cli at load 9-20 (15 November, UAT bundle on main): house_two_storey
|
|
2956
|
+
// new build 473 s, as an existing building 365 s (HEM_EPC_Integration_Plan.md, Status).
|
|
2957
|
+
// Full, estimated: 35 min natively at the measured 2.4-2.6x browser ratio (same plan, Measured).
|
|
2958
|
+
status: "preview",
|
|
2959
|
+
typicalRunMinutes: { epc_quick: 8, epc_full: 90 },
|
|
2960
|
+
estimatedRunMinutes: ["epc_full"]
|
|
2961
|
+
};
|
|
2962
|
+
var UNRELEASED_HEM_TARGETS = [
|
|
2963
|
+
HEM_EPC_0_13_2,
|
|
2964
|
+
// The same pins with the HEM Core engine patch set (scripts/hem-targets/stage-python-core.mjs):
|
|
2965
|
+
// byte-identical outputs, faster passive-duct runs. A short-term fix; not the default until the owner's UAT.
|
|
2966
|
+
{ ...HEM_EPC_0_13_2, id: "python-epc-0.13.2-6367f1ec-18032feb-v2", label: "HEM:EPC 0.13.2 (faster)" }
|
|
2967
|
+
];
|
|
2968
|
+
var findHemTarget = (id) => [...HEM_TARGETS, ...UNRELEASED_HEM_TARGETS].find((target2) => target2.id === id);
|
|
670
2969
|
function resolveHemTarget(id) {
|
|
671
|
-
const
|
|
672
|
-
if (!
|
|
673
|
-
return
|
|
2970
|
+
const target2 = findHemTarget(id);
|
|
2971
|
+
if (!target2) throw new Error(`HEM target '${id}' is unavailable. Select a supported target explicitly; saved runs are never upgraded automatically.`);
|
|
2972
|
+
return target2;
|
|
674
2973
|
}
|
|
675
2974
|
function modelArtifacts(manifest2) {
|
|
676
2975
|
const runtime2 = [manifest2.runtime.javascript, manifest2.runtime.wasm];
|
|
677
2976
|
const converter = [manifest2.preparation.javascript, manifest2.preparation.wasm].filter((path) => !runtime2.includes(path));
|
|
678
2977
|
return manifest2.artifacts.filter((artifact) => !artifact.path.startsWith("source/") && !artifact.path.startsWith("notices/") && !converter.includes(artifact.path));
|
|
679
2978
|
}
|
|
680
|
-
function validateTargetManifest(manifest2,
|
|
681
|
-
if (manifest2.bundleId !==
|
|
682
|
-
throw new Error(`Target manifest identity mismatch for ${
|
|
2979
|
+
function validateTargetManifest(manifest2, target2) {
|
|
2980
|
+
if (manifest2.bundleId !== target2.id || manifest2.protocol !== 1 || manifest2.engineCommit !== target2.engineCommit || manifest2.wrapperCommit !== target2.wrapperCommit || manifest2.conversionProfile !== target2.conversionProfile || JSON.stringify(sortedComponents(manifest2.components)) !== JSON.stringify(sortedComponents(target2.components)) || manifest2.productDataSha256 !== target2.productDataSha256) {
|
|
2981
|
+
throw new Error(`Target manifest identity mismatch for ${target2.id}`);
|
|
683
2982
|
}
|
|
2983
|
+
const wrapper = targetWrapper(target2);
|
|
2984
|
+
if (JSON.stringify(Object.keys(target2.components ?? {}).sort()) !== JSON.stringify([...wrapper.componentDistributions].sort())) throw new Error(`${target2.id} must pin exactly the ${target2.wrapper.toUpperCase()} component distributions`);
|
|
684
2985
|
const paths = /* @__PURE__ */ new Set();
|
|
685
2986
|
const sizesByHash = /* @__PURE__ */ new Map();
|
|
686
2987
|
const isRelativePath = (path) => typeof path === "string" && /^[a-zA-Z0-9_./+-]+$/.test(path) && path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
|
|
687
2988
|
for (const artifact of manifest2.artifacts) {
|
|
688
2989
|
if (!isRelativePath(artifact.path) || !/^[a-f0-9]{64}$/.test(artifact.sha256) || !Number.isSafeInteger(artifact.bytes) || artifact.bytes <= 0 || paths.has(artifact.path)) {
|
|
689
|
-
throw new Error(`Invalid artifact in ${
|
|
2990
|
+
throw new Error(`Invalid artifact in ${target2.id}: ${artifact.path}`);
|
|
690
2991
|
}
|
|
691
2992
|
const priorSize = sizesByHash.get(artifact.sha256);
|
|
692
2993
|
if (priorSize !== void 0 && priorSize !== artifact.bytes) throw new Error(`Conflicting sizes for pinned artifact hash ${artifact.sha256}`);
|
|
@@ -697,10 +2998,13 @@ function validateTargetManifest(manifest2, target) {
|
|
|
697
2998
|
if (path.startsWith("source/") || path.startsWith("notices/")) throw new Error(`Runtime/preparation cannot reference reserved source/notice material: ${path}`);
|
|
698
2999
|
if (!paths.has(path)) throw new Error(`Target manifest is missing required artifact ${path}`);
|
|
699
3000
|
}
|
|
700
|
-
if (!manifest2.modes.length || new Set(manifest2.modes).size !== manifest2.modes.length || manifest2.modes.some((mode) => !
|
|
701
|
-
|
|
3001
|
+
if (!manifest2.modes.length || new Set(manifest2.modes).size !== manifest2.modes.length || manifest2.modes.some((mode) => !wrapper.modes.includes(mode))) throw new Error(`Unsupported or duplicate ${target2.wrapper.toUpperCase()} calculation modes`);
|
|
3002
|
+
const { data } = manifest2.runtime;
|
|
3003
|
+
if (!!data !== !!target2.productDataSha256) throw new Error("Runtime product data and its pinned hash must be declared together");
|
|
3004
|
+
if (data && (target2.runtime !== "python" || data.startsWith("source/") || data.startsWith("notices/") || !data.endsWith("/") || !isRelativePath(data.slice(0, -1)) || !manifest2.artifacts.some((artifact) => artifact.path.startsWith(data)))) throw new Error("Runtime product data must be a non-empty relative Python bundle directory ending in /");
|
|
3005
|
+
if (target2.runtime === "rust") {
|
|
702
3006
|
if (!manifest2.runtime.wasm) throw new Error("Rust target manifest is missing its runtime WASM artifact");
|
|
703
|
-
if (manifest2.modes.some((mode) => mode !== "actual") && manifest2.modes.length !== targetWrapper(
|
|
3007
|
+
if (manifest2.modes.some((mode) => mode !== "actual") && manifest2.modes.length !== targetWrapper(target2).modes.length) throw new Error("Rust target modes require actual alone or the complete compliance set");
|
|
704
3008
|
} else {
|
|
705
3009
|
const { index, wheels, requiredVersions } = manifest2.runtime;
|
|
706
3010
|
if (index?.startsWith("source/") || index?.startsWith("notices/")) throw new Error("Python runtime cannot use the reserved source/notice directory");
|
|
@@ -709,10 +3013,196 @@ function validateTargetManifest(manifest2, target) {
|
|
|
709
3013
|
for (const file of ["pyodide.asm.js", "pyodide.asm.wasm", "pyodide-lock.json", "python_stdlib.zip"]) {
|
|
710
3014
|
if (!paths.has(`${index}${file}`)) throw new Error(`Python runtime is missing pinned artifact ${index}${file}`);
|
|
711
3015
|
}
|
|
712
|
-
if (requiredVersions?.[
|
|
713
|
-
throw new Error(`Python runtime must pin matching engine ${
|
|
3016
|
+
if (requiredVersions?.[wrapper.coreDistribution] !== target2.engineVersion || requiredVersions?.[wrapper.wrapperDistribution] !== target2.wrapperVersion) {
|
|
3017
|
+
throw new Error(`Python runtime must pin matching engine ${target2.engineVersion} and wrapper ${target2.wrapperVersion} distributions`);
|
|
3018
|
+
}
|
|
3019
|
+
for (const [distribution, { version }] of Object.entries(target2.components ?? {})) {
|
|
3020
|
+
if (requiredVersions?.[distribution] !== version) throw new Error(`Python runtime must pin ${distribution} ${version}`);
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
var sortedComponents = (components) => Object.entries(components ?? {}).sort(([a], [b]) => a.localeCompare(b));
|
|
3025
|
+
async function bundleDataSha256(artifacts, directory) {
|
|
3026
|
+
const lines = artifacts.filter((artifact) => artifact.path.startsWith(directory)).map((artifact) => `${artifact.path.slice(directory.length)} ${artifact.sha256}
|
|
3027
|
+
`).sort().join("");
|
|
3028
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(lines));
|
|
3029
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
3030
|
+
}
|
|
3031
|
+
|
|
3032
|
+
// ../hem-target-runtime/src/hem/pythonTarget.ts
|
|
3033
|
+
function pythonEpcArguments(modes) {
|
|
3034
|
+
if (modes.length !== 1 || !["quick", "full"].includes(modes[0])) throw new Error(`An EPC calculation runs exactly one of quick or full, not ${modes.join(", ") || "no mode"}`);
|
|
3035
|
+
const quick = modes[0] === "quick";
|
|
3036
|
+
return { skip_smart_metric: quick, skip_fees_metric: quick };
|
|
3037
|
+
}
|
|
3038
|
+
var epc = {
|
|
3039
|
+
initialise(py, _bundleId, data) {
|
|
3040
|
+
if (!data) throw new Error("The EPC target bundle has no product data");
|
|
3041
|
+
py.runPython(`import contextlib, io, json, os
|
|
3042
|
+
os.environ['MPLBACKEND'] = 'Agg'
|
|
3043
|
+
from pathlib import Path
|
|
3044
|
+
import sqlalchemy
|
|
3045
|
+
from sqlalchemy.pool import StaticPool
|
|
3046
|
+
import hem_db_client
|
|
3047
|
+
from hem_db_client.tools.import_data import import_data
|
|
3048
|
+
from hem_core.hem import OutputFormat
|
|
3049
|
+
from hem_epc_orchestrator.orchestrator import Orchestrator
|
|
3050
|
+
vulcan_epc_engine = sqlalchemy.create_engine('sqlite://', poolclass=StaticPool, connect_args={'check_same_thread': False})
|
|
3051
|
+
# import_data returns False when a CSV has a header and no rows; five pinned CSVs are like that.
|
|
3052
|
+
# Any other import failure raises.
|
|
3053
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
3054
|
+
import_data(vulcan_epc_engine, Path(${JSON.stringify(data)}))
|
|
3055
|
+
vulcan_epc_config = Path('/vulcan-epc/db-config.json')
|
|
3056
|
+
vulcan_epc_config.parent.mkdir(parents=True, exist_ok=True)
|
|
3057
|
+
vulcan_epc_config.write_text(json.dumps({'dialect': 'sqlite', 'database': ':memory:'}))
|
|
3058
|
+
import traceback
|
|
3059
|
+
# Calls of the upstream epc.py main, in order, and the stage each starts. Main's later lines are metrics.
|
|
3060
|
+
VULCAN_EPC_MAIN_STAGES = (('model_validate', None), ('create_custom_energy_supply_factors', 'preprocessing'),
|
|
3061
|
+
('smart_controls_24hr_pre_simulation', 'preprocessing'), ('create_core_input', 'preprocessing'),
|
|
3062
|
+
('run_core(', 'core'), ('write_project_outputs', 'core'))
|
|
3063
|
+
def vulcan_epc_stage(error, existing):
|
|
3064
|
+
# The innermost recognised frame names the stage: the Orchestrator's own input parse, its
|
|
3065
|
+
# product substitution (and database), or the line of the wrapper's main that raised.
|
|
3066
|
+
stage = 'unclassified'
|
|
3067
|
+
for frame in traceback.extract_tb(error.__traceback__):
|
|
3068
|
+
if frame.name == 'orchestrator_input': stage = 'input_check'
|
|
3069
|
+
elif frame.name == 'vulcan_epc_estimated_leaks': stage = 'existing_building_conversion'
|
|
3070
|
+
elif frame.name in ('_add_metadata_to_input', '_write_epc_input_file') or '/hem_db_client/' in frame.filename: stage = 'product_lookup'
|
|
3071
|
+
elif frame.filename.endswith('/bin/epc.py') and frame.name == 'main':
|
|
3072
|
+
line = frame.line or ''
|
|
3073
|
+
stage = next(((found or ('existing_building_conversion' if existing else 'input_check')) for call, found in VULCAN_EPC_MAIN_STAGES if call in line), 'metrics')
|
|
3074
|
+
return stage
|
|
3075
|
+
def vulcan_epc_run(input_path, output_dir, options):
|
|
3076
|
+
try:
|
|
3077
|
+
model = json.loads(Path(input_path).read_text())
|
|
3078
|
+
Path(input_path).write_text(json.dumps(vulcan_epc_estimated_leaks(model)))
|
|
3079
|
+
orchestrator = Orchestrator(db_config_file=vulcan_epc_config, input_file=Path(input_path), output_dir=Path(output_dir))
|
|
3080
|
+
orchestrator.client = hem_db_client.Client(engine_url=vulcan_epc_engine)
|
|
3081
|
+
orchestrator.run(**options, core_output_formats=(OutputFormat.CSV,))
|
|
3082
|
+
except Exception as error:
|
|
3083
|
+
existing = json.loads(Path(input_path).read_text()).get('IsExistingBuilding') is True
|
|
3084
|
+
errors = error.errors(include_url=False, include_input=False, include_context=False) if hasattr(error, 'errors') and callable(error.errors) else []
|
|
3085
|
+
# A KeyError's text is only the quoted key, which may be an input field or an internal name.
|
|
3086
|
+
message = f'a value named {error.args[0]} was not found' if isinstance(error, KeyError) and error.args else str(error)
|
|
3087
|
+
return json.dumps({'stage': vulcan_epc_stage(error, existing), 'kind': type(error).__name__, 'message': message,
|
|
3088
|
+
'errors': [{'loc': list(e['loc']), 'type': e['type'], 'msg': e['msg']} for e in errors],
|
|
3089
|
+
'traceback': ''.join(traceback.format_exception(error))})
|
|
3090
|
+
def vulcan_epc_design_heat_loss(source, core_input):
|
|
3091
|
+
# Loaded on use, so a Core without calc_HTC_HLP still runs every other job.
|
|
3092
|
+
import hem_core.project, runpy
|
|
3093
|
+
if not hasattr(hem_core.project, 'calc_HTC_HLP'): return None
|
|
3094
|
+
return runpy.run_path(source)['vulcan_design_heat_loss_file'](core_input)
|
|
3095
|
+
def vulcan_epc_overheating_input(core_input):
|
|
3096
|
+
# Read-only: the core input HEMIE expanded the existing building into, the EPC energy run's own.
|
|
3097
|
+
model = json.loads(Path(core_input).read_text())
|
|
3098
|
+
return json.dumps({key: model[key] for key in ('Zone', 'InfiltrationVentilation')})
|
|
3099
|
+
${EPC_ASSUMPTIONS_PYTHON}`);
|
|
3100
|
+
},
|
|
3101
|
+
call({ input, output, weather }, modes) {
|
|
3102
|
+
if (weather) throw new Error("HEM:EPC runs on its pinned weather; it does not accept a custom weather file");
|
|
3103
|
+
const options = pythonEpcArguments(modes);
|
|
3104
|
+
return `vulcan_epc_run(${JSON.stringify(input)}, ${JSON.stringify(output)}, {'skip_smart_metric': ${options.skip_smart_metric ? "True" : "False"}, 'skip_fees_metric': ${options.skip_fees_metric ? "True" : "False"}})`;
|
|
3105
|
+
},
|
|
3106
|
+
check({ input, output }) {
|
|
3107
|
+
return `vulcan_epc_run(${JSON.stringify(input)}, ${JSON.stringify(output)}, {'preprocess_only': True})`;
|
|
3108
|
+
},
|
|
3109
|
+
designHeatLoss(source, coreInput) {
|
|
3110
|
+
return `vulcan_epc_design_heat_loss(${JSON.stringify(source)}, ${JSON.stringify(coreInput)})`;
|
|
3111
|
+
},
|
|
3112
|
+
overheatingInput(coreInput) {
|
|
3113
|
+
return `vulcan_epc_overheating_input(${JSON.stringify(coreInput)})`;
|
|
3114
|
+
},
|
|
3115
|
+
outputs(files) {
|
|
3116
|
+
const metrics = Object.keys(files).filter((name) => name.endsWith("_metrics.json"));
|
|
3117
|
+
if (metrics.length !== 1) throw new Error(`An EPC run must write exactly one metrics file, found ${metrics.length}`);
|
|
3118
|
+
return files;
|
|
3119
|
+
}
|
|
3120
|
+
};
|
|
3121
|
+
var PYTHON_TARGET_ENTRIES = { epc };
|
|
3122
|
+
var pythonEntry = (target2) => {
|
|
3123
|
+
const entry = PYTHON_TARGET_ENTRIES[target2.wrapper];
|
|
3124
|
+
if (!entry) throw new Error(`${target2.label} has no Python runtime`);
|
|
3125
|
+
return entry;
|
|
3126
|
+
};
|
|
3127
|
+
async function startPythonTarget(py, bundle, target2, artifactUrl, artifactBytes) {
|
|
3128
|
+
const { wheels, requiredVersions, data } = bundle.runtime;
|
|
3129
|
+
if (!wheels?.length || !requiredVersions) throw new Error("Incomplete Python runtime manifest");
|
|
3130
|
+
await py.loadPackage("micropip");
|
|
3131
|
+
const install = (paths) => py.runPythonAsync(`import micropip
|
|
3132
|
+
await micropip.install(${JSON.stringify(paths.map(artifactUrl))}, deps=False, index_urls=[])`);
|
|
3133
|
+
const isNumpy = (path) => path.split("/").pop().startsWith("numpy-");
|
|
3134
|
+
await install(wheels.filter(isNumpy));
|
|
3135
|
+
await py.loadPackage(bundle.runtime.packages ?? []);
|
|
3136
|
+
await install(wheels.filter((path) => !isNumpy(path)));
|
|
3137
|
+
const versions = JSON.parse(py.runPython("import importlib.metadata as m,json\njson.dumps({d.metadata['Name'].lower().replace('_','-'):d.version for d in m.distributions()})"));
|
|
3138
|
+
for (const [name, version] of Object.entries(requiredVersions)) {
|
|
3139
|
+
if (versions[name.toLowerCase().replace(/_/g, "-")] !== version) throw new Error(`Python runtime identity mismatch for ${name}`);
|
|
3140
|
+
}
|
|
3141
|
+
if (data) {
|
|
3142
|
+
if (await bundleDataSha256(bundle.artifacts, data) !== target2.productDataSha256) throw new Error(`Runtime data identity mismatch for ${target2.id}`);
|
|
3143
|
+
for (const artifact of bundle.artifacts.filter((artifact2) => artifact2.path.startsWith(data))) {
|
|
3144
|
+
const path = `/${artifact.path}`;
|
|
3145
|
+
py.FS.mkdirTree(path.slice(0, path.lastIndexOf("/")));
|
|
3146
|
+
py.FS.writeFile(path, await artifactBytes(artifact.path));
|
|
714
3147
|
}
|
|
715
3148
|
}
|
|
3149
|
+
pythonEntry(target2).initialise(py, bundle.bundleId, data ? `/${data}` : void 0);
|
|
3150
|
+
}
|
|
3151
|
+
async function inJobFolder(py, input, run2) {
|
|
3152
|
+
const folder = `/runs/${crypto.randomUUID()}`;
|
|
3153
|
+
py.FS.mkdirTree(folder);
|
|
3154
|
+
py.FS.writeFile(`${folder}/model.json`, input);
|
|
3155
|
+
try {
|
|
3156
|
+
return await run2(folder);
|
|
3157
|
+
} finally {
|
|
3158
|
+
await py.runPythonAsync(`import shutil
|
|
3159
|
+
shutil.rmtree(${JSON.stringify(folder)})`);
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
async function runEntry(py, code, input) {
|
|
3163
|
+
const report = await py.runPythonAsync(code);
|
|
3164
|
+
if (typeof report === "string") throw targetRunError(JSON.parse(report), input);
|
|
3165
|
+
}
|
|
3166
|
+
async function runPythonTargetJob(py, target2, input, modes, weather, heatingProfile) {
|
|
3167
|
+
const entry = pythonEntry(target2);
|
|
3168
|
+
return inJobFolder(py, input, async (folder) => {
|
|
3169
|
+
const weatherPath = weather ? `${folder}/weather.epw` : void 0;
|
|
3170
|
+
if (weather) py.FS.writeFile(weatherPath, weather.epw);
|
|
3171
|
+
if (heatingProfile) throw new Error(`${target2.label} does not support heating profiles`);
|
|
3172
|
+
const output = `${folder}/model__results`;
|
|
3173
|
+
await runEntry(py, entry.call({ input: `${folder}/model.json`, output, weather: weatherPath }, modes), input);
|
|
3174
|
+
const files = Object.fromEntries(py.FS.readdir(output).flatMap((name) => name !== "." && name !== ".." ? [[name, py.FS.readFile(`${output}/${name}`, { encoding: "utf8" })]] : []));
|
|
3175
|
+
return entry.outputs(files, modes);
|
|
3176
|
+
});
|
|
3177
|
+
}
|
|
3178
|
+
async function checkPythonTargetJob(py, target2, input) {
|
|
3179
|
+
const { check } = pythonEntry(target2);
|
|
3180
|
+
if (!check) throw new Error(`${target2.label} has no preprocess-only run`);
|
|
3181
|
+
await inJobFolder(py, input, (folder) => runEntry(py, check({ input: `${folder}/model.json`, output: `${folder}/model__results` }), input));
|
|
3182
|
+
}
|
|
3183
|
+
var NO_PYTHON_DESIGN_HEAT_LOSS = "This HEM target's engine has no static heat loss calculation, so it cannot size the heating.";
|
|
3184
|
+
async function withCoreInput(py, check, input, read) {
|
|
3185
|
+
return inJobFolder(py, input, async (folder) => {
|
|
3186
|
+
const output = `${folder}/model__results`;
|
|
3187
|
+
await runEntry(py, check({ input: `${folder}/model.json`, output }), input);
|
|
3188
|
+
return read(`${output}/preproc.json`, folder);
|
|
3189
|
+
});
|
|
3190
|
+
}
|
|
3191
|
+
async function designHeatLossPythonTargetJob(py, target2, input) {
|
|
3192
|
+
const { check, designHeatLoss } = pythonEntry(target2);
|
|
3193
|
+
if (!check || !designHeatLoss) return { status: "unavailable", reason: NO_PYTHON_DESIGN_HEAT_LOSS };
|
|
3194
|
+
return withCoreInput(py, check, input, async (coreInput, folder) => {
|
|
3195
|
+
const source = `${folder}/epc_design_heat_loss.py`;
|
|
3196
|
+
py.FS.writeFile(source, (await Promise.resolve().then(() => __toESM(require_epc_design_heat_loss(), 1))).default);
|
|
3197
|
+
const loss = await py.runPythonAsync(designHeatLoss(source, coreInput));
|
|
3198
|
+
if (typeof loss !== "string") return { status: "unavailable", reason: NO_PYTHON_DESIGN_HEAT_LOSS };
|
|
3199
|
+
return { status: "ready", model: JSON.parse(py.FS.readFile(coreInput, { encoding: "utf8" })), designHeatLoss: { ...JSON.parse(loss), weatherName: PINNED_WEATHER_NAME } };
|
|
3200
|
+
});
|
|
3201
|
+
}
|
|
3202
|
+
async function overheatingInputPythonTargetJob(py, target2, input) {
|
|
3203
|
+
const { check, overheatingInput } = pythonEntry(target2);
|
|
3204
|
+
if (!check || !overheatingInput) throw new Error(`${target2.label} has no core input for overheating`);
|
|
3205
|
+
return withCoreInput(py, check, input, async (coreInput) => JSON.parse(String(await py.runPythonAsync(overheatingInput(coreInput)))));
|
|
716
3206
|
}
|
|
717
3207
|
|
|
718
3208
|
// ../hem-target-runtime/src/hem/targetAssets.ts
|
|
@@ -852,64 +3342,12 @@ var TargetAssets = class _TargetAssets {
|
|
|
852
3342
|
}
|
|
853
3343
|
};
|
|
854
3344
|
|
|
855
|
-
// ../hem-target-runtime/src/hem/targetSchemaCorrections.ts
|
|
856
|
-
var PYTHON_TARGETS = /* @__PURE__ */ new Set(["python-fhs-a8-f2ab6cf7-8ca182b0-v1", "python-fhs-a9-918addad-b9b90138-v1"]);
|
|
857
|
-
var RUST_A7 = "rust-fhs-a7-62d3df70-c5ba2673-v1";
|
|
858
|
-
var FIELD = "is_adjacent_space_within_dwelling";
|
|
859
|
-
var WARM_AIR_FIELD = "temp_diff_emit_dsgn";
|
|
860
|
-
var STORAGE_FAN_FIELD = "fan_pwr";
|
|
861
|
-
var hasTargetSchemaCorrection = (targetId) => PYTHON_TARGETS.has(targetId) || targetId === RUST_A7;
|
|
862
|
-
var ruleTypes = (rule) => [rule.if?.properties?.type?.const, ...(rule.if?.anyOf ?? []).map((branch) => branch?.properties?.type?.const)].filter((type) => !!type);
|
|
863
|
-
function thenFor(targetId, rules, ...types) {
|
|
864
|
-
const matches = rules.filter((rule) => {
|
|
865
|
-
const own = ruleTypes(rule);
|
|
866
|
-
return own.length === types.length && types.every((type) => own.includes(type));
|
|
867
|
-
});
|
|
868
|
-
if (matches.length !== 1) throw new Error(`Schema correction for ${targetId} no longer applies: ${matches.length} rules for ${types.join(" or ")}`);
|
|
869
|
-
return matches[0].then;
|
|
870
|
-
}
|
|
871
|
-
function correctTargetSchema(targetId, schemaText) {
|
|
872
|
-
if (!hasTargetSchemaCorrection(targetId)) return schemaText;
|
|
873
|
-
const schema = JSON.parse(schemaText);
|
|
874
|
-
const elementRules = schema.properties.Zone.additionalProperties.properties.BuildingElement.additionalProperties.allOf;
|
|
875
|
-
if (targetId === RUST_A7) {
|
|
876
|
-
const window2 = thenFor(targetId, elementRules, "BuildingElementTransparent");
|
|
877
|
-
const shared = schema.$defs.WindowShading;
|
|
878
|
-
const types = shared.items.properties.type.enum;
|
|
879
|
-
if (window2.properties.shading?.$ref !== "#/$defs/WindowShading" || !types.includes("reveal")) {
|
|
880
|
-
throw new Error(`Schema correction for ${targetId} no longer applies`);
|
|
881
|
-
}
|
|
882
|
-
const shading = structuredClone(shared);
|
|
883
|
-
shading.items.properties.type.enum = types.filter((type) => type !== "reveal");
|
|
884
|
-
window2.properties.shading = shading;
|
|
885
|
-
return JSON.stringify(schema);
|
|
886
|
-
}
|
|
887
|
-
const branch = thenFor(
|
|
888
|
-
targetId,
|
|
889
|
-
elementRules,
|
|
890
|
-
"BuildingElementAdjacentConditionedSpace",
|
|
891
|
-
"BuildingElementAdjacentUnconditionedSpace_Simple"
|
|
892
|
-
);
|
|
893
|
-
const spaceHeatRules = schema.properties.SpaceHeatSystem.additionalProperties.allOf;
|
|
894
|
-
const storage = thenFor(targetId, spaceHeatRules, "ElecStorageHeater");
|
|
895
|
-
const warmAir = thenFor(targetId, spaceHeatRules, "WarmAir");
|
|
896
|
-
if (!branch.required.includes(FIELD) || !warmAir.required.includes(WARM_AIR_FIELD) || storage.properties[STORAGE_FAN_FIELD]) {
|
|
897
|
-
throw new Error(`Schema correction for ${targetId} no longer applies`);
|
|
898
|
-
}
|
|
899
|
-
branch.required = branch.required.filter((key) => key !== FIELD);
|
|
900
|
-
warmAir.required = warmAir.required.filter((key) => key !== WARM_AIR_FIELD);
|
|
901
|
-
warmAir.properties[WARM_AIR_FIELD] = false;
|
|
902
|
-
storage.properties[STORAGE_FAN_FIELD] = { type: "number", minimum: 0 };
|
|
903
|
-
storage.required = [...storage.required, STORAGE_FAN_FIELD];
|
|
904
|
-
return JSON.stringify(schema);
|
|
905
|
-
}
|
|
906
|
-
|
|
907
3345
|
// ../hem-target-runtime/src/workers/workerProtocol.ts
|
|
908
3346
|
var FS_REQUEST_TYPE = "file_system";
|
|
909
3347
|
var FS_RESPONSE_TYPE = "file_system_response";
|
|
910
3348
|
|
|
911
3349
|
// ../hem-target-runtime/src/workers/batchWorkerFileSystemBridge.ts
|
|
912
|
-
var DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS =
|
|
3350
|
+
var DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS = 5 * 6e4;
|
|
913
3351
|
var BatchWorkerFileSystemAcknowledgements = class {
|
|
914
3352
|
constructor(timeoutMs = DEFAULT_ACKNOWLEDGEMENT_TIMEOUT_MS) {
|
|
915
3353
|
this.timeoutMs = timeoutMs;
|
|
@@ -944,9 +3382,10 @@ var BatchWorkerFileSystemAcknowledgements = class {
|
|
|
944
3382
|
settled: false
|
|
945
3383
|
};
|
|
946
3384
|
entry.timer = setTimeout(() => {
|
|
3385
|
+
const limit = this.timeoutMs >= 6e4 ? `${Math.round(this.timeoutMs / 6e4)} minutes` : `${Math.round(this.timeoutMs / 1e3)} seconds`;
|
|
947
3386
|
this.settleFailure(
|
|
948
3387
|
request.messageId,
|
|
949
|
-
|
|
3388
|
+
`${request.operation === "write_file" ? "Saving" : "Deleting"} '${request.path}' did not finish within ${limit}. Check that the workspace folder is still available, then run again.`
|
|
950
3389
|
);
|
|
951
3390
|
}, this.timeoutMs);
|
|
952
3391
|
this.pending.set(request.messageId, entry);
|
|
@@ -1005,32 +3444,92 @@ var BatchWorkerFileSystemAcknowledgements = class {
|
|
|
1005
3444
|
}
|
|
1006
3445
|
};
|
|
1007
3446
|
|
|
3447
|
+
// ../hem-target-runtime/src/hem/workspaceName.ts
|
|
3448
|
+
var NON_PORTABLE_NAME_CHARACTERS = /[<>:"|?*]/;
|
|
3449
|
+
var hasControlCharacter = (name) => [...name].some((character) => character.charCodeAt(0) < 32);
|
|
3450
|
+
function isWorkspaceName(name) {
|
|
3451
|
+
return typeof name === "string" && name.trim() !== "" && !/[\\/]/.test(name) && !NON_PORTABLE_NAME_CHARACTERS.test(name) && !hasControlCharacter(name) && !name.startsWith(".") && !/[. ]$/.test(name);
|
|
3452
|
+
}
|
|
3453
|
+
function isRunOutputPath(path) {
|
|
3454
|
+
const segments = path.split("/");
|
|
3455
|
+
return segments[0] === "output" && segments.length > 1 && segments.slice(1).every(isWorkspaceName);
|
|
3456
|
+
}
|
|
3457
|
+
|
|
3458
|
+
// ../hem-target-runtime/src/hem/heatingProfile.ts
|
|
3459
|
+
function parseHeatingProfile(value) {
|
|
3460
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Heating profile must be an object");
|
|
3461
|
+
const profile = value;
|
|
3462
|
+
const keys = profile.type === "reference" ? ["type"] : ["type", "weekday", "weekend", "setback"];
|
|
3463
|
+
if (Object.keys(profile).some((key) => !keys.includes(key))) throw new Error("Unknown heating profile field");
|
|
3464
|
+
if (profile.type === "reference") return { type: "reference" };
|
|
3465
|
+
if (profile.type !== "weekly") throw new Error("Heating profile type must be reference or weekly");
|
|
3466
|
+
if (typeof profile.setback !== "number" || !Number.isFinite(profile.setback) || profile.setback < 0 || profile.setback > 30) throw new Error("Heating setback must be between 0 and 30 C");
|
|
3467
|
+
for (const day of ["weekday", "weekend"]) {
|
|
3468
|
+
const periods = profile[day];
|
|
3469
|
+
if (!Array.isArray(periods) || !periods.length) throw new Error(`Heating ${day} needs at least one period`);
|
|
3470
|
+
let end = 0;
|
|
3471
|
+
for (const period of periods) {
|
|
3472
|
+
if (!Array.isArray(period) || period.length !== 2 || period.some((time) => typeof time !== "number" || !Number.isFinite(time)) || period[0] < 0 || period[1] > 24 || period[0] >= period[1]) throw new Error("Heating periods must be [start, end] within 0\u201324 hours");
|
|
3473
|
+
if (period[0] < end) throw new Error("Heating periods must be ordered without overlap");
|
|
3474
|
+
end = period[1];
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
return structuredClone(profile);
|
|
3478
|
+
}
|
|
3479
|
+
|
|
1008
3480
|
// ../hem-target-runtime/src/hem/preparedRun.ts
|
|
1009
|
-
async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, write2, progress) {
|
|
3481
|
+
async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, write2, progress, check) {
|
|
1010
3482
|
if (manifest2.bundleId !== bundleId) throw new Error("Worker target identity mismatch");
|
|
1011
3483
|
if (!jobs.length) throw new Error("Batch has no prepared jobs");
|
|
1012
3484
|
const allowedModes = new Set(manifest2.modes);
|
|
3485
|
+
const { resultsKind } = targetWrapper(resolveHemTarget(manifest2.bundleId));
|
|
1013
3486
|
const reservedNames = /* @__PURE__ */ new Set(["model.json", "source.csv", "weather.epw", "target-run.json"]);
|
|
1014
|
-
for (const
|
|
1015
|
-
if (
|
|
3487
|
+
for (const job of jobs) {
|
|
3488
|
+
if (!isRunOutputPath(job.outputDirectory)) throw new Error(`Invalid run output path: ${JSON.stringify(job.outputDirectory)}`);
|
|
1016
3489
|
if (!job.modes.length || job.modes.some((mode) => !allowedModes.has(mode))) throw new Error("Unsupported calculation mode for selected target");
|
|
1017
|
-
if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || job.archiveDirectory
|
|
3490
|
+
if (job.archiveDirectory && (!job.archiveDirectory.startsWith(`${job.outputDirectory}/`) || !isRunOutputPath(job.archiveDirectory))) throw new Error(`Invalid archive path: ${JSON.stringify(job.archiveDirectory)}`);
|
|
1018
3491
|
if (job.heatingProfile) {
|
|
1019
3492
|
parseHeatingProfile(job.heatingProfile);
|
|
1020
3493
|
if (job.modes.length !== 1 || job.modes[0] !== "actual") throw new Error("Heating profiles require actual alone; they are not FHS compliance calculations");
|
|
1021
3494
|
}
|
|
3495
|
+
}
|
|
3496
|
+
const scenario = (job) => `Scenario ${job.name}${job.parameterFiles?.length ? ` (${job.parameterFiles.join(", ")})` : ""}`;
|
|
3497
|
+
const traceback = (error) => error instanceof TargetRunError ? { traceback: error.traceback } : {};
|
|
3498
|
+
const located = (error, job) => error instanceof TargetRunError && error.report && job.provenance ? targetRunError(error.report, job.input, job.provenance) : error;
|
|
3499
|
+
if (check) {
|
|
3500
|
+
const failures = [];
|
|
3501
|
+
for (const [index, job] of jobs.entries()) {
|
|
3502
|
+
progress(index, jobs.length, "Checking");
|
|
3503
|
+
try {
|
|
3504
|
+
await check(job.input);
|
|
3505
|
+
} catch (caught) {
|
|
3506
|
+
const error = located(caught, job);
|
|
3507
|
+
failures.push({ job, error, message: error instanceof Error ? error.message : String(error) });
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
for (const { job, error, message } of failures) {
|
|
3511
|
+
const archive = job.archiveDirectory ?? job.outputDirectory;
|
|
3512
|
+
const record = { target: manifest2, jobId, name: job.name, modes: job.modes, status: "failed", check: true, error: message };
|
|
3513
|
+
await write2(`${archive}/model.json`, job.input);
|
|
3514
|
+
await write2(`${archive}/target-run.json`, JSON.stringify({ ...record, ...traceback(error) }));
|
|
3515
|
+
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...record, archive }));
|
|
3516
|
+
}
|
|
3517
|
+
if (failures.length) {
|
|
3518
|
+
throw Object.assign(new Error(failures.map(({ job, message }) => `${scenario(job)}: ${message}`).join("\n")), { cause: failures[0].error });
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
for (const [index, job] of jobs.entries()) {
|
|
1022
3522
|
const archive = job.archiveDirectory ?? job.outputDirectory;
|
|
1023
3523
|
const inputSha256 = await sha256(new TextEncoder().encode(job.input));
|
|
1024
3524
|
if (job.weather && (!job.weather.epw.trim() || await sha256(new TextEncoder().encode(job.weather.epw)) !== job.weather.sha256)) throw new Error("Prepared weather hash mismatch or empty EPW");
|
|
1025
|
-
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, inputSha256, ...job.preparedBy ? { preparedBy: job.preparedBy } : {}, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
|
|
3525
|
+
const provenance = { ...job.weather ? { weather: { path: job.weather.path, sha256: job.weather.sha256 } } : {}, ...job.heatingProfile ? { calculationKind: "operating-sensitivity", heatingProfile: job.heatingProfile } : {}, target: manifest2, resultsKind, inputSha256, ...job.preparedBy ? { preparedBy: job.preparedBy } : {}, modes: job.modes, jobId, ...job.startedAt ? { startedAt: job.startedAt } : {}, name: job.name, ...job.warnings?.length ? { warnings: job.warnings } : {} };
|
|
1026
3526
|
try {
|
|
1027
3527
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "running" }));
|
|
1028
|
-
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
|
|
1029
3528
|
await write2(`${archive}/model.json`, job.input);
|
|
1030
3529
|
if (job.sourceCsv) await write2(`${archive}/source.csv`, job.sourceCsv);
|
|
1031
3530
|
if (job.weather) await write2(`${archive}/weather.epw`, job.weather.epw);
|
|
1032
3531
|
progress(index, jobs.length);
|
|
1033
|
-
const files = await execute(job.input, job.modes, job.weather, job.heatingProfile);
|
|
3532
|
+
const files = await execute(job.input, job.modes, job.weather, job.heatingProfile, job.detailedHeating);
|
|
1034
3533
|
const names = Object.keys(files);
|
|
1035
3534
|
if (!names.length) throw new Error("Calculation produced no result files");
|
|
1036
3535
|
for (const [name, content] of Object.entries(files)) {
|
|
@@ -1038,23 +3537,25 @@ async function executePreparedJobs(manifest2, bundleId, jobId, jobs, execute, wr
|
|
|
1038
3537
|
await write2(`${archive}/${name}`, content);
|
|
1039
3538
|
}
|
|
1040
3539
|
if (archive !== job.outputDirectory) {
|
|
3540
|
+
await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "running", archive }));
|
|
1041
3541
|
for (const [name, content] of Object.entries(files)) await write2(`${job.outputDirectory}/${name}`, content);
|
|
1042
|
-
await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names, archive }));
|
|
1043
3542
|
}
|
|
1044
3543
|
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names }));
|
|
1045
|
-
|
|
3544
|
+
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "complete", files: names, archive }));
|
|
3545
|
+
} catch (caught) {
|
|
3546
|
+
const error = located(caught, job);
|
|
1046
3547
|
const message = error instanceof Error ? error.message : String(error);
|
|
1047
|
-
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message }));
|
|
3548
|
+
await write2(`${archive}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, ...traceback(error) }));
|
|
1048
3549
|
if (archive !== job.outputDirectory) await write2(`${job.outputDirectory}/target-run.json`, JSON.stringify({ ...provenance, status: "failed", error: message, archive }));
|
|
1049
|
-
|
|
1050
|
-
throw new Error(`Scenario ${job.name}${files}: ${message}`);
|
|
3550
|
+
throw Object.assign(new Error(`${scenario(job)}: ${message}`), { cause: error });
|
|
1051
3551
|
}
|
|
1052
3552
|
}
|
|
1053
3553
|
}
|
|
1054
3554
|
|
|
1055
|
-
// ../hem-target-runtime/src/hem/
|
|
3555
|
+
// ../hem-target-runtime/src/hem/pythonTargetWorker.ts
|
|
1056
3556
|
var runtime;
|
|
1057
3557
|
var manifest;
|
|
3558
|
+
var target;
|
|
1058
3559
|
var busy = false;
|
|
1059
3560
|
var acknowledgements = new BatchWorkerFileSystemAcknowledgements();
|
|
1060
3561
|
var send = (message) => self.postMessage(message);
|
|
@@ -1065,15 +3566,15 @@ async function write(path, content) {
|
|
|
1065
3566
|
await acknowledgements.waitForPending();
|
|
1066
3567
|
}
|
|
1067
3568
|
async function initialize(bundle) {
|
|
1068
|
-
const
|
|
1069
|
-
validateTargetManifest(bundle,
|
|
1070
|
-
if (
|
|
3569
|
+
const selected = resolveHemTarget(bundle.bundleId);
|
|
3570
|
+
validateTargetManifest(bundle, selected);
|
|
3571
|
+
if (selected.runtime !== "python") throw new Error("Python worker requires a Python target");
|
|
1071
3572
|
const assets = await TargetAssets.open();
|
|
1072
3573
|
const responses = /* @__PURE__ */ new Map();
|
|
3574
|
+
const artifactUrl = (path) => new URL(`/hem-targets/${bundle.bundleId}/${path}`, self.location.origin).href;
|
|
1073
3575
|
await Promise.all(modelArtifacts(bundle).map(async (artifact) => {
|
|
1074
3576
|
const bytes = await assets.bytes(artifact);
|
|
1075
|
-
|
|
1076
|
-
responses.set(url, new Response(bytes, { headers: { "Content-Type": artifact.path.endsWith(".wasm") ? "application/wasm" : "application/octet-stream" } }));
|
|
3577
|
+
responses.set(artifactUrl(artifact.path), new Response(bytes, { headers: { "Content-Type": artifact.path.endsWith(".wasm") ? "application/wasm" : "application/octet-stream" } }));
|
|
1077
3578
|
}));
|
|
1078
3579
|
self.fetch = async (input) => {
|
|
1079
3580
|
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, self.location.origin).href;
|
|
@@ -1081,10 +3582,13 @@ async function initialize(bundle) {
|
|
|
1081
3582
|
if (!response) throw new Error(`Python attempted to load an artifact outside its pinned bundle: ${url}`);
|
|
1082
3583
|
return response.clone();
|
|
1083
3584
|
};
|
|
1084
|
-
const
|
|
1085
|
-
const response = responses.get(
|
|
3585
|
+
const artifactBytes = async (path) => {
|
|
3586
|
+
const response = responses.get(artifactUrl(path));
|
|
1086
3587
|
if (!response) throw new Error(`Missing executable artifact ${path}`);
|
|
1087
|
-
|
|
3588
|
+
return new Uint8Array(await response.clone().arrayBuffer());
|
|
3589
|
+
};
|
|
3590
|
+
const importAsset = async (path) => {
|
|
3591
|
+
const url = URL.createObjectURL(new Blob([await artifactBytes(path)], { type: "text/javascript" }));
|
|
1088
3592
|
try {
|
|
1089
3593
|
return await import(
|
|
1090
3594
|
/* @vite-ignore */
|
|
@@ -1095,58 +3599,34 @@ async function initialize(bundle) {
|
|
|
1095
3599
|
}
|
|
1096
3600
|
};
|
|
1097
3601
|
const index = bundle.runtime.index;
|
|
1098
|
-
if (!index
|
|
3602
|
+
if (!index) throw new Error("Incomplete Python runtime manifest");
|
|
1099
3603
|
await importAsset(`${index}pyodide.asm.js`);
|
|
1100
3604
|
const { loadPyodide } = await importAsset(bundle.runtime.javascript);
|
|
1101
|
-
|
|
1102
|
-
indexURL:
|
|
3605
|
+
const py = await loadPyodide({
|
|
3606
|
+
indexURL: artifactUrl(index),
|
|
1103
3607
|
stdout: (message) => send({ type: "worker_log", message }),
|
|
1104
3608
|
stderr: (message) => send({ type: "worker_log", message })
|
|
1105
3609
|
});
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
const install = (paths) => py.runPythonAsync(`import micropip
|
|
1109
|
-
await micropip.install(${JSON.stringify(paths.map((path) => new URL(`/hem-targets/${bundle.bundleId}/${path}`, self.location.origin).href))}, index_urls=[])`);
|
|
1110
|
-
await install(bundle.runtime.wheels.filter((path) => path.split("/").pop().startsWith("numpy-")));
|
|
1111
|
-
await py.loadPackage(bundle.runtime.packages ?? []);
|
|
1112
|
-
await install(bundle.runtime.wheels.filter((path) => !path.split("/").pop().startsWith("numpy-")));
|
|
1113
|
-
py.runPython(`import os
|
|
1114
|
-
os.environ['MPLBACKEND']='Agg'
|
|
1115
|
-
from ${targetWrapper(target).pythonModule} import main`);
|
|
1116
|
-
const versions = JSON.parse(py.runPython("import importlib.metadata as m,json\njson.dumps({d.metadata['Name'].lower().replace('_','-'):d.version for d in m.distributions()})"));
|
|
1117
|
-
for (const [name, version] of Object.entries(bundle.runtime.requiredVersions)) {
|
|
1118
|
-
if (versions[name.toLowerCase().replace(/_/g, "-")] !== version) throw new Error(`Python runtime identity mismatch for ${name}`);
|
|
1119
|
-
}
|
|
1120
|
-
if (hasTargetSchemaCorrection(bundle.bundleId)) {
|
|
1121
|
-
const schemaPath = py.runPython(`import os, future_homes_standard.schema_validation as v
|
|
1122
|
-
os.path.join(os.path.dirname(v.__file__), 'schema.json')`);
|
|
1123
|
-
py.FS.writeFile(schemaPath, correctTargetSchema(bundle.bundleId, py.FS.readFile(schemaPath, { encoding: "utf8" })));
|
|
1124
|
-
}
|
|
3610
|
+
await startPythonTarget(py, bundle, selected, artifactUrl, artifactBytes);
|
|
3611
|
+
runtime = py;
|
|
1125
3612
|
manifest = bundle;
|
|
3613
|
+
target = selected;
|
|
1126
3614
|
send({ type: "worker_ready", targetBundleId: bundle.bundleId });
|
|
1127
3615
|
}
|
|
1128
3616
|
async function run(jobId, bundleId, jobs) {
|
|
1129
|
-
if (!runtime || !manifest) throw new Error("Python worker is not initialized");
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
const compliance = buildPythonFhsComplianceReport(files, modes);
|
|
1143
|
-
if (compliance) files["fhs_compliance_report.json"] = JSON.stringify(compliance);
|
|
1144
|
-
return files;
|
|
1145
|
-
} finally {
|
|
1146
|
-
await py.runPythonAsync(`import shutil
|
|
1147
|
-
shutil.rmtree(${JSON.stringify(folder)})`);
|
|
1148
|
-
}
|
|
1149
|
-
}, write, (completed, total) => send({ type: "progress", jobId, progress: { completed, total, status: "Calculating" } }));
|
|
3617
|
+
if (!runtime || !manifest || !target) throw new Error("Python worker is not initialized");
|
|
3618
|
+
const [py, selected] = [runtime, target];
|
|
3619
|
+
const check = jobs.length > 1 && PYTHON_TARGET_ENTRIES[selected.wrapper]?.check ? (input) => checkPythonTargetJob(py, selected, input) : void 0;
|
|
3620
|
+
await executePreparedJobs(
|
|
3621
|
+
manifest,
|
|
3622
|
+
bundleId,
|
|
3623
|
+
jobId,
|
|
3624
|
+
jobs,
|
|
3625
|
+
(input, modes, weather, heatingProfile) => runPythonTargetJob(py, selected, input, modes, weather, heatingProfile),
|
|
3626
|
+
write,
|
|
3627
|
+
(completed, total, status) => send({ type: "progress", jobId, progress: { completed, total, status: status ?? "Calculating" } }),
|
|
3628
|
+
check
|
|
3629
|
+
);
|
|
1150
3630
|
send({ type: "complete", jobId, targetBundleId: bundleId, result: { status: "success", targetBundleId: bundleId } });
|
|
1151
3631
|
}
|
|
1152
3632
|
self.onmessage = async ({ data }) => {
|
|
@@ -1162,22 +3642,45 @@ self.onmessage = async ({ data }) => {
|
|
|
1162
3642
|
try {
|
|
1163
3643
|
if (data.type === "initialize") await initialize(data.manifest);
|
|
1164
3644
|
else if (data.type === "run_prepared_batch") await run(data.jobId, data.targetBundleId, data.jobs);
|
|
1165
|
-
else
|
|
3645
|
+
else if (data.type === "design_heat_loss") {
|
|
3646
|
+
if (!runtime || !target) throw new Error("Python worker is not initialized");
|
|
3647
|
+
send({ type: "design_heat_loss_result", jobId: data.jobId, result: await designHeatLossPythonTargetJob(runtime, target, data.input) });
|
|
3648
|
+
} else if (data.type === "overheating_input") {
|
|
3649
|
+
if (!runtime || !target) throw new Error("Python worker is not initialized");
|
|
3650
|
+
send({ type: "overheating_input_result", jobId: data.jobId, result: await overheatingInputPythonTargetJob(runtime, target, data.input) });
|
|
3651
|
+
} else throw new Error(`Unsupported Python worker message ${data.type}`);
|
|
1166
3652
|
} catch (error) {
|
|
1167
3653
|
const text = error instanceof Error ? error.message : String(error);
|
|
1168
3654
|
console.error(text);
|
|
1169
|
-
|
|
3655
|
+
const failure = targetRunFailureOf(error);
|
|
3656
|
+
send({ type: data.type === "initialize" ? "init_error" : "error", jobId: data.jobId, error: failure ? text : pythonFailureMessage(text), ...failure ? { failure } : {} });
|
|
1170
3657
|
} finally {
|
|
1171
3658
|
busy = false;
|
|
1172
3659
|
}
|
|
1173
3660
|
};
|
|
1174
3661
|
/*! Bundled license information:
|
|
1175
3662
|
|
|
1176
|
-
|
|
1177
|
-
(
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
3663
|
+
polygon-clipping/dist/polygon-clipping.umd.js:
|
|
3664
|
+
(**
|
|
3665
|
+
* splaytree v3.1.2
|
|
3666
|
+
* Fast Splay tree for Node and browser
|
|
3667
|
+
*
|
|
3668
|
+
* @author Alexander Milevski <info@w8r.name>
|
|
3669
|
+
* @license MIT
|
|
3670
|
+
* @preserve
|
|
3671
|
+
*)
|
|
3672
|
+
(*! *****************************************************************************
|
|
3673
|
+
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3674
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
3675
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
3676
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
3677
|
+
|
|
3678
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
3679
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
3680
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
3681
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
3682
|
+
|
|
3683
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
|
3684
|
+
and limitations under the License.
|
|
3685
|
+
***************************************************************************** *)
|
|
1183
3686
|
*/
|