DefunctionalizedAlgorithms.cs
C# 14 (.NET 10 Native AOT) — Zero-OOP Defunctionalized Graph & Spatial Search Kernels (ΔSP = 0, 0 B Heap)
← Back to DFS IV Article
1
using
System;
2
using
System.Numerics;
3
using
System.Runtime.CompilerServices;
4
5
namespace
MasterPiDfsEngine;
6
7
/// <summary>
8
/// Compact Compressed-Sparse-Row (CSR) adjacency view over flat unmanaged buffers.
9
/// Zero object headers, zero per-node List<int> allocations.
10
/// </summary>
11
public
readonly
unsafe
struct
CsrGraph
12
{
13
public
readonly
int
* RowOffsets;
// Length: NodeCount + 1
14
public
readonly
int
* ColIndices;
// Length: EdgeCount
15
public
readonly
int
NodeCount;
16
17
public
CsrGraph
(
int
* rowOffsets,
int
* colIndices,
int
nodeCount)
18
{
19
RowOffsets = rowOffsets;
20
ColIndices = colIndices;
21
NodeCount = nodeCount;
22
}
23
}
24
25
/// <summary>
26
/// 8-byte value-type continuation slot storing suspended parent vertex and next outgoing CSR edge index.
27
/// </summary>
28
public
struct
EdgeContinuation
29
{
30
public
int
Node;
31
public
int
EdgeIdx;
32
}
33
34
/// <summary>
35
/// 12-byte value-type binary min-heap entry for unmanaged A* open-set priority ordering.
36
/// </summary>
37
public
struct
AStarOpenSlot
38
{
39
public
int
Node;
40
public
int
GScore;
41
public
int
FScore;
42
}
43
44
/// <summary>
45
/// 32-byte cache-aligned flat octree node with a 64-bit (4x4x4) 1-bit leaf voxel occupancy mask.
46
/// </summary>
47
public
struct
OctreeNode
48
{
49
public
float
MinX, MinY, MinZ;
50
public
float
HalfSize;
51
public
int
FirstChildIdx;
// -1 when leaf node; otherwise index of first of 8 contiguous child octants
52
public
int
Padding;
53
public
ulong
LeafVoxelBits;
// 64-bit occupancy brick when FirstChildIdx < 0
54
}
55
56
/// <summary>
57
/// Zero-OOP Defunctionalized Graph & Spatial Search Kernels (Delta SP = 0, 0 B Heap).
58
/// Lowers recursive DFS TopoSort, Tarjan SCC, IDA* / A*, 3D Octree Collision, and Frontier Bitset BFS
59
/// into flat C# goto state machines over registers and 1-bit-per-state slabs.
60
/// </summary>
61
public
readonly
unsafe
struct
DefunctionalizedAlgorithms
62
{
63
// =========================================================================================
64
// 1. Reverse Post-Order DFS (Topological Sort) — Stationary Frame + Explicit Continuation
65
// =========================================================================================
66
[
MethodImpl
(
MethodImplOptions
.AggressiveInlining)]
67
public
static
int
TopoSortDefunc(
68
CsrGraph
graph,
69
ulong
* visitedBits,
70
EdgeContinuation
* contBuf,
71
int
* postOrderOut)
72
{
73
int
writeHead = graph.NodeCount;
74
75
for
(
int
root =
0
; root < graph.NodeCount; root++)
76
{
77
if
((visitedBits[root >>
6
] & (
1UL
<< (root &
63
))) !=
0UL
)
78
continue
;
79
80
int
regNode = root;
81
int
regEdge =
0
;
82
int
depth =
0
;
83
84
Topo_Enter:
85
visitedBits[regNode >>
6
] |=
1UL
<< (regNode &
63
);
86
regEdge = graph.RowOffsets[regNode];
87
if
(regEdge == graph.RowOffsets[regNode +
1
])
88
goto
Topo_Return;
89
90
Topo_NextEdge:
91
int
edgeEnd = graph.RowOffsets[regNode +
1
];
92
while
(regEdge < edgeEnd)
93
{
94
int
child = graph.ColIndices[regEdge++];
95
if
((visitedBits[child >>
6
] & (
1UL
<< (child &
63
))) ==
0UL
)
96
{
97
contBuf[depth].Node = regNode;
98
contBuf[depth].EdgeIdx = regEdge;
99
depth++;
100
regNode = child;
101
goto
Topo_Enter;
102
}
103
}
104
105
Topo_Return:
106
// Emit vertex strictly in post-order after every downstream child has returned
107
postOrderOut[--writeHead] = regNode;
108
if
(depth >
0
)
109
{
110
depth--;
111
regNode = contBuf[depth].Node;
112
regEdge = contBuf[depth].EdgeIdx;
113
goto
Topo_NextEdge;
114
}
115
}
116
117
return
graph.NodeCount - writeHead;
118
}
119
120
// =========================================================================================
121
// 2. Tarjan's Strongly Connected Components (SCC) — Non-Tail lowlink Post-Order Unwind
122
// =========================================================================================
123
[
MethodImpl
(
MethodImplOptions
.AggressiveInlining)]
124
public
static
int
TarjanSccDefunc(
125
CsrGraph
graph,
126
int
* disc,
127
int
* lowlink,
128
ulong
* onStackBits,
129
int
* sccStack,
130
EdgeContinuation
* contBuf,
131
int
* componentOut)
132
{
133
for
(
int
i =
0
; i < graph.NodeCount; i++)
134
disc[i] = -
1
;
135
136
int
timer =
0
, stackTop =
0
, sccCount =
0
;
137
138
for
(
int
root =
0
; root < graph.NodeCount; root++)
139
{
140
if
(disc[root] != -
1
)
141
continue
;
142
143
int
regNode = root;
144
int
regEdge =
0
;
145
int
depth =
0
;
146
147
Scc_Enter:
148
int
stamp = timer++;
149
disc[regNode] = stamp;
150
lowlink[regNode] = stamp;
151
sccStack[stackTop++] = regNode;
152
onStackBits[regNode >>
6
] |=
1UL
<< (regNode &
63
);
153
regEdge = graph.RowOffsets[regNode];
154
if
(regEdge == graph.RowOffsets[regNode +
1
])
155
goto
Scc_PostChildUnwind;
156
157
Scc_ScanEdge:
158
int
edgeEnd = graph.RowOffsets[regNode +
1
];
159
while
(regEdge < edgeEnd)
160
{
161
int
v = graph.ColIndices[regEdge++];
162
if
(disc[v] == -
1
)
163
{
164
contBuf[depth].Node = regNode;
165
contBuf[depth].EdgeIdx = regEdge;
166
depth++;
167
regNode = v;
168
goto
Scc_Enter;
169
}
170
if
((onStackBits[v >>
6
] & (
1UL
<< (v &
63
))) !=
0UL
&& disc[v] < lowlink[regNode])
171
{
172
lowlink[regNode] = disc[v];
173
}
174
}
175
176
Scc_PostChildUnwind:
177
if
(lowlink[regNode] == disc[regNode])
178
{
179
while
(true)
180
{
181
int
w = sccStack[--stackTop];
182
onStackBits[w >>
6
] &= ~(
1UL
<< (w &
63
));
183
componentOut[w] = sccCount;
184
if
(w == regNode)
break
;
185
}
186
sccCount++;
187
}
188
189
if
(depth >
0
)
190
{
191
int
childNode = regNode;
192
depth--;
193
regNode = contBuf[depth].Node;
194
regEdge = contBuf[depth].EdgeIdx;
195
if
(lowlink[childNode] < lowlink[regNode])
196
lowlink[regNode] = lowlink[childNode];
197
goto
Scc_ScanEdge;
198
}
199
}
200
201
return
sccCount;
202
}
203
204
// =========================================================================================
205
// 3A. Heuristic IDA* — 2-Bit Direction Continuations (32 Levels in One 64-Bit Register)
206
// =========================================================================================
207
[
MethodImpl
(
MethodImplOptions
.AggressiveInlining)]
208
private
static
int
StepDx(
int
dir) => dir ==
0
?
1
: (dir ==
1
? -
1
:
0
);
209
210
[
MethodImpl
(
MethodImplOptions
.AggressiveInlining)]
211
private
static
int
StepDy(
int
dir) => dir ==
2
?
1
: (dir ==
3
? -
1
:
0
);
212
213
public
static
int
IdaStarGridDefunc(
214
ulong
* obstacleBits,
215
ulong
* pathVisitedBits,
216
int
width,
217
int
height,
218
int
startX,
219
int
startY,
220
int
goalX,
221
int
goalY)
222
{
223
int
threshold =
Math
.Abs(goalX - startX) +
Math
.Abs(goalY - startY);
224
225
while
(true)
226
{
227
int
nextBound =
int
.MaxValue;
228
int
x = startX, y = startY, depth =
0
, regDir =
0
;
229
ulong
dirContReg =
0UL
;
// Packs 32 levels x 2 bits/direction in a single CPU register
230
231
Ida_Enter:
232
int
idx = y * width + x;
233
pathVisitedBits[idx >>
6
] |=
1UL
<< (idx &
63
);
234
235
int
fScore = depth +
Math
.Abs(goalX - x) +
Math
.Abs(goalY - y);
236
if
(fScore > threshold)
237
{
238
if
(fScore < nextBound) nextBound = fScore;
239
goto
Ida_Unwind;
240
}
241
if
(x == goalX && y == goalY)
242
{
243
pathVisitedBits[idx >>
6
] &= ~(
1UL
<< (idx &
63
));
244
return
depth;
245
}
246
if
(depth >=
31
)
247
goto
Ida_Unwind;
248
249
regDir =
0
;
250
251
Ida_TryDir:
252
while
(regDir <
4
)
253
{
254
int
d = regDir++;
255
int
nx = x + StepDx(d);
256
int
ny = y + StepDy(d);
257
if
((uint)nx >= (uint)width || (uint)ny >= (uint)height)
258
continue
;
259
260
int
nIdx = ny * width + nx;
261
ulong
mask =
1UL
<< (nIdx &
63
);
262
if
(((obstacleBits[nIdx >>
6
] | pathVisitedBits[nIdx >>
6
]) & mask) !=
0UL
)
263
continue
;
264
265
int
shift = depth <<
1
;
266
dirContReg = (dirContReg & ~(
3UL
<< shift)) | ((
ulong
)d << shift);
267
x = nx;
268
y = ny;
269
depth++;
270
goto
Ida_Enter;
271
}
272
273
Ida_Unwind:
274
int
curIdx = y * width + x;
275
pathVisitedBits[curIdx >>
6
] &= ~(
1UL
<< (curIdx &
63
));
276
if
(depth ==
0
)
277
{
278
if
(nextBound ==
int
.MaxValue)
return
-
1
;
279
threshold = nextBound;
280
continue
;
281
}
282
depth--;
283
int
prevDir = (
int
)((dirContReg >> (depth <<
1
)) &
3UL
);
284
x -= StepDx(prevDir);
285
y -= StepDy(prevDir);
286
regDir = prevDir +
1
;
287
goto
Ida_TryDir;
288
}
289
}
290
291
// =========================================================================================
292
// 3B. Flat Unmanaged A* — 1-Bit Closed Slab + Zero-Allocation Struct Binary Min-Heap
293
// =========================================================================================
294
public
static
int
AStarBitSlab(
295
ulong
* obstacleBits,
296
ulong
* closedBits,
297
int
* bestG,
298
AStarOpenSlot
* openHeap,
299
int
width,
300
int
height,
301
int
startIdx,
302
int
goalIdx)
303
{
304
int
total = width * height;
305
for
(
int
i =
0
; i < total; i++)
306
bestG[i] =
int
.MaxValue;
307
308
int
goalX = goalIdx % width, goalY = goalIdx / width;
309
bestG[startIdx] =
0
;
310
int
heapLen =
1
;
311
openHeap[
0
] =
new
AStarOpenSlot
312
{
313
Node = startIdx,
314
GScore =
0
,
315
FScore =
Math
.Abs(goalX - (startIdx % width)) +
Math
.Abs(goalY - (startIdx / width))
316
};
317
318
while
(heapLen >
0
)
319
{
320
AStarOpenSlot
top = openHeap[
0
];
321
AStarOpenSlot
last = openHeap[--heapLen];
322
int
p =
0
;
323
while
((p <<
1
) +
1
< heapLen)
324
{
325
int
c = (p <<
1
) +
1
;
326
if
(c +
1
< heapLen && openHeap[c +
1
].FScore < openHeap[c].FScore) c++;
327
if
(last.FScore <= openHeap[c].FScore)
break
;
328
openHeap[p] = openHeap[c];
329
p = c;
330
}
331
if
(heapLen >
0
) openHeap[p] = last;
332
333
int
u = top.Node;
334
ulong
uMask =
1UL
<< (u &
63
);
335
if
((closedBits[u >>
6
] & uMask) !=
0UL
)
continue
;
336
closedBits[u >>
6
] |= uMask;
337
if
(u == goalIdx)
return
top.GScore;
338
339
int
ux = u % width, uy = u / width;
340
for
(
int
d =
0
; d <
4
; d++)
341
{
342
int
nx = ux + StepDx(d), ny = uy + StepDy(d);
343
if
((uint)nx >= (uint)width || (uint)ny >= (uint)height)
continue
;
344
int
v = ny * width + nx;
345
ulong
vMask =
1UL
<< (v &
63
);
346
if
(((obstacleBits[v >>
6
] | closedBits[v >>
6
]) & vMask) !=
0UL
)
continue
;
347
348
int
candG = top.GScore +
1
;
349
if
(candG < bestG[v])
350
{
351
bestG[v] = candG;
352
int
f = candG +
Math
.Abs(goalX - nx) +
Math
.Abs(goalY - ny);
353
int
idx = heapLen++;
354
while
(idx >
0
)
355
{
356
int
par = (idx -
1
) >>
1
;
357
if
(openHeap[par].FScore <= f)
break
;
358
openHeap[idx] = openHeap[par];
359
idx = par;
360
}
361
openHeap[idx] =
new
AStarOpenSlot
{ Node = v, GScore = candG, FScore = f };
362
}
363
}
364
}
365
366
return
-
1
;
367
}
368
369
// =========================================================================================
370
// 4. 3D Octree Spatial Collision Search — 3-Bit Octant Continuations (21 Levels in 1 Register)
371
// =========================================================================================
372
public
static
int
OctreeCollisionDefunc(
373
OctreeNode
* nodes,
374
int
rootIdx,
375
float
qMinX,
float
qMinY,
float
qMinZ,
376
float
qMaxX,
float
qMaxY,
float
qMaxZ)
377
{
378
int
* ancestorNodes = stackalloc
int
[
21
];
// Stationary prologue allocation (Delta SP = 0)
379
ulong
octantContReg =
0UL
;
// 21 levels x 3 bits/octant = 63 bits in 1 register
380
int
currIdx = rootIdx;
381
int
regOctant =
0
;
382
int
depth =
0
;
383
384
Oct_Enter:
385
ref
OctreeNode
node =
ref
nodes[currIdx];
386
float
span = node.HalfSize *
2.0f
;
387
if
(qMaxX < node.MinX || qMinX > node.MinX + span ||
388
qMaxY < node.MinY || qMinY > node.MinY + span ||
389
qMaxZ < node.MinZ || qMinZ > node.MinZ + span)
390
{
391
goto
Oct_Unwind;
392
}
393
394
if
(node.FirstChildIdx <
0
)
395
{
396
if
(node.LeafVoxelBits !=
0UL
)
397
return
currIdx;
398
goto
Oct_Unwind;
399
}
400
401
regOctant =
0
;
402
403
Oct_NextOctant:
404
if
(regOctant <
8
&& depth <
21
)
405
{
406
int
oct = regOctant;
407
int
shift = depth *
3
;
408
octantContReg = (octantContReg & ~(
7UL
<< shift)) | ((
ulong
)oct << shift);
409
ancestorNodes[depth++] = currIdx;
410
currIdx = nodes[currIdx].FirstChildIdx + oct;
411
goto
Oct_Enter;
412
}
413
414
Oct_Unwind:
415
if
(depth ==
0
)
416
return
-
1
;
417
depth--;
418
currIdx = ancestorNodes[depth];
419
regOctant = (
int
)((octantContReg >> (depth *
3
)) &
7UL
) +
1
;
420
goto
Oct_NextOctant;
421
}
422
423
// =========================================================================================
424
// 5. Level-Order BFS — Word-Parallel 64-State 1-Bit Frontier Sweep (Zero Queue<T>)
425
// =========================================================================================
426
public
static
int
BfsBitFrontierSweep(
427
CsrGraph
graph,
428
int
sourceNode,
429
int
targetNode,
430
ulong
* currFrontier,
431
ulong
* nextFrontier,
432
ulong
* visitedBits,
433
int
wordCount)
434
{
435
if
(sourceNode == targetNode)
return
0
;
436
437
for
(
int
w =
0
; w < wordCount; w++)
438
{
439
currFrontier[w] =
0UL
;
440
nextFrontier[w] =
0UL
;
441
visitedBits[w] =
0UL
;
442
}
443
444
currFrontier[sourceNode >>
6
] =
1UL
<< (sourceNode &
63
);
445
visitedBits[sourceNode >>
6
] =
1UL
<< (sourceNode &
63
);
446
447
int
level =
0
;
448
int
wordIdx =
0
;
449
ulong
anyNext =
0UL
;
450
ulong
word =
0UL
;
451
452
Bfs_ScanWord:
453
if
(wordIdx >= wordCount)
454
goto
Bfs_AdvanceLevel;
455
456
word = currFrontier[wordIdx];
457
if
(word ==
0UL
)
458
{
459
wordIdx++;
460
goto
Bfs_ScanWord;
461
}
462
currFrontier[wordIdx] =
0UL
;
463
464
Bfs_ExpandNeighbors:
465
int
bit =
BitOperations
.TrailingZeroCount(word);
466
word &= word -
1UL
;
// Clear lowest set bit in 1 CPU cycle (blsr / bic)
467
int
u = (wordIdx <<
6
) + bit;
468
469
int
eStart = graph.RowOffsets[u];
470
int
eEnd = graph.RowOffsets[u +
1
];
471
for
(
int
e = eStart; e < eEnd; e++)
472
{
473
int
v = graph.ColIndices[e];
474
int
vw = v >>
6
;
475
ulong
vm =
1UL
<< (v &
63
);
476
if
((visitedBits[vw] & vm) ==
0UL
)
477
{
478
visitedBits[vw] |= vm;
479
if
(v == targetNode)
return
level +
1
;
480
nextFrontier[vw] |= vm;
481
anyNext =
1UL
;
482
}
483
}
484
485
if
(word !=
0UL
)
486
goto
Bfs_ExpandNeighbors;
487
488
wordIdx++;
489
goto
Bfs_ScanWord;
490
491
Bfs_AdvanceLevel:
492
if
(anyNext ==
0UL
)
493
return
-
1
;
494
495
ulong
* tmp = currFrontier;
496
currFrontier = nextFrontier;
497
nextFrontier = tmp;
498
level++;
499
wordIdx =
0
;
500
anyNext =
0UL
;
501
goto
Bfs_ScanWord;
502
}
503
}