Repository navigation
Expand file tree
/
Copy pathperiphery.cpp
More file actions
5887 lines (5153 loc) · 192 KB
/
Copy pathperiphery.cpp
File metadata and controls
5887 lines (5153 loc) · 192 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Copyright (C) Svetlin Tassev
// This file is part of CrochetPARADE.
// CrochetPARADE is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later version.
// CrochetPARADE is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with CrochetPARADE. If not, see <https://www.gnu.org/licenses/>.
// periphery.cpp
// C++ port of periphery.js (faithful, deterministic, same algorithm and option semantics).
//
// Exports (C ABI for Emscripten ccall):
// - const char* find_periphery(const char* dot_simple, int Kmax, int N, const char* opts_json)
// Returns a malloc-allocated UTF-8 JSON string. Caller should free via Module._free.
// On cooperative cancellation, returns the literal "__CANCELLED__" (also malloc-allocated).
// - void cancel_periphery()
//
// NOTE: This file intentionally mirrors the JS implementation structure and tie-breaks.
// Do NOT "optimize away" ordering; insertion-order behavior is significant.
#include <algorithm>
#include <atomic>
#include <array>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <functional>
#include <limits>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using std::string;
using std::vector;
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
static inline void wasm_log_progress(const char* stage, int pct, int done, int total) {
EM_ASM({
var stage = UTF8ToString($0);
console.log("[periphery wasm] " + stage + ": " + $1 + "% (" + $2 + "/" + $3 + ")");
}, stage, pct, done, total);
}
\
static inline void wasm_log_msg(const char* msg) {
EM_ASM({
console.log(UTF8ToString($0));
}, msg);
}
#else
static inline void wasm_log_progress(const char* /*stage*/, int /*pct*/, int /*done*/, int /*total*/) {}
static inline void wasm_log_msg(const char* /*msg*/) {}
#endif
struct ProgressLogger {
std::string stage;
int total = 0;
int minStep = 1;
int lastPct = -1;
ProgressLogger(const std::string& s, int t, int step = 1) : stage(s), total(t), minStep(step), lastPct(-1) {
if (total <= 0) {
// still emit a start line so you can tell the stage began
wasm_log_progress(stage.c_str(), 0, 0, total);
lastPct = 0;
} else {
wasm_log_progress(stage.c_str(), 0, 0, total);
lastPct = 0;
}
}
void update(int done) {
if (total <= 0) return;
if (done < 0) done = 0;
if (done > total) done = total;
int pct = (int)((100LL * done) / total);
if (pct >= lastPct + minStep || pct == 100) {
lastPct = pct;
wasm_log_progress(stage.c_str(), pct, done, total);
}
}
void finish() {
if (total > 0) update(total);
}
};
static std::atomic<bool> g_cancel(false);
// Current component being ordered (for verbose progress logging in heavy subroutines).
static int g_log_comp_idx = 0;
static int g_log_comp_total = 0;
extern "C" void cancel_periphery() { g_cancel.store(true, std::memory_order_relaxed); }
extern "C" void cancel_find_periphery() { cancel_periphery(); }
struct CancelledException {};
static inline void CHECK_CANCEL() {
if (g_cancel.load(std::memory_order_relaxed)) throw CancelledException{};
}
static inline char* dup_cstr(const std::string& s) {
char* out = (char*)std::malloc(s.size() + 1);
if (!out) return nullptr;
std::memcpy(out, s.c_str(), s.size() + 1);
return out;
}
template <typename T>
static int compareArraysLex(const std::vector<T>& a, const std::vector<T>& b) {
const size_t n = std::min(a.size(), b.size());
for (size_t i = 0; i < n; i++) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
if (a.size() < b.size()) return -1;
if (a.size() > b.size()) return 1;
return 0;
}
// ---------- OrderedSet (insertion-ordered like JS Set) ----------
template <typename T, typename Hash = std::hash<T>, typename Eq = std::equal_to<T>>
struct OrderedSet {
std::vector<T> items;
std::unordered_set<T, Hash, Eq> set;
bool has(const T& v) const { return set.find(v) != set.end(); }
bool insert(const T& v) {
auto [it, ok] = set.insert(v);
if (ok) items.push_back(v);
return ok;
}
size_t size() const { return items.size(); }
void clear() {
items.clear();
set.clear();
}
};
// ---------- VertexMap ----------
struct VertexMap {
std::unordered_map<std::string, int> label2id;
std::vector<std::string> id2label; // 0-based storage, ids are 1-based
int getVertexId(const std::string& label) {
auto it = label2id.find(label);
if (it != label2id.end()) return it->second;
const int id = (int)id2label.size() + 1;
id2label.push_back(label);
label2id.emplace(label, id);
return id;
}
const std::string& labelOf(int id) const { return id2label[(size_t)id - 1]; }
int size() const { return (int)id2label.size(); }
};
// ---------- DOT parsing (matches /"([^"]+)"\s*--\s*"([^"]+)"/g ) ----------
static std::vector<std::pair<std::string, std::string>> parseDotStringEdges(const std::string& s, ProgressLogger* prog = nullptr) {
// Faithfully matches the JS regex: /"([^"]+)"\s*--\s*"([^"]+)"/g
// After the first closing quote, ONLY whitespace may appear before `--`.
std::vector<std::pair<std::string, std::string>> edges;
size_t pos = 0;
const size_t n = s.size();
while (pos < n) {
CHECK_CANCEL();
size_t q1 = s.find('"', pos);
if (q1 == std::string::npos) break;
size_t q2 = s.find('"', q1 + 1);
if (q2 == std::string::npos) break;
std::string a = s.substr(q1 + 1, q2 - (q1 + 1));
size_t i = q2 + 1;
while (i < n && std::isspace((unsigned char)s[i])) i++;
if (!(i + 1 < n && s[i] == '-' && s[i + 1] == '-')) {
pos = q2 + 1;
if (prog) prog->update((int)pos);
continue;
}
i += 2;
while (i < n && std::isspace((unsigned char)s[i])) i++;
if (i >= n || s[i] != '"') {
pos = q2 + 1;
if (prog) prog->update((int)pos);
continue;
}
size_t q3 = i;
size_t q4 = s.find('"', q3 + 1);
if (q4 == std::string::npos) break;
std::string b = s.substr(q3 + 1, q4 - (q3 + 1));
edges.emplace_back(std::move(a), std::move(b));
pos = q4 + 1;
if (prog) prog->update((int)pos);
}
if (prog) prog->finish();
return edges;
}
static int parseDotLeadingDimension(const std::string& s) {
// dot_simple starts with a line containing DIM (e.g. "3\n").
size_t nl = s.find('\n');
std::string first = (nl == std::string::npos) ? s : s.substr(0, nl);
// trim
size_t a = 0;
while (a < first.size() && std::isspace((unsigned char)first[a])) a++;
size_t b = first.size();
while (b > a && std::isspace((unsigned char)first[b - 1])) b--;
if (b <= a) return 0;
return std::atoi(first.substr(a, b - a).c_str());
}
struct PosTable {
int dim = 0;
std::vector<std::array<double,3>> xyz; // 1..n (index 0 unused)
std::vector<uint8_t> has; // 1..n
};
static PosTable parseDotStringNodePositions(const std::string& s, const VertexMap& vm, int dim) {
PosTable t;
t.dim = dim;
t.xyz.resize((size_t)vm.size() + 1, {0.0, 0.0, 0.0});
t.has.assign((size_t)vm.size() + 1, 0);
auto parseCoords = [&](const std::string& inside, std::array<double,3>& out)->bool{
const char* p = inside.c_str();
char* endp = nullptr;
// x
while (*p && std::isspace((unsigned char)*p)) p++;
double x = std::strtod(p, &endp);
if (endp == p) return false;
p = endp;
while (*p && (std::isspace((unsigned char)*p) || *p == ',')) p++;
// y
double y = std::strtod(p, &endp);
if (endp == p) return false;
p = endp;
while (*p && (std::isspace((unsigned char)*p) || *p == ',')) p++;
// z (optional; default 0)
double z = 0.0;
if (*p) {
z = std::strtod(p, &endp);
if (endp == p) z = 0.0;
}
out = {x, y, (dim == 3 ? z : 0.0)};
return true;
};
// Scan for: "label" {x,y,z}
size_t pos = 0;
const size_t n = s.size();
while (pos < n) {
CHECK_CANCEL();
size_t q1 = s.find('"', pos);
if (q1 == std::string::npos) break;
size_t q2 = s.find('"', q1 + 1);
if (q2 == std::string::npos) break;
std::string lab = s.substr(q1 + 1, q2 - (q1 + 1));
size_t i = q2 + 1;
while (i < n && std::isspace((unsigned char)s[i])) i++;
if (i < n && s[i] == '{') {
size_t j = s.find('}', i + 1);
if (j == std::string::npos) break;
std::string inside = s.substr(i + 1, j - (i + 1));
auto it = vm.label2id.find(lab);
if (it != vm.label2id.end()) {
int id = it->second;
std::array<double,3> xyz;
if (parseCoords(inside, xyz)) {
t.xyz[(size_t)id] = xyz;
t.has[(size_t)id] = 1;
}
}
pos = j + 1;
continue;
}
pos = q2 + 1;
}
return t;
}
// ---------- Canonical label check: /^\d+,\d+\|\d+$/ ----------
static bool isCanonicalLabel(const std::string& lab) {
size_t i = 0;
auto isdig = [](unsigned char c) { return std::isdigit(c) != 0; };
if (lab.empty()) return false;
// digits
size_t start = i;
while (i < lab.size() && isdig((unsigned char)lab[i])) i++;
if (i == start) return false;
if (i >= lab.size() || lab[i] != ',') return false;
i++;
start = i;
while (i < lab.size() && isdig((unsigned char)lab[i])) i++;
if (i == start) return false;
if (i >= lab.size() || lab[i] != '|') return false;
i++;
start = i;
while (i < lab.size() && isdig((unsigned char)lab[i])) i++;
if (i == start) return false;
return i == lab.size();
}
static int parseCanonicalK(const std::string& lab) {
size_t bar = lab.rfind('|');
if (bar == std::string::npos) return 0;
return std::atoi(lab.c_str() + bar + 1);
}
// ---------- SimpleGraph with insertion-ordered adjacency ----------
struct SimpleGraph {
int n = 0;
std::vector<std::vector<int>> adj; // 1..n
std::vector<std::unordered_set<int>> adjSet; // membership to prevent dups
explicit SimpleGraph(int n_) : n(n_), adj((size_t)n_ + 1), adjSet((size_t)n_ + 1) {}
void addEdge(int u, int v) {
if (u == v) return;
if (adjSet[(size_t)u].insert(v).second) adj[(size_t)u].push_back(v);
if (adjSet[(size_t)v].insert(u).second) adj[(size_t)v].push_back(u);
}
const std::vector<int>& neighbors(int u) const {
static const std::vector<int> empty;
if (u < 1 || u > n) return empty;
return adj[(size_t)u];
}
};
// ---------- reduced_internal_range_js ----------
static std::pair<int,int> reduced_internal_range_js(const std::vector<int>& p, const std::vector<bool>& is_canonical) {
const int L = (int)p.size();
int s_idx = 1;
int e_idx = L - 2;
if (!is_canonical[(size_t)p[0]]) {
bool found = false;
for (int j = 1; j <= e_idx; j++) {
if (is_canonical[(size_t)p[j]]) {
s_idx = j + 1;
found = true;
break;
}
}
if (!found) s_idx = e_idx + 1;
}
if (!is_canonical[(size_t)p[L - 1]]) {
bool found = false;
const int lowerBound = std::max(1, s_idx);
for (int j = L - 2; j >= lowerBound; j--) {
if (is_canonical[(size_t)p[j]]) {
e_idx = j - 1;
found = true;
break;
}
}
if (!found) e_idx = s_idx - 1;
}
return {s_idx, e_idx};
}
// ---------- simple_paths_u_v (DFS) ----------
static std::vector<std::vector<int>> simple_paths_u_v(const SimpleGraph& g, int u, int v, int Kmax) {
std::vector<std::vector<int>> results;
std::vector<char> visited((size_t)g.n + 1, 0);
std::vector<int> path;
std::function<void()> dfs = [&]() {
CHECK_CANCEL();
int cur = path.back();
int len_edges = (int)path.size() - 1;
if (len_edges > Kmax) return;
if (cur == v && len_edges >= 2) {
results.push_back(path);
return;
}
for (int w : g.neighbors(cur)) {
if (!visited[(size_t)w]) {
visited[(size_t)w] = 1;
path.push_back(w);
dfs();
path.pop_back();
visited[(size_t)w] = 0;
}
}
};
visited[(size_t)u] = 1;
path.push_back(u);
dfs();
path.pop_back();
visited[(size_t)u] = 0;
return results;
}
// ---------- EdgeKey ----------
static inline std::string EdgeKey(int u, int v) {
if (u < v) return std::to_string(u) + "," + std::to_string(v);
return std::to_string(v) + "," + std::to_string(u);
}
// ---------- Ordered adjacency built from edge keys ----------
struct OrderedAdj {
// NOTE: Edge keys are already unique (EdgeKey(min,max)), so per-node duplicate checks are unnecessary here.
// We preserve insertion order by:
// - scanning edgeKeys.items in order
// - pushing endpoints into `keys` the first time they are seen
// - pushing neighbors into adjacency lists in that same scan order
std::vector<int> keys; // insertion order of node keys
std::unordered_set<int> keyset;
std::unordered_map<int, std::vector<int>> adj;
void ensure(int u) {
if (keyset.insert(u).second) keys.push_back(u);
if (adj.find(u) == adj.end()) adj.emplace(u, std::vector<int>{});
}
void add(int u, int v) {
ensure(u);
ensure(v);
// Edge keys are unique, so (u,v) cannot appear twice in the input edge set.
adj[u].push_back(v);
adj[v].push_back(u);
}
const std::vector<int>& neighbors(int u) const {
static const std::vector<int> empty;
auto it = adj.find(u);
if (it == adj.end()) return empty;
return it->second;
}
bool hasKey(int u) const { return keyset.find(u) != keyset.end(); }
};
static OrderedAdj buildAdjFromEdgeKeys(const OrderedSet<std::string>& edgeKeys) {
OrderedAdj adj;
// Reserve to reduce rehashing/allocation churn on large graphs.
adj.keys.reserve(edgeKeys.size() * 2 + 8);
adj.keyset.reserve(edgeKeys.size() * 2 + 8);
adj.adj.reserve(edgeKeys.size() * 2 + 8);
for (const auto& ek : edgeKeys.items) {
CHECK_CANCEL();
size_t comma = ek.find(',');
if (comma == std::string::npos) continue;
int u = std::atoi(ek.c_str());
int v = std::atoi(ek.c_str() + comma + 1);
adj.add(u, v);
}
return adj;
}
static std::unordered_map<int,int> degreesFromAdj(const OrderedAdj& adj, const OrderedSet<int>& nodesSet) {
std::unordered_map<int,int> deg;
deg.reserve(nodesSet.items.size() * 2);
for (int u : nodesSet.items) {
CHECK_CANCEL();
auto it = adj.adj.find(u);
int d = (it == adj.adj.end()) ? 0 : (int)it->second.size();
deg.emplace(u, d);
}
return deg;
}
// ---------- Options parsing (strict JS semantics) ----------
struct Options {
int leap_max = 0;
bool include_bridge_edges_in_output = false;
bool include_longest_cycle_subgraph = false;
bool include_breaking_cycle_subgraph = false;
bool export_stl = false;
bool export_obj = false;
// Mesh cleanup options (applied only when stl_repair is enabled; affects STL and OBJ exports).
bool stl_repair = false;
// Optional pre-pass: weld/snap vertices within eps before cleanup (0 disables).
// This modifies the output STL/OBJ geometry/topology only (does not affect periphery detection).
double stl_snap_eps = 0.0; // distance threshold (in the model's 3D coordinate units)
// Optional cleanup: drop disconnected triangle components whose area is tiny relative to the largest.
// 0 disables. Example: 0.001 drops components with <0.1% of largest component area.
double stl_drop_component_area_frac = 0.0;
};
static inline bool is_json_delim(char c) {
return c == ',' || c == '}' || c == ']' || std::isspace((unsigned char)c);
}
static bool extract_json_token(const std::string& json, const std::string& key, std::string& tokenOut) {
// naive key search for "key" : <token>
// This is sufficient because we only accept flat option objects.
const std::string pat = "\"" + key + "\"";
size_t pos = json.find(pat);
if (pos == std::string::npos) return false;
pos = json.find(':', pos + pat.size());
if (pos == std::string::npos) return false;
pos++;
while (pos < json.size() && std::isspace((unsigned char)json[pos])) pos++;
if (pos >= json.size()) return false;
size_t start = pos;
// string
if (json[pos] == '"') {
pos++;
while (pos < json.size()) {
if (json[pos] == '\\') { pos += 2; continue; }
if (json[pos] == '"') { pos++; break; }
pos++;
}
tokenOut = json.substr(start, pos - start);
return true;
}
// literal/number
while (pos < json.size() && !is_json_delim(json[pos])) pos++;
tokenOut = json.substr(start, pos - start);
return true;
}
static Options parseOptions(const char* opts_json_cstr) {
Options o;
if (!opts_json_cstr) return o;
std::string json(opts_json_cstr);
std::string tok;
// leap_max_raw = opts.leap_max ?? 0; leap_max = clamp(trunc(raw),0..8)
double leap_raw = 0.0;
if (extract_json_token(json, "leap_max", tok)) {
if (tok == "null") {
leap_raw = 0.0;
} else {
// If token begins with quote => not number => NaN-like => defaults to 0 per JS trunc + clamp?
// In JS, Math.trunc("foo") => NaN, Math.min/max propagate NaN => leap_max becomes NaN,
// but later used in comparisons; however UI only supplies numbers. We treat non-number as 0.
char* endp = nullptr;
leap_raw = std::strtod(tok.c_str(), &endp);
if (endp == tok.c_str()) leap_raw = 0.0;
}
}
int leap_tr = (int)std::trunc(leap_raw); // trunc toward zero
if (leap_tr < 0) leap_tr = 0;
if (leap_tr > 8) leap_tr = 8;
o.leap_max = leap_tr;
auto parseStrictTrue = [&](const std::string& key)->bool{
std::string t;
if (!extract_json_token(json, key, t)) return false;
// (value ?? false) === true => true only if literal true
return t == "true";
};
o.include_bridge_edges_in_output = parseStrictTrue("include_bridge_edges_in_output");
o.include_longest_cycle_subgraph = parseStrictTrue("include_longest_cycle_subgraph");
o.include_breaking_cycle_subgraph = parseStrictTrue("include_breaking_cycle_subgraph");
o.export_stl = parseStrictTrue("export_stl");
o.export_obj = parseStrictTrue("export_obj");
o.stl_repair = parseStrictTrue("stl_repair");
auto parseNumOr = [&](const std::string& key, double def)->double{
std::string t;
if (!extract_json_token(json, key, t)) return def;
if (t == "null") return def;
char* endp = nullptr;
double v = std::strtod(t.c_str(), &endp);
if (endp == t.c_str()) return def;
return v;
};
// STL cleanup options (numbers; parsed with JS-like "null => default" behavior).
{
double e = parseNumOr("stl_snap_eps", o.stl_snap_eps);
if (std::isfinite(e) && e >= 0.0) o.stl_snap_eps = e;
}
{
double f = parseNumOr("stl_drop_component_area_frac", o.stl_drop_component_area_frac);
if (std::isfinite(f) && f > 0.0) o.stl_drop_component_area_frac = f;
}
return o;
}
// ---------- JSON escaping ----------
static std::string jsonEscape(const std::string& s) {
std::string out;
out.reserve(s.size() + 8);
for (unsigned char c : s) {
switch (c) {
case '\\': out += "\\\\"; break;
case '"': out += "\\\""; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[7];
std::snprintf(buf, sizeof(buf), "\\u%04x", (unsigned int)c);
out += buf;
} else {
out.push_back((char)c);
}
}
}
return out;
}
// ---------- Ordering helpers ----------
static inline bool lexLessLabel(const VertexMap& vm, int aId, int bId) {
return vm.labelOf(aId) < vm.labelOf(bId);
}
struct CanonInfo { double k; double dist; };
static CanonInfo firstCanonicalInfoFromEnd(int end, const OrderedAdj& adj, const std::vector<bool>& is_canon, const std::vector<int>& canon_k) {
int prev = 0;
int cur = end;
int dist = 0;
if (is_canon[(size_t)cur] && canon_k[(size_t)cur] != std::numeric_limits<int>::min()) {
return { (double)canon_k[(size_t)cur], 0.0 };
}
while (true) {
CHECK_CANCEL();
const auto& nbs = adj.neighbors(cur);
int next = 0;
for (int x : nbs) { if (x != prev) { next = x; break; } }
if (next == 0) break;
prev = cur;
cur = next;
dist++;
if (is_canon[(size_t)cur] && canon_k[(size_t)cur] != std::numeric_limits<int>::min()) {
return { (double)canon_k[(size_t)cur], (double)dist };
}
}
return { -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity() };
}
static int pickBestEndpoint(int endA, int endB, const OrderedAdj& adj, const VertexMap& vm,
const std::vector<bool>& is_canon, const std::vector<int>& canon_k) {
CanonInfo aInfo = firstCanonicalInfoFromEnd(endA, adj, is_canon, canon_k);
CanonInfo bInfo = firstCanonicalInfoFromEnd(endB, adj, is_canon, canon_k);
if (aInfo.k != bInfo.k) return (aInfo.k > bInfo.k) ? endA : endB;
if (aInfo.dist != bInfo.dist) return (aInfo.dist < bInfo.dist) ? endA : endB;
return lexLessLabel(vm, endA, endB) ? endA : endB;
}
struct Traversal {
std::vector<int> nodes;
std::vector<std::pair<int,int>> edges;
};
static Traversal traversePathFromStart(int start, const OrderedAdj& adj) {
Traversal t;
int prev = 0;
int cur = start;
t.nodes.push_back(cur);
while (true) {
CHECK_CANCEL();
const auto& nbs = adj.neighbors(cur);
int next = 0;
for (int x : nbs) { if (x != prev) { next = x; break; } }
if (next == 0) break;
t.edges.emplace_back(cur, next);
prev = cur;
cur = next;
t.nodes.push_back(cur);
}
return t;
}
static Traversal orderPath(const OrderedSet<int>& incidentNodesSet,
const OrderedSet<std::string>& edgeKeys,
const VertexMap& vm,
const std::vector<bool>& is_canon,
const std::vector<int>& canon_k) {
OrderedAdj adj = buildAdjFromEdgeKeys(edgeKeys);
auto deg = degreesFromAdj(adj, incidentNodesSet);
if (incidentNodesSet.size() == 1) {
Traversal t;
t.nodes.push_back(incidentNodesSet.items[0]);
return t;
}
std::vector<int> endpoints;
endpoints.reserve(2);
for (int u : incidentNodesSet.items) {
CHECK_CANCEL();
auto it = deg.find(u);
int d = (it == deg.end()) ? 0 : it->second;
if (d == 1) endpoints.push_back(u);
}
if (endpoints.size() < 2) {
// fallback: lex smallest label among incident nodes
std::vector<int> tmp = incidentNodesSet.items;
std::sort(tmp.begin(), tmp.end(), [&](int a, int b){ return vm.labelOf(a) < vm.labelOf(b); });
return traversePathFromStart(tmp[0], adj);
}
int start = pickBestEndpoint(endpoints[0], endpoints[1], adj, vm, is_canon, canon_k);
return traversePathFromStart(start, adj);
}
static std::vector<int> traverseCycle(int start, int firstNeighbor, const OrderedAdj& adj) {
std::vector<int> nodes;
nodes.reserve(16);
nodes.push_back(start);
nodes.push_back(firstNeighbor);
int prev = start;
int cur = firstNeighbor;
while (true) {
CHECK_CANCEL();
const auto& nbs = adj.neighbors(cur);
int next = 0;
for (int x : nbs) { if (x != prev) { next = x; break; } }
if (next == 0) break;
if (next == start) break;
nodes.push_back(next);
prev = cur;
cur = next;
if (nodes.size() > 10000000ULL) break;
}
return nodes;
}
static std::vector<std::pair<int,int>> cycleEdgesFromNodeOrder(const std::vector<int>& nodeOrder) {
std::vector<std::pair<int,int>> edges;
edges.reserve(nodeOrder.size());
for (size_t i = 0; i < nodeOrder.size(); i++) {
int u = nodeOrder[i];
int v = nodeOrder[(i + 1) % nodeOrder.size()];
edges.emplace_back(u, v);
}
return edges;
}
static int nextCanonicalKAlong(const std::vector<int>& order,
const std::vector<bool>& is_canon,
const std::vector<int>& canon_k) {
for (size_t i = 1; i < order.size(); i++) {
int id = order[i];
if (is_canon[(size_t)id] && canon_k[(size_t)id] != std::numeric_limits<int>::min()) {
return canon_k[(size_t)id];
}
}
return std::numeric_limits<int>::min();
}
static Traversal orderCycleSimple(const OrderedSet<int>& incidentNodesSet,
const OrderedSet<std::string>& edgeKeys,
const VertexMap& vm,
const std::vector<bool>& is_canon,
const std::vector<int>& canon_k) {
OrderedAdj adj = buildAdjFromEdgeKeys(edgeKeys);
// start at canonical with largest k, else lex smallest label
int start = 0;
int bestK = std::numeric_limits<int>::min();
for (int u : incidentNodesSet.items) {
CHECK_CANCEL();
int ku = canon_k[(size_t)u];
if (is_canon[(size_t)u] && ku != std::numeric_limits<int>::min() && ku > bestK) {
bestK = ku;
start = u;
}
}
if (start == 0) {
std::vector<int> tmp = incidentNodesSet.items;
std::sort(tmp.begin(), tmp.end(), [&](int a, int b){ return vm.labelOf(a) < vm.labelOf(b); });
start = tmp[0];
}
const auto& nbs = adj.neighbors(start);
if (nbs.size() < 2) {
Traversal t;
t.nodes.push_back(start);
return t;
}
int a = nbs[0], b = nbs[1];
std::vector<int> ord1 = traverseCycle(start, a, adj);
std::vector<int> ord2 = traverseCycle(start, b, adj);
bool hasKStart = is_canon[(size_t)start] && canon_k[(size_t)start] != std::numeric_limits<int>::min();
int kStart = hasKStart ? canon_k[(size_t)start] : std::numeric_limits<int>::min();
int k1 = hasKStart ? nextCanonicalKAlong(ord1, is_canon, canon_k) : std::numeric_limits<int>::min();
int k2 = hasKStart ? nextCanonicalKAlong(ord2, is_canon, canon_k) : std::numeric_limits<int>::min();
auto score = [&](int nextK)->double {
if (!hasKStart) return std::numeric_limits<double>::infinity();
if (nextK == std::numeric_limits<int>::min()) return std::numeric_limits<double>::infinity();
return std::fabs((double)nextK - (double)kStart);
};
double s1 = score(k1), s2 = score(k2);
const std::vector<int>* chosen = &ord1;
if (s2 < s1) chosen = &ord2;
else if (s1 == s2) {
std::vector<std::string> labs1, labs2;
labs1.reserve(ord1.size()); labs2.reserve(ord2.size());
for (int id : ord1) labs1.push_back(vm.labelOf(id));
for (int id : ord2) labs2.push_back(vm.labelOf(id));
if (compareArraysLex(labs2, labs1) < 0) chosen = &ord2;
}
Traversal t;
t.nodes = *chosen;
t.edges = cycleEdgesFromNodeOrder(*chosen);
return t;
}
struct ClassifyResult {
OrderedAdj adj;
std::unordered_map<int,int> deg;
int edgeCount = 0;
int nodeCount = 0;
bool isPath = false;
bool isSimpleCycle = false;
};
static ClassifyResult classifyGraph(const OrderedSet<int>& incidentNodesSet,
const OrderedSet<std::string>& edgeKeys) {
ClassifyResult r;
r.adj = buildAdjFromEdgeKeys(edgeKeys);
OrderedSet<int> nodes = incidentNodesSet;
r.deg = degreesFromAdj(r.adj, nodes);
r.edgeCount = (int)edgeKeys.size();
r.nodeCount = (int)incidentNodesSet.size();
int maxDeg = 0;
bool allDeg2 = (r.nodeCount > 0);
for (int u : incidentNodesSet.items) {
auto it = r.deg.find(u);
int d = (it == r.deg.end()) ? 0 : it->second;
if (d > maxDeg) maxDeg = d;
if (d != 2) allDeg2 = false;
}
r.isPath = (r.edgeCount == r.nodeCount - 1) && (maxDeg <= 2);
r.isSimpleCycle = (r.edgeCount == r.nodeCount) && allDeg2 && (r.nodeCount >= 3);
return r;
}
struct DiamResult {
int length;
std::vector<int> path;
};
static DiamResult diameterShortestPath(const std::vector<int>& nodesArr, const OrderedAdj& adj, const VertexMap& vm) {
// The JS version computes the exact (all-pairs) diameter via BFS from every node.
// That becomes infeasible for large components (e.g. thousands of nodes) in single-threaded WASM.
//
// We keep exact behavior for small components, and switch to a deterministic pseudo-diameter
// approximation for large ones (multiple two-sweep BFS runs from evenly-spaced seeds).
//
// This preserves input/output format, remains deterministic, and prevents "stalling" on big graphs.
if (nodesArr.empty()) return {-1, {}};
auto comparePathLabelsLex = [&](const std::vector<int>& a, const std::vector<int>& b) -> int {
const size_t n = std::min(a.size(), b.size());
for (size_t i = 0; i < n; i++) {
const std::string& la = vm.labelOf(a[i]);
const std::string& lb = vm.labelOf(b[i]);
if (la < lb) return -1;
if (la > lb) return 1;
}
if (a.size() < b.size()) return -1;
if (a.size() > b.size()) return 1;
return 0;
};
int maxId = 0;
for (int x : nodesArr) if (x > maxId) maxId = x;
for (int x : adj.keys) if (x > maxId) maxId = x;
if (maxId <= 0) return {-1, {nodesArr[0]}};
std::vector<uint8_t> allowed((size_t)maxId + 1, 0);
for (int x : nodesArr) if (x >= 0 && x <= maxId) allowed[(size_t)x] = 1;
std::vector<int> dist((size_t)maxId + 1, -1);
std::vector<int> parent((size_t)maxId + 1, -1);
std::vector<int> q;
q.reserve(nodesArr.size() + 8);
std::vector<int> order;
order.reserve(nodesArr.size() + 8);
std::vector<int> touched;
touched.reserve(nodesArr.size() + 8);
auto resetTouched = [&]() {
for (int v : touched) { dist[(size_t)v] = -1; parent[(size_t)v] = -1; }
touched.clear();
};
auto reconstruct = [&](int end) -> std::vector<int> {
std::vector<int> path;
int cur = end;
while (cur != -1) {
path.push_back(cur);
int p = parent[(size_t)cur];
cur = p;
}
std::reverse(path.begin(), path.end());
return path;
};
auto runBfs = [&](int start, bool keepParent) -> std::pair<int,int> {
q.clear();
order.clear();
touched.clear();
dist[(size_t)start] = 0;
if (keepParent) parent[(size_t)start] = -1;
q.push_back(start);
order.push_back(start);
touched.push_back(start);
size_t qi = 0;
int farNode = start;
int farDist = 0;
while (qi < q.size()) {
CHECK_CANCEL();
int u = q[qi++];
int du = dist[(size_t)u];
const auto& nbs = adj.neighbors(u);
for (int v : nbs) {
if (v <= 0 || v > maxId) continue;
if (!allowed[(size_t)v]) continue;
if (dist[(size_t)v] != -1) continue;
dist[(size_t)v] = du + 1;
if (keepParent) parent[(size_t)v] = u;
q.push_back(v);
order.push_back(v);
touched.push_back(v);
int dv = du + 1;
if (dv > farDist) {
farDist = dv;
farNode = v;
} else if (dv == farDist) {
// Deterministic tie-break: smallest label among farthest.
if (vm.labelOf(v) < vm.labelOf(farNode)) farNode = v;
}
}
}
return {farNode, farDist};
};
int bestLen = -1;
std::vector<int> bestPath;