-
Notifications
You must be signed in to change notification settings - Fork 23
/
mesh.pas
executable file
·10967 lines (10707 loc) · 385 KB
/
mesh.pas
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
unit mesh;
{$Include opts.inc}
{$mode objfpc}{$H+}
interface
//{$DEFINE TIMER} //defined in opts.inc
{$DEFINE TREFOIL} //use Trefoil Knot as default object (instead of pyramid)
uses
//nifti_foreign,
{$IFDEF DGL} dglOpenGL, {$ELSE DGL} {$IFDEF COREGL}glcorearb, {$ELSE} gl, glext,{$ENDIF} {$ENDIF DGL}
{$IFDEF CTM} ctm_loader, {$ENDIF}
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, strutils, DateUtils,
base64, zstream, LcLIntf, nifti_loader, colorTable, matmath, math,
define_types, nifti_types, fileutil;
const
kMinOverlayIndex = 1;
kMaxOverlays = 256;
kLUTinvisible = 0;
kLUTtranslucent = 50;
kLUTopaque = 100;
kXRayNo = 0;
kXRayDarkBackground = -1;
kXRayBrightBackground = 1;
type
TSphere = packed record
X: single;
Y: single;
Z: single;
Clr: single;
Radius: single;
end;
TOverlay = record
LUTinvert, AOmap: boolean;
PaintMode: integer;
OpacityPercent: integer;
//LUTvisible: integer; //0=invisible, 1=translucent, 2=opaque
LUTindex,atlasMaxIndex, volumes, CurrentVolume : integer;
LUT: TLUT;
minIntensity, maxIntensity, windowScaledMin, windowScaledMax: single;
filename: string;
isBinary: boolean;
intensity: TFloats;
//next: if loaded as mesh...
faces : TFaces;
vertices: TVertices;
vertexRGBA : TVertexRGBA; //array of TRGBA;
vertexAtlas: TInts; //what atlas regions does this vertex belong to, e.g. [7, 8, 17...] the 3rd vertex belongs to region 17
atlasTransparentFilter: TBools;
atlasHideFilter: TInts; //atlas show these atlas regions, e.g. if [7, 8, 22] then only regions 7,8 and 22 will be visible
end;
TNodePrefs = record //preferences for nodes
minEdge, maxEdge, maxEdgeAbs, minEdgeThresh, maxEdgeThresh, minNodeColor, maxNodeColor, minNodeSize, maxNodeSize,
minNodeThresh, maxNodeThresh, scaleNodeSize, scaleEdgeSize, thresholdNodeFrac: single;
nodeLUTindex , edgeLUTindex: integer;
isNodeThresholdBySize, isNoNegEdge, isNoPosEdge, isNoLeftNodes,isNoRightNodes,isNoNodeWithoutEdge, isNodeColorVaries, isEdgeColorVaries, isEdgeSizeVaries, isEdgeShowNeg, isEdgeShowPos : boolean;
layerName: array[0..kMaxOverlays] of string[32];
end;
type
TMesh = class
scale, vertexRgbaSaturation, vertexRgbaAlpha : single;
origin, mxV, mnV : TPoint3f;
nFacesOverlay, nFaces: integer;
{$IFDEF COREGL}
vao, vbo, vaoOverlay, vboOverlay: GLuint;
{$ELSE}
{$IFDEF LEGACY_INDEXING}
index_vbo, vertex_vbo, index_vboOverlay, vertex_vboOverlay: GLuint;
{$ELSE}
displayList, displayListOverlay : GLuint;
{$ENDIF}
{$ENDIF}
isZDimIsUp, isRebuildList, isBusy, isNode, isFreeSurferMesh, isVisible, isAdditiveOverlay : boolean;
OpenOverlays, OverlayTransparency, AtlasMaxIndex : integer;
overlay: array [kMinOverlayIndex..kMaxOverlays] of TOverlay;
nodes: array of TSphere;
edges: array of array of Single;
edgeLayers: array of single;
faces : array of TPoint3i;
vertices: array of TPoint3f;
vertexRGBA : array of TRGBA;
vertexAtlas: TInts; //what atlas regions does this vertex belong to, e.g. [7, 8, 17...] the 3rd vertex belongs to region 17
atlasTransparentFilter: TBools;
atlasHideFilter: TInts; //atlas show these atlas regions, e.g. if [7, 8, 22] then only regions 7,8 and 22 will be visible
tempIntensityLUT : TFloats; //only used to load without external files - flushed after LoadOverlay
shortName, errorString: string;
//overlay: array of single;
private
//procedure DBug();
function FindBorderVertices(): TUInt8s;
function CheckMesh: boolean;
function CheckNodes: boolean;
function CheckEdges: boolean;
procedure SetOverlayDescriptives(lOverlayIndex: integer);
procedure MinMaxPct(lOverlayIndex, num_v: integer; var mx, mn: single; isExcludeZero: boolean);
procedure SetDescriptives;
{$IFDEF TREFOIL} procedure MakeTrefoil; {$ENDIF}
procedure MakeSphere;
function SetLutIndex(layer:integer): integer;
procedure BuildListCore(Clr: TRGBA; var f: TFaces; var v: TVertices; var vtxRGBA: TVertexRGBA; vRemap: TInts = nil; isWriteToGPU: boolean = true);
//procedure BuildListCore(Clr: TRGBA; var f: TFaces; var v: TVertices; var vtxRGBA: TVertexRGBA; vRemap: TInts = nil);
procedure BuildListPartialAtlas(Clr: TRGBA; vtxRGBA: TVertexRGBA);
procedure BuildList(Clr: TRGBA);
procedure FilterOverlay(c: integer; var f: TFaces; var v: TVertices; var vRGBA: TVertexRGBA);
procedure BuildListOverlay(Clr: TRGBA);
function Load1D(const FileName: string; lOverlayIndex: integer): boolean;
function Load3Do(const FileName: string): boolean;
function Load3ds(const FileName: string): boolean;
function LoadAc(const FileName: string): boolean;
function LoadByu(const FileName: string): boolean;
function LoadAnnot(const FileName: string): boolean;
function LoadNiml(const FileName: string): boolean;
function LoadNimlNodeEdge(const FileName: string): boolean;
function loadCifti(fnm: string; lOverlayIndex, lSeriesIndex: integer; isLoadCortexLeft: boolean): integer;
function LoadDae(const FileName: string): boolean; //only subset!
function LoadDfs(const FileName: string): boolean;
function LoadDxf(const FileName: string): boolean;
function LoadGcs(const FileName: string): boolean;
function LoadGii(const FileName: string; lOverlayIndex, lOverlayItem: integer; var HasOverlays: boolean): integer;
function LoadGts(const FileName: string): boolean;
function LoadIdtf(const FileName: string): boolean;
function LoadJson(const FileName: string): boolean;
function LoadLwo(const FileName: string): boolean;
function LoadMesh(const FileName: string): boolean;
function LoadMeshAscii(const FileName: string): boolean;
function LoadVoxel2Vertex(const FileName: string; lOverlayIndex: integer): boolean;
function LoadMs3d(const FileName: string): boolean;
//function LoadVbo(const FileName: string): boolean;
function LoadMz3(const FileName: string; lOverlayIndex : integer): boolean;
function LoadPrwm(const FileName: string): boolean;
function LoadObjMni(const FileName: string): boolean;
function LoadOff(const FileName: string): boolean;
function LoadOffBin(const FileName: string): boolean;
function LoadPly2(const FileName: string): boolean;
function CullUnusedVertices(): boolean;
function LoadSrf(const FileName: string): boolean;
function LoadSurf(const FileName: string): boolean;
function LoadTri(const FileName: string): boolean;
function LoadVrml(const FileName: string): boolean;
function LoadWfr(const FileName: string): boolean; //EMSE wireframe
function LoadAsc_Srf(const FileName: string): boolean;
function LoadAsc_Sparse(const FileName: string): boolean;
procedure LoadCtm(const FileName: string);
function LoadDpv(const FileName: string; lOverlayIndex: integer): boolean;
function LoadCol(const FileName: string; lOverlayIndex, lOverlayItem: integer): integer; //AFNI https://afni.nimh.nih.gov/afni/community/board/read.php?1,44391,44410
function LoadAtlasMapCore(lOverlayIndex: integer; intensityLUT: TFloats): string;
function LoadAtlasMap(const FileName: string; lOverlayIndex: integer): boolean;
procedure LoadCurv(const FileName: string; lOverlayIndex: integer);
procedure LoadMeshAsOverlay(const FileName: string; lOverlayIndex: integer);
procedure LoadNii(const FileName: string; lOverlayIndex: integer; lLoadSmooth: boolean);
procedure Overlay2Atlas();
function LoadCluster(const FileName: string): boolean;
function LoadNodeTxt(const FileName: string): boolean;
procedure LoadNode(const FileName: string; out isEmbeddedEdge: boolean);
procedure LoadNv(const FileName: string);
procedure LoadObj(const FileName: string);
//procedure LoadFreeSurferQuad(const FileName: string);
procedure LoadPial(const FileName: string);
procedure LoadPly(const FileName: string);
procedure LoadStl(const FileName: string);
procedure LoadStlAscii(const FileName: string);
function LoadVtkTxt(const FileName: string):boolean;
procedure LoadVtk(const FileName: string);
procedure LoadW(const FileName: string; lOverlayIndex: integer);
public
bilateralOffset: single;
nodePrefs: TNodePrefs;
isBilateral: boolean;
OverlappingOverlaysOverwrite: boolean;
procedure MakePyramid;
function SetEdgeLayer(layer: integer): boolean;
//function AtlasStatMapCore(AtlasName, StatName: string; Indices: TInts; Intensities: TFloats): string;
//function AtlasMaxIndex: integer;
procedure DrawGL (Clr: TRGBA; clipPlane: TPoint4f; isFlipMeshOverlay: boolean; XRay: integer = kXRayNo);
//procedure DrawGL (Clr: TRGBA; clipPlane: TPoint4f; isFlipMeshOverlay: boolean; XRay: integer);
procedure Node2Mesh;
procedure ReverseFaces;
procedure CenterOrigin;
procedure SwapYZ;
procedure SwapZY;
function LoadFromFile(const FileName: string): boolean;
function LoadEdge(const FileName: string; isEmbeddedEdge: boolean): boolean;
function LoadOverlay(const FileName: string; lLoadSmooth: boolean): boolean;
procedure LoadDummyOverlay(layer: integer; ov: TOverlay);
procedure CloseOverlaysCore;
procedure CloseOverlays;
function Contours(OverlayIndex: integer): boolean;
function Mesh2Node(const FileName: string; isAppend: boolean = true):boolean;
function Atlas2Node(const FileName: string; isAppend: boolean = true):boolean;
procedure Close;
constructor Create;
(*procedure SaveVrml(const FileName: string; MeshColor: TColor = clWhite);
procedure SaveMz3(const FileName: string; MeshColor: TColor = clWhite);
procedure SaveGii(const FileName: string);
procedure SaveObj(const FileName: string);
procedure SavePly(const FileName: string; MeshColor: TColor = clWhite);*)
procedure SaveMesh(const FileName: string; MeshColor: TColor = clWhite);
procedure SaveOverlay(const FileName: string; OverlayIndex: integer);
destructor Destroy; override;
end;
function isNimlNodes(fnm: string): boolean;
implementation
uses
mainunit, {$IFDEF FASTGZ}SynZip, {$ENDIF}
meshify_simplify,shaderu, {$IFDEF COREGL} gl_core_3d {$ELSE} gl_legacy_3d {$ENDIF};
procedure printf(s: string);
begin
{$IFDEF UNIX}writeln(s);{$ENDIF}
end;
procedure ShowMessageX(str: string);
begin
printf(str);
showmessage(str);
end;
function isNimlNodes(fnm: string): boolean;
//some .niml.dset are per-vertex scalars, others are node maps, the latter have "Graph_Bucket_data"
label
123;
var
f: TextFile;
st: string;
begin
result := false;
AssignFile(f, fnm);
FileMode := fmOpenRead;
reset(f);
while not eof(f) do begin
readln(f, st);
if (AnsiContainsText(st, '"Graph_Bucket"')) then begin
result := true;
goto 123;
end;
if (AnsiContainsText(st, '"Node_Bucket"')) or (AnsiContainsText(st, '"Node_Label"')) or (AnsiContainsText(st, '>')) then
goto 123;
end;
123:
closefile(f);
end;
(*function TMesh.Atlas2Node(const FileName: string):boolean;
const
kT = chr(9);
label
123;
var
xROI, yROI, zROI, maxRoiDxIdx, nVert, maxROI, nFace, roi, nroiEdges, nroiVerts, nCOGs: integer;
roiEdges, roiVerts: TInts;
isEdge, isVert: TInts;
roiDx, maxRoiDx: double;
COGs: array of TPoint4f; //center of gravity
j, i : integer;
txt: TextFile;
begin
result := false;
nVert := length(vertices);
nFace := length(faces);
maxROI := AtlasMaxIndex;
if (nFace < 1) or (nVert < 3) or (maxROI < 1) or (length(vertexAtlas) <> nVert) then exit;
setlength(COGs, maxROI+1);
setlength(roiEdges, nVert); //list of vertices on edge of ROI
setlength(roiVerts, nVert); //list all vertices in ROI
setlength(isEdge, nVert);
setlength(isVert, nVert);
for i := 0 to maxROI do
COGs[i] := pt4f(0,0,0,0);
nCOGs := 0;
for roi := 0 to maxROI do begin
nroiEdges := 0;
for i := 0 to nVert -1 do begin
isEdge[i] := 0;
isVert[i] := 0;
end;
//fillChar(isEdge,sizeOf(isEdge),0);
//fillChar(isVert,sizeOf(isVert),0);
for i := 0 to (nFace-1) do begin
xROI := vertexAtlas[Faces[i].X];
yROI := vertexAtlas[Faces[i].Y];
zROI := vertexAtlas[Faces[i].Z];
if (xROI <> roi) and (yROI <> roi) and (zROI <> roi) then continue; //this vertex not member of ROI
//roiVerts[nroiVerts] := i;
if (xROI = roi) then isVert[Faces[i].X] := 1;
if (yROI = roi) then isVert[Faces[i].Y] := 1;
if (zROI = roi) then isVert[Faces[i].Z] := 1;
if (xROI = yROI) and (xROI = zROI) then continue; //all members of same ROI
if (xROI = roi) then isEdge[Faces[i].X] := 1;
if (yROI = roi) then isEdge[Faces[i].Y] := 1;
if (zROI = roi) then isEdge[Faces[i].Z] := 1;
nroiEdges := nroiEdges + 1;
end;
if nroiEdges < 1 then continue; //no edges found!
//compute total number of edges, faces...
nroiEdges := 0;
for i := 0 to (nVert-1) do
if isEdge[i] > 0 then begin
roiEdges[nroiEdges] := i;
nroiEdges := nroiEdges + 1;
end;
nroiVerts := 0;
for i := 0 to (nVert-1) do
if isVert[i] > 0 then begin
roiVerts[nroiVerts] := i;
nroiVerts := nroiVerts + 1;
end;
maxRoiDx := -infinity;
maxRoiDxIdx := 0;
for i := 0 to (nroiVerts -1) do begin //compute cost function for each vertex - furtherst from edges
roiDx := 0;
for j := 0 to (nroiEdges - 1) do
roiDx := roiDx + DistanceBetween(vertices[roiVerts[i]], vertices[roiEdges[j]]);
if (roiDx <= maxRoiDx) then continue;
maxRoiDx := roiDx;
maxRoiDxIdx := roiVerts[i];
end;
COGs[nCOGs].x := vertices[maxRoiDxIdx].x;
COGs[nCOGs].y := vertices[maxRoiDxIdx].y;
COGs[nCOGs].z := vertices[maxRoiDxIdx].z;
COGs[nCOGs].w := roi+1;
nCOGs := nCOGs + 1;
end;
if nCOGs < 1 then goto 123;
result := true;
AssignFile(txt, FileName);
rewrite(txt);
for i := 0 to nCOGs-1 do begin
if COGs[i].w < 1 then continue; //label not present
writeln(txt, format('%g%s%g%s%g%s%d%s1', [COGs[i].x,kT,COGs[i].y,kT,COGs[i].z,kT,round(COGs[i].w),kT ]));
end;
CloseFile(txt);
123:
roiEdges := nil;
roiEdges := nil;
COGs := nil;
isVert := nil;
isEdge := nil;
nearestNode := nil;
end; *)
{$DEFINE FXR}
{$IFDEF FXR}
function DistanceBetween(var a,b: TPoint3f): single;
begin
result := sqrt(sqr(a.x-b.x)+sqr(a.y-b.y)+sqr(a.z-b.z));
end;
function AddPt3f(var a,b: TPoint3f): TPoint3f; //create float vector
begin
result.X := a.X + b.X;
result.Y := a.Y + b.Y;
result.Z := a.Z + b.Z;
end;
(*procedure TMesh.dBug();
var
mn, mx, i, nVert, nFace: integer;
begin
nVert := length(vertices);
nFace := length(faces);
if (nFace < 1) or (nVert < 3) or (length(vertexAtlas) <> nVert) then exit;
mn := vertexAtlas[0];
mx := mn;
for i := 0 to (nVert -1) do begin
mn := min(mn, vertexAtlas[i]);
mx := max(mx, vertexAtlas[i]);
end;
printf(format('>>>> %d..%d', [mn, mx]));
end; *)
function TMesh.FindBorderVertices(): TUInt8s;
var
isEdge: TUInt8s;
prefixSum, loCount, hiVs: TInts;
nVert, nFace, i, j, k, lov, repeats: integer;
procedure addV(x, y: integer);
var
lo, hi: integer;
begin
lo := min(x,y);
hi := max(x,y);
prefixSum[lo] -= 1;
hiVs[prefixSum[lo]] := hi;
end;
begin
result := nil;
//For triangular mesh, a "border vertex" has at least one edge
// that is used by only one face (triangle)
nVert := length(vertices);
nFace := length(faces);
if (nFace < 2) or (nVert < 3) then exit(nil);
printf(format('Find borders. face %d vert %d', [nFace, nVert]));
//each face (triangle) has 3 vertices (x,y,z)
setlength(loCount, nVert);
//first pass: bucket size
for i := 0 to (nFace-1) do begin
loCount[min(faces[i].X, faces[i].Y)] += 1;
loCount[min(faces[i].X, faces[i].Z)] += 1;
loCount[min(faces[i].Y, faces[i].Z)] += 1;
end;
//create prefix sum
setlength(prefixSum, nVert);
prefixSum := Copy(loCount, Low(loCount), Length(loCount));
for i := 1 to (nVert -1) do
prefixSum[i] += prefixSum[i-1];
setlength(hiVs, nFace * 3);
//second pass: load high value
for i := 0 to (nFace-1) do begin
addV(faces[i].X, faces[i].Y);
addV(faces[i].X, faces[i].Z);
addV(faces[i].Y, faces[i].Z);
end;
prefixSum := nil;
//finally: identify vertices that have singleton lines
setlength(isEdge, nVert);
//test
(*i := 0;
for lov := 0 to (nVert -1) do
i += loCount[lov];
printf(format(' lines %d %d', [i, nFace * 3]));
i := 0;
for lov := 0 to (nVert -1) do begin
if loCount[lov] < 1 then continue;
//printf(format('%d %d', [loCount[lov], lov]));
for j := 0 to (loCount[lov]-1) do begin
printf(format('%d line %d %d', [i+j, lov, hiVs[i+j]]));
end;
i += loCount[lov];
end; *)
//done
i := 0;
for lov := 0 to (nVert -1) do begin
if loCount[lov] < 1 then continue;
//printf(format('%d %d', [loCount[lov], lov]));
for j := 0 to (loCount[lov]-1) do begin
repeats := 0;
for k := 0 to (loCount[lov]-1) do
if hiVs[i+j] = hiVs[i+k] then
repeats += 1;
if repeats > 1 then continue;
//border edge found - set both vertices of edge as "border"
isEdge[lov] := 1;
isEdge[hiVs[i+j]] := 1;
end;
i += loCount[lov];
end;
hiVs := nil;
loCount := nil;
//test if watertight
j := 0;
for i := 0 to (nVert -1) do
if isEdge[i] > 0 then
j += 1;
if (j = 0) then begin
printf(format('This is a watertight mesh: none of the %d vertices are on the border', [nVert]));
isEdge := nil;
exit;
end else
printf(format('%d of %d vertices are on the border', [j, nVert]));
result := isEdge;
end;
function TMesh.Mesh2Node(const FileName: string; isAppend: boolean = true): boolean;
label
123;
const
kT = chr(9);
var
borderVertices: TUInt8s; //binary for all vertices [0 0 1 0 1]
borderIdxs: TInts; //indices for edges [2 4]
nVert, nEdge, i, j, maxIdx: integer;
vert, cog: TPoint3f;
cogDx, maxCogDX, maxEdgeDx, dx: single;
txt: TextFile;
begin
result := false;
nVert := length(vertices);
if nVert < 3 then exit;
borderVertices := FindBorderVertices;
if borderVertices = nil then begin
printf('Finding vertex closest to center-of-gravity');
cog := ptf(0,0,0);
for i := 0 to (nVert -1) do
cog := AddPt3f(cog, vertices[i]);
cog.x := cog.x / nVert;
cog.y := cog.y / nVert;
cog.z := cog.z / nVert;
maxCogDX := infinity;
maxIdx := 0;
for i := 0 to (nVert -1) do begin
cogDx := DistanceBetween(vertices[i], cog);
if (cogDx > maxCogDx) then continue;
maxCogDx := cogDx;
maxIdx := i;
end;
goto 123; //e.g. watertight mesh
end;
//
setlength(borderIdxs, nVert); //worst case scenario: all edges
nEdge := 0;
for i := 0 to (nVert -1) do
if borderVertices[i] <> 0 then begin
borderIdxs[nEdge] := i;
nEdge += 1;
end;
setlength(borderIdxs, nEdge); //reduce memory
if nEdge = 0 then exit;
//find center of gravity for whole mesh (tie breaker);
cog := ptf(0,0,0);
for i := 0 to (nVert -1) do
cog := AddPt3f(cog, vertices[i]);
cog.x := cog.x / nVert;
cog.y := cog.y / nVert;
cog.z := cog.z / nVert;
maxCogDX := infinity;
maxEdgeDx := -infinity;
maxIdx := 0;
for i := 0 to (nVert -1) do begin
//compute cost function for each vertex - furtherst from edges
// who on the island has the longest walk to the beach?
if (maxEdgeDx > 0) and (borderVertices[i] = 1) then continue; //this vertex is on the edge, only useful if all vertices edge
dx := infinity;
vert := vertices[i];
for j := 0 to (nEdge - 1) do //find closest distance to edge
dx := min(dx, DistanceBetween(vert, vertices[borderIdxs[j]]));
if (dx < maxEdgeDx) then continue; //a previous vertex is closer to edge
cogDx := DistanceBetween(vert, cog);
if (dx = maxEdgeDx) then begin //we have a tie - is this closer to the center of gravity
if (cogDx > maxCogDx) then continue;
end;
maxCogDx := cogDx;
maxEdgeDx := dx;
maxIdx := i;
end;
borderVertices := nil;
borderIdxs := nil;
123:
result := true;
printf(format('xyz %g %g %g', [vertices[maxIdx].x, vertices[maxIdx].y, vertices[maxIdx].z]));
AssignFile(txt, FileName);
if (isAppend) and (FileExists(FileName)) then
append(txt)
else
rewrite(txt);
writeln(txt, format('%g%s%g%s%g%s%d%s1', [vertices[maxIdx].x,kT,vertices[maxIdx].y,kT,vertices[maxIdx].z,kT,round(123),kT ]));
CloseFile(txt);
end;
function TMesh.Atlas2Node(const FileName: string; isAppend: boolean = true):boolean;
const
kT = chr(9);
label
123;
var
xROI, yROI, zROI, maxRoiDxIdx, nVert, maxROI, nFace, roi, nroiEdges, nroiVerts, nCOGs: integer;
roiEdges, roiVerts: TInts;
isEdge, isVert: TUInt8s;
cogDx, maxCogDX, roiDx, maxRoiDx, dx: single;
vert, cog: TPoint3f;
COGs: array of TPoint4f; //center of gravity
j, i : integer;
txt: TextFile;
isOverlayAsAtlas: boolean = false;
borderVertices: TUInt8s; //binary for all vertices [0 0 1 0 1]
{$IFDEF TIMER}startTime : TDateTime;{$ENDIF}
begin
{$IFDEF TIMER}startTime := Now;{$ENDIF}
result := false;
nVert := length(vertices);
nFace := length(faces);
maxROI := AtlasMaxIndex;
//GLForm1.OverlayBox.Caption := 'a'+inttostr(maxROI);
if (nFace < 1) or (nVert < 3) then exit;
if (maxROI < 1) and (OpenOverlays > 0) and (length(overlay[kMinOverlayIndex].intensity) = nVert) then begin
maxROI := 0;
isOverlayAsAtlas := true;
setlength(vertexAtlas, nVert);
for i := 0 to nVert -1 do begin
vertexAtlas[i] := round(overlay[kMinOverlayIndex].intensity[i]);
maxROI := max(vertexAtlas[i], maxROI);
end;
if maxROI < 1 then
vertexAtlas := nil
else
printf(format('Overlay is %d discrete parcels', [maxROI]));
end;
if (maxROI < 1) or (length(vertexAtlas) <> nVert) then begin
//find single node most representative of whole mesh
result := Mesh2Node(FileName);
exit;
end;
// for i := 0 to (nVert -1) do
// sumV += vertexAtlas[i];
setlength(COGs, maxROI+1);
setlength(roiEdges, nVert); //list of vertices on edge of ROI
setlength(roiVerts, nVert); //list all vertices in ROI
setlength(isEdge, nVert);
setlength(isVert, nVert);
//GLForm1.OverlayBox.Caption := 'b'+inttostr(maxROI);
for i := 0 to maxROI do
COGs[i] := pt4f(0,0,0,0);
nCOGs := 0;
borderVertices := FindBorderVertices; //find border vertices that have no neighbors - these are boundary for a region
for roi := 0 to maxROI do begin
for i := 0 to nVert -1 do begin
isEdge[i] := 0;
isVert[i] := 0;
end;
nroiVerts := 0;
for i := 0 to (nFace-1) do begin
if maxROI < 1 then begin
xROI := 0;
yROI := 0;
zROI := 0;
end else begin
xROI := vertexAtlas[Faces[i].X];
yROI := vertexAtlas[Faces[i].Y];
zROI := vertexAtlas[Faces[i].Z];
end;
if (xROI <> roi) and (yROI <> roi) and (zROI <> roi) then continue; //this vertex not member of ROI
//roiVerts[nroiVerts] := i;
nroiVerts += 1;
if (xROI = roi) then isVert[Faces[i].X] := 1;
if (yROI = roi) then isVert[Faces[i].Y] := 1;
if (zROI = roi) then isVert[Faces[i].Z] := 1;
if (xROI = yROI) and (xROI = zROI) then continue; //all members of same ROI
if (xROI = roi) then isEdge[Faces[i].X] := 1;
if (yROI = roi) then isEdge[Faces[i].Y] := 1;
if (zROI = roi) then isEdge[Faces[i].Z] := 1;
end;
//add border vertices that are part of region but have no neighbors
if (borderVertices <> nil) then begin //if mesh is not water tight
for i := 0 to nVert -1 do begin
if (isVert[i] = 1) and (borderVertices[i] = 1) then
isEdge[i] := 1;
end;
end;
//count
nroiEdges := 0;
for i := 0 to nVert -1 do
if (isEdge[i] = 1) then
nroiEdges := nroiEdges + 1;
//printf(roi, ' has ', nroiVerts, ' vertices and ', nroiEdges, ' edges' );
if nroiVerts < 1 then continue;
//compute total number of edges, faces...
nroiEdges := 0;
for i := 0 to (nVert-1) do
if isEdge[i] > 0 then begin
roiEdges[nroiEdges] := i;
nroiEdges := nroiEdges + 1;
end;
nroiVerts := 0;
for i := 0 to (nVert-1) do
if isVert[i] > 0 then begin
roiVerts[nroiVerts] := i;
nroiVerts := nroiVerts + 1;
end;
//find center of mass
cog := ptf(0,0,0);
for i := 0 to (nroiVerts -1) do
cog := AddPt3f(cog, vertices[roiVerts[i]]);
cog.x := cog.x / nroiVerts;
cog.y := cog.y / nroiVerts;
cog.z := cog.z / nroiVerts;
maxCogDX := infinity;
maxRoiDx := -infinity;
maxRoiDxIdx := 0;
//if no edges, center of gravity is our only metric
if nroiEdges < 1 then begin
printf(format('Region %d has no edges (%d vertices, CoG %g %g %g)',[roi,nroiVerts, cog.x, cog.y, cog.z ]));
for i := 0 to (nroiVerts -1) do begin
cogDx := DistanceBetween(vertices[roiVerts[i]], cog);
if (cogDx > maxCogDx) then continue;
maxCogDx := cogDx;
maxRoiDxIdx := roiVerts[i];
end;
COGs[nCOGs].x := vertices[maxRoiDxIdx].x;
COGs[nCOGs].y := vertices[maxRoiDxIdx].y;
COGs[nCOGs].z := vertices[maxRoiDxIdx].z;
COGs[nCOGs].w := roi+1;
nCOGs := nCOGs + 1;
continue; //no edges found: only use CoG
end;
for i := 0 to (nroiVerts -1) do begin
//compute cost function for each vertex - furtherst from edges
// who on the island has the longest walk to the beach?
roiDx := infinity;
vert := vertices[roiVerts[i]];
for j := 0 to (nroiEdges - 1) do begin
dx := DistanceBetween(vert, vertices[roiEdges[j]]);
if dx < roiDx then
roiDx := dx;
end;
if (roiDx < maxRoiDx) then continue; //a previous vertex is closer to edge
cogDx := DistanceBetween(vert, cog);
if (roiDx = maxRoiDx) then begin //we have a tie - is this closer to the center of gravity
if (cogDx > maxCogDx) then continue;
end;
maxCogDx := cogDx;
maxRoiDx := roiDx;
maxRoiDxIdx := roiVerts[i];
end;
//maxRoiDxIdx := roiVerts[random(nroiVerts)];
//maxRoiDxIdx := roiEdges[random(nroiEdges)];
COGs[nCOGs].x := vertices[maxRoiDxIdx].x;
COGs[nCOGs].y := vertices[maxRoiDxIdx].y;
COGs[nCOGs].z := vertices[maxRoiDxIdx].z;
COGs[nCOGs].w := roi+1;
nCOGs := nCOGs + 1;
end;
if isOverlayAsAtlas then
vertexAtlas := nil;
if nCOGs < 1 then goto 123;
//GLForm1.Caption := 'nCOGs'+inttostr(nCOGs);
result := true;
AssignFile(txt, FileName);
if (isAppend) and (FileExists(FileName)) then
append(txt)
else
rewrite(txt);
for i := 0 to nCOGs-1 do begin
if COGs[i].w < 1 then continue; //label not present
writeln(txt, format('%g%s%g%s%g%s%d%s1', [COGs[i].x,kT,COGs[i].y,kT,COGs[i].z,kT,round(COGs[i].w),kT ]));
end;
CloseFile(txt);
//if result then GLForm1.Caption := 'nCOGs'+inttostr(nCOGs);
{$IFDEF TIMER}GLForm1.Caption := inttostr(MilliSecondsBetween(Now,StartTime)); {$ENDIF}
123:
roiEdges := nil;
borderVertices := nil;
roiEdges := nil;
COGs := nil;
isVert := nil;
isEdge := nil;
//nearestNode := nil;
end;
{$ELSE}
function TMesh.Atlas2Node(const FileName: string):boolean;
const
kT = chr(9);
label
123;
var
nVert, maxROI: integer;
COGs, nearestNode: array of TPoint4f; //center of gravity
i, idx : integer;
dx: single;
txt: TextFile;
begin
result := false;
nVert := length(vertices);
maxROI := AtlasMaxIndex;
if (nVert < 3) or (maxROI < 1) or (length(vertexAtlas) <> nVert) then exit;
//vertexAtlas: TInts; //what atlas regions does this vertex belong to, e.g. [7, 8, 17...] the 3rd vertex belongs to region 17
//setlength(mass, maxROI+1);
setlength(COGs, maxROI+1);
for i := 0 to maxROI do
COGs[i] := pt4f(0,0,0,0);
for i := 0 to (nVert -1) do begin
idx := vertexAtlas[i];
COGs[idx].w := COGs[idx].w + 1;
COGs[idx].x := COGs[idx].x + vertices[i].x;
COGs[idx].y := COGs[idx].y + vertices[i].y;
COGs[idx].z := COGs[idx].z + vertices[i].z;
end;
//set center of gravity = mean
for i := 0 to maxROI do begin
COGs[i].x := COGs[i].x / COGs[i].w;
COGs[i].y := COGs[i].y / COGs[i].w;
COGs[i].z := COGs[i].z / COGs[i].w;
end;
//initialize nearest node - infinitely far away from COG
setlength(nearestNode, maxROI+1);
for i := 0 to maxROI do
nearestNode[i] := pt4f(0,0,0,Infinity);
//for each vertex - see if this is closest to COG
for i := 0 to (nVert -1) do begin
idx := vertexAtlas[i];
dx := sqrt( sqr(COGs[idx].x-vertices[i].x) + sqr(COGs[idx].y-vertices[i].y) + sqr(COGs[idx].z-vertices[i].z) );
if (dx >= nearestNode[idx].w) then continue;
nearestNode[idx] := pt4f(vertices[i].x, vertices[i].y, vertices[i].z, dx);
result := true; //at least one node survives
end;
if not result then goto 123;
AssignFile(txt, FileName);
rewrite(txt);
for i := 0 to maxROI do begin
if COGs[i].w < 1 then continue; //label not present
writeln(txt, format('%g%s%g%s%g%s%d%s1', [nearestNode[i].x,kT,nearestNode[i].y,kT,nearestNode[i].z,kT,i,kT ]));
end;
CloseFile(txt);
123:
COGs := nil;
nearestNode := nil;
end;
{$ENDIF}
{$IFDEF FASTGZ}
function ExtractGz(fnm: string; var mStream : TMemoryStream; magic: word = 0): boolean;
//if magic <> 0, then a file that starts with magic will assume to uncompressed
//if magic = 0, a file will be assumed to be uncompressed if first two bytes are not $8B1F
var
gz: TGZRead;
sig: word;
F : File Of byte;
src : array of byte;
cSz : int64; //uncompressed, compressed size
begin
if not fileexists(fnm) then exit(false);
FileMode := fmOpenRead;
Assign (F, fnm);
Reset (F);
cSz := FileSize(F);
sig := 0; //only to hide compiler warning
blockread(F, sig, SizeOf(sig) );
seek(F,0);
//n.b. GZ header/footer is ALWAYS little-endian
{$IFDEF ENDIAN_BIG}
sig := Swap(sig);
{$ENDIF}
if ( ((magic = 0) and (sig <> $8B1F)) or ((magic <> 0) and (sig = magic)) ) then begin //hex: 1F 8B : gzip specific: will reject zlib format
Close (F);
mStream.LoadFromFile(fnm);
exit(true);
end;
setlength(src, cSz);
blockread(f, src[0], cSz );
CloseFile(f);
result := gz.Init(@src[0], cSz);
if not result then begin
src := nil;
exit;
end;
gz.ToStream(mStream, cSz);
src := nil;
gz.ZStreamDone;
end;
{$ELSE}
function ExtractGz(fnm: string; var mStream : TMemoryStream; magic: word = 0): boolean;
const
kChunkSize = 65535;
var
zStream : TGZFileStream;
bytes : array of byte;
i: integer;
begin
zStream := TGZFileStream.create(fnm, gzopenread);
result := (zStream <> nil);
setlength(bytes, kChunkSize);
repeat
i := zStream.read(bytes[0],kChunkSize);
mStream.Write(bytes[0],i) ;
until i < kChunkSize;
zStream.Free;
end;
{$ENDIF}
//{$IFDEF COREGL}
function mixRGBA(c1, c2: TRGBA; frac2: single): TRGBA;
var
frac1: single;
begin
frac2 := ((c2.a * frac2 )/255.0);
frac1 := 1 - frac2;
result.R := round(c1.R*frac1 + c2.R*frac2) ;
result.G := round(c1.G*frac1 + c2.G*frac2);
result.B := round(c1.B*frac1 + c2.B*frac2);
end;
//{$ENDIF}
procedure AddPt4f(var v: TPoint4f; c1,c2,c3: TRGBA); //create float vector
begin
v.X := v.X + c1.r+ c2.r+ c3.r;
v.Y := v.Y + c1.g+ c2.g+ c3.g;
v.Z := v.Z + c1.b+ c2.b+ c3.b;
v.W := v.W + c1.a+ c2.a+ c3.a;
end;
procedure invertDarken(var c: TRGBA; v, mn,mx: single);
var
frac: single;
begin
if (v <= mn) then exit;
if (v >= mx) then begin
c.R := 0;
c.G := 0;
c.B := 0;
exit;
end;
frac := 1.0 - ((v-mn)/(mx-mn));
c.R := round(c.R * frac);
c.G := round(c.G * frac);
c.B := round(c.B * frac);
end;
procedure darken(var c: TRGBA; v, mn,mx: single);
var
frac: single;
begin
if (v >= mx) then exit;
if (v <= mn) then begin
c.R := 0;
c.G := 0;
c.B := 0;
exit;
end;
frac := (v-mn)/(mx-mn);
c.R := round(c.R * frac);
c.G := round(c.G * frac);
c.B := round(c.B * frac);
end;
procedure TMesh.BuildListCore(Clr: TRGBA; var f: TFaces; var v: TVertices; var vtxRGBA: TVertexRGBA; vRemap: TInts = nil; isWriteToGPU: boolean = true);
var
i,volInc, c: integer;
mn, mx, frac: single;
rgb, rgb0: TRGBA;
vRGBA, vRGBAmx :TVertexRGBA;
vNumNeighbor: array of integer;
vSumRGBBA: array of TPoint4f;
isOverlayPainting : boolean = false;
begin
nFaces := length(f);
if (length(f) < 1) or (length(v) < 3) then exit;
volInc := 0;
isOverlayPainting := false;
if (OpenOverlays > 0) then //ignore overlays if they are all meshes rather than vertex colors
for c := OpenOverlays downto 1 do
if (overlay[c].OpacityPercent <> kLUTinvisible) and (length(overlay[c].intensity) >= length(v)) then
isOverlayPainting := true;
if (isOverlayPainting) or (length(vtxRGBA) = length(v)) then begin
rgb := RGBA(Clr.R, Clr.G, Clr.B, 0);
setlength(vRGBA, length(v));
if (length(vtxRGBA) = length(v)) then begin
c := round(vertexRgbaAlpha * 255);
if vertexRgbaSaturation >= 1 then begin
for i := 0 to (length(v)-1) do begin
vRGBA[i].r := vtxRGBA[i].r;
vRGBA[i].g := vtxRGBA[i].g;
vRGBA[i].b := vtxRGBA[i].b;
if vtxRGBA[i].a > 0 then begin
c := round(vertexRgbaAlpha * vtxRGBA[i].a);
vRGBA[i].a := c
end else begin
vRGBA[i] := Clr; //Catani2020
vRGBA[i].a := 0; //Catani
end;
end;
end else begin
for i := 0 to (length(v)-1) do
vRGBA[i] := desaturateRGBA ( vtxRGBA[i], vertexRgbaSaturation, C);
end;
//2019: required only when no overlays open - try adjusting transparency of Altas
if (OpenOverlays < 1) and (vertexRGBAAlpha < 1.0) then
for i := 0 to (length(v)-1) do
vRGBA[i] := mixRGBA( Clr, vRGBA[i], vertexRGBAAlpha);
end else begin
for i := 0 to (length(v)-1) do
vRGBA[i] := rgb;
end;
if (OpenOverlays > 0) then begin
if isAdditiveOverlay then begin
setlength(vRGBAmx, length(v));
rgb0 := RGBA(0,0,0,0);
for i := 0 to (length(v)-1) do
vRGBAmx[i] := rgb0;
for c := OpenOverlays downto 1 do begin
if isFreeSurferLUT(overlay[c].LUTindex) then continue; //curve files ALWAYs darken
volInc := length(v) * (overlay[c].currentVolume - 1);
if (not overlay[c].aoMap) and (overlay[c].OpacityPercent <> kLUTinvisible) and (length(overlay[c].intensity) >= length(v)) then begin
frac := overlay[c].OpacityPercent/100;
if (frac > 1) or (frac < 0) then frac := 1;
if overlay[c].windowScaledMax > overlay[c].windowScaledMin then begin
mn := overlay[c].windowScaledMin;
mx := overlay[c].windowScaledMax;
end else begin
mx := overlay[c].windowScaledMin;
mn := overlay[c].windowScaledMax;
end;
if vRemap <> nil then begin //filtered atlas: vertices have been decimated
for i := 0 to (length(v)-1) do begin
rgb := inten2rgb(overlay[c].intensity[vRemap[i]+volInc], mn, mx, overlay[c].LUT, overlay[c].PaintMode);
rgb.A := round(rgb.A * frac);
vRGBAmx[i] := maxRGBA(vRGBAmx[i], rgb);
end; //for i
end else begin