euv-core 0.52.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
/// Exact packed byte size of one `#[repr(C)]` `GpuDrawIndirectArgs` record (`16` bytes).
pub const GPU_DRAW_INDIRECT_ARGS_BYTES: usize = 16;
/// Exact packed byte size of one `#[repr(C)]` `GpuLevelUniform` record (`64` bytes).
pub const GPU_LEVEL_UNIFORM_BYTES: usize = 64;
/// Workgroup / threadgroup width (`64` lanes) shared across MSL, WGSL, and GLSL ES 3.1 compute kernels.
pub const GPU_COMPUTE_WORKGROUP_SIZE: u32 = 64;
/// Sentinel BFS parent index indicating a root node with no parent.
pub const GPU_LAYOUT_NO_PARENT: u32 = u32::MAX;
/// Sentinel hit-test result indicating no node was hit at the query point.
pub const GPU_HIT_TEST_MISS: u32 = u32::MAX;
/// Packed `flags_kind` bit mask for the 4-bit layout mode discriminant (`bits[0..4]`).
pub const GPU_LAYOUT_MODE_MASK: u32 = 0x0000_000F;
/// Packed `flags_kind` bit shift for main-axis `justify_content` (`bits[4..7]`).
pub const GPU_LAYOUT_JUSTIFY_SHIFT: u32 = 4;
/// Packed `flags_kind` bit shift for cross-axis `align_items` (`bits[7..10]`).
pub const GPU_LAYOUT_ALIGN_SHIFT: u32 = 7;
/// Packed `flags_kind` bit flag marking a node dirty for layout computation (`bit 10`).
pub const GPU_LAYOUT_FLAG_DIRTY: u32 = 1 << 10;
/// Packed `flags_kind` bit flag marking a leaf with pre-measured intrinsic text size (`bit 11`).
pub const GPU_LAYOUT_FLAG_PREMEASURED: u32 = 1 << 11;
/// Packed `flags_kind` bit flag marking a node visible for culling and primitive emission (`bit 12`).
pub const GPU_LAYOUT_FLAG_VISIBLE: u32 = 1 << 12;
/// Packed `flags_kind` bit flag enabling clip containment on this container (`bit 13`).
pub const GPU_LAYOUT_FLAG_CLIPS_CHILDREN: u32 = 1 << 13;
/// Packed `flags_kind` bit flag enabling visual primitive emission for this node (`bit 14`).
pub const GPU_LAYOUT_FLAG_EMIT_VISUAL: u32 = 1 << 14;
/// Default vertex count per instanced UI quad (`6` vertices = `2` triangles).
pub const GPU_INDIRECT_QUAD_VERTEX_COUNT: u32 = 6;
/// Apple Metal (MSL) 4-kernel GPU compute layout, Blelloch scan/reduce, culling, indirect emission, and hit-test shader.
pub const MSL_COMPUTE_LAYOUT_SHADER: &str = r#"#include <metal_stdlib>
using namespace metal;

struct GpuLayoutNodeInput {
    uint parent_bfs;
    uint first_child;
    uint child_count;
    uint flags_kind;
    float4 pref_min_size;
    float4 pad_gap_flex;
    float4 extra_or_intrinsic;
};

struct GpuLayoutNodeOutput {
    float4 rect;
    float4 content_rect;
};

struct GpuVisualStyleInput {
    uint color_rgba;
    uint aux_color_rgba;
    uint uv_rect_packed0;
    uint uv_rect_packed1;
    uint radii_packed0;
    uint radii_packed1;
    uint kind_flags;
    uint extra_param;
    uint clip_ancestor_bfs;
    uint scroll_layer_id;
    uint reserved0;
    uint reserved1;
};

struct GpuPrimitiveInstance {
    float4 rect;
    float4 clip_rect;
    uint color_rgba;
    uint aux_color_rgba;
    uint uv_rect_packed0;
    uint uv_rect_packed1;
    uint radii_packed0;
    uint radii_packed1;
    uint kind_flags;
    uint extra_param;
};

struct GpuDrawIndirectArgs {
    uint vertex_count;
    atomic_uint instance_count;
    uint vertex_start;
    uint base_instance;
};

struct GpuLevelUniform {
    uint level_start;
    uint level_count;
    uint node_count;
    uint pass_flags;
    float2 viewport_size;
    float dt_secs;
    uint reserved;
    float4 root_boundary_rect;
    float2 pick_point;
    float2 pad_tail;
};

static inline float euv_blelloch_exclusive_scan_64(threadgroup float* buf, uint lid) {
    for (uint offset = 1u; offset < 64u; offset <<= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            buf[idx] += buf[idx - offset];
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    float total = buf[63u];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (lid == 0u) {
        buf[63u] = 0.0f;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint offset = 32u; offset >= 1u; offset >>= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            float temp = buf[idx - offset];
            buf[idx - offset] = buf[idx];
            buf[idx] += temp;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    return total;
}

static inline uint euv_blelloch_exclusive_scan_u32_64(threadgroup uint* buf, uint lid) {
    for (uint offset = 1u; offset < 64u; offset <<= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            buf[idx] += buf[idx - offset];
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    uint total = buf[63u];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (lid == 0u) {
        buf[63u] = 0u;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint offset = 32u; offset >= 1u; offset >>= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            uint temp = buf[idx - offset];
            buf[idx - offset] = buf[idx];
            buf[idx] += temp;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    return total;
}

kernel void euv_layout_measure_bottom_up(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint tg_id [[threadgroup_position_in_grid]],
    uint lid [[thread_position_in_threadgroup]]
) {
    if (tg_id >= uniform.level_count) {
        return;
    }
    uint node_idx = uniform.level_start + tg_id;
    if (node_idx >= uniform.node_count) {
        return;
    }
    GpuLayoutNodeInput node = inputs[node_idx];
    uint mode = node.flags_kind & 0xFu;
    float pref_w = node.pref_min_size.x;
    float pref_h = node.pref_min_size.y;
    float min_w = node.pref_min_size.z;
    float min_h = node.pref_min_size.w;
    float pad_h = node.pad_gap_flex.x;
    float pad_v = node.pad_gap_flex.y;
    float gap_main = node.pad_gap_flex.z;
    float col_gap = node.pad_gap_flex.w;
    uint count = node.child_count;
    if (count == 0u || (pref_w > 0.0f && pref_h > 0.0f)) {
        if (lid == 0u) {
            float mw = max((pref_w > 0.0f) ? pref_w : node.extra_or_intrinsic.z, min_w);
            float mh = max((pref_h > 0.0f) ? pref_h : node.extra_or_intrinsic.w, min_h);
            outputs[node_idx].content_rect = float4(0.0f, 0.0f, mw, mh);
        }
        return;
    }

    threadgroup float sum_w[64];
    threadgroup float sum_h[64];
    threadgroup float max_w[64];
    threadgroup float max_h[64];

    float local_sw = 0.0f;
    float local_sh = 0.0f;
    float local_mw = 0.0f;
    float local_mh = 0.0f;

    uint first = node.first_child;
    for (uint child_offset = lid; child_offset < count; child_offset += 64u) {
        uint child_idx = first + child_offset;
        if (child_idx < uniform.node_count) {
            float4 child_meas = outputs[child_idx].content_rect;
            local_sw += child_meas.z;
            local_sh += child_meas.w;
            local_mw = max(local_mw, child_meas.z);
            local_mh = max(local_mh, child_meas.w);
        }
    }
    sum_w[lid] = local_sw;
    sum_h[lid] = local_sh;
    max_w[lid] = local_mw;
    max_h[lid] = local_mh;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint stride = 32u; stride >= 1u; stride >>= 1u) {
        if (lid < stride) {
            sum_w[lid] += sum_w[lid + stride];
            sum_h[lid] += sum_h[lid + stride];
            max_w[lid] = max(max_w[lid], max_w[lid + stride]);
            max_h[lid] = max(max_h[lid], max_h[lid + stride]);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }

    if (lid == 0u) {
        float measured_w = 0.0f;
        float measured_h = 0.0f;
        if (count == 0u) {
            measured_w = (pref_w > 0.0f) ? pref_w : node.extra_or_intrinsic.z;
            measured_h = (pref_h > 0.0f) ? pref_h : node.extra_or_intrinsic.w;
        } else if (mode == 0u) {
            uint cols = max(1u, uint(round(max(node.extra_or_intrinsic.x, 1.0f))));
            uint rows = (count + cols - 1u) / cols;
            float grid_w = float(cols) * max_w[0] + float(cols > 0u ? cols - 1u : 0u) * col_gap + pad_h * 2.0f;
            float grid_h = float(rows) * max_h[0] + float(rows > 0u ? rows - 1u : 0u) * gap_main + pad_v * 2.0f;
            measured_w = (pref_w > 0.0f) ? pref_w : grid_w;
            measured_h = (pref_h > 0.0f) ? pref_h : grid_h;
        } else if (mode == 1u) {
            float gaps = float(count > 0u ? count - 1u : 0u) * gap_main;
            measured_w = (pref_w > 0.0f) ? pref_w : (sum_w[0] + gaps + pad_h * 2.0f);
            measured_h = (pref_h > 0.0f) ? pref_h : (max_h[0] + pad_v * 2.0f);
        } else if (mode == 2u || mode == 3u) {
            float gaps = float(count > 0u ? count - 1u : 0u) * gap_main;
            measured_w = (pref_w > 0.0f) ? pref_w : (max_w[0] + pad_h * 2.0f);
            measured_h = (pref_h > 0.0f) ? pref_h : (sum_h[0] + gaps + pad_v * 2.0f);
        } else {
            measured_w = (pref_w > 0.0f) ? pref_w : max_w[0];
            measured_h = (pref_h > 0.0f) ? pref_h : max_h[0];
        }
        measured_w = max(measured_w, min_w);
        measured_h = max(measured_h, min_h);
        outputs[node_idx].content_rect = float4(0.0f, 0.0f, measured_w, measured_h);
    }
}

kernel void euv_layout_solve_top_down(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint tg_id [[threadgroup_position_in_grid]],
    uint lid [[thread_position_in_threadgroup]]
) {
    if (tg_id >= uniform.level_count) {
        return;
    }
    uint parent_idx = uniform.level_start + tg_id;
    if (parent_idx >= uniform.node_count) {
        return;
    }
    GpuLayoutNodeInput parent = inputs[parent_idx];
    float pad_h = parent.pad_gap_flex.x;
    float pad_v = parent.pad_gap_flex.y;
    float gap_main = parent.pad_gap_flex.z;
    float col_gap = parent.pad_gap_flex.w;
    uint mode = parent.flags_kind & 0xFu;
    uint justify = (parent.flags_kind >> 4u) & 0x7u;
    uint align = (parent.flags_kind >> 7u) & 0x7u;

    if (lid == 0u && parent.parent_bfs == 0xFFFFFFFFu) {
        float4 root_r = uniform.root_boundary_rect;
        if (root_r.z <= 0.0f || root_r.w <= 0.0f) {
            root_r = float4(0.0f, 0.0f, uniform.viewport_size.x, uniform.viewport_size.y);
        }
        outputs[parent_idx].rect = root_r;
        outputs[parent_idx].content_rect = float4(
            root_r.x + pad_h,
            root_r.y + pad_v,
            max(0.0f, root_r.z - pad_h * 2.0f),
            max(0.0f, root_r.w - pad_v * 2.0f)
        );
    }
    threadgroup_barrier(mem_flags::mem_device);

    uint count = parent.child_count;
    if (count == 0u) {
        return;
    }
    uint first = parent.first_child;
    float4 p_rect = outputs[parent_idx].rect;
    float cx = p_rect.x + pad_h;
    float cy = p_rect.y + pad_v;
    float cw = max(0.0f, p_rect.z - pad_h * 2.0f);
    float ch = max(0.0f, p_rect.w - pad_v * 2.0f);

    threadgroup float scan_buf[64];
    threadgroup float aux_buf[64];

    if (mode == 0u) {
        uint cols = max(1u, uint(round(max(parent.extra_or_intrinsic.x, 1.0f))));
        uint rows = (count + cols - 1u) / cols;
        float cell_w = max(0.0f, (cw - float(cols > 0u ? cols - 1u : 0u) * col_gap) / float(cols));
        float row_running_y = cy;
        for (uint row_base = 0u; row_base < rows; row_base += 64u) {
            uint row_idx = row_base + lid;
            float row_h = 0.0f;
            if (row_idx < rows) {
                uint c_start = row_idx * cols;
                uint c_end = min(c_start + cols, count);
                for (uint c = c_start; c < c_end; ++c) {
                    uint ci = first + c;
                    if (ci < uniform.node_count) {
                        GpuLayoutNodeInput child = inputs[ci];
                        float h_meas = outputs[ci].content_rect.w;
                        float h_val = (child.pref_min_size.y > 0.0f) ? child.pref_min_size.y : h_meas;
                        row_h = max(row_h, max(h_val, child.pref_min_size.w));
                    }
                }
            }
            aux_buf[lid] = row_h;
            scan_buf[lid] = (row_idx < rows) ? (row_h + gap_main) : 0.0f;
            threadgroup_barrier(mem_flags::mem_threadgroup);
            float chunk_total = euv_blelloch_exclusive_scan_64(scan_buf, lid);
            if (row_idx < rows) {
                float y_pos = row_running_y + scan_buf[lid];
                float resolved_row_h = aux_buf[lid];
                uint c_start = row_idx * cols;
                uint c_end = min(c_start + cols, count);
                for (uint c = c_start; c < c_end; ++c) {
                    uint ci = first + c;
                    if (ci < uniform.node_count) {
                        GpuLayoutNodeInput child = inputs[ci];
                        uint col = c - c_start;
                        float x_pos = cx + float(col) * (cell_w + col_gap);
                        float child_w = (child.pref_min_size.x > 0.0f) ? min(child.pref_min_size.x, cell_w) : cell_w;
                        float child_h = (child.pref_min_size.y > 0.0f) ? child.pref_min_size.y : resolved_row_h;
                        float cph = child.pad_gap_flex.x;
                        float cpv = child.pad_gap_flex.y;
                        outputs[ci].rect = float4(x_pos, y_pos, child_w, child_h);
                        outputs[ci].content_rect = float4(
                            x_pos + cph,
                            y_pos + cpv,
                            max(0.0f, child_w - cph * 2.0f),
                            max(0.0f, child_h - cpv * 2.0f)
                        );
                    }
                }
            }
            row_running_y += chunk_total;
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }
    } else if (mode == 1u || mode == 2u || mode == 3u) {
        bool is_row = (mode == 1u);
        float avail_main = is_row ? cw : ch;
        float avail_cross = is_row ? ch : cw;
        float total_base = 0.0f;
        float total_grow = 0.0f;

        for (uint base = 0u; base < count; base += 64u) {
            uint c = base + lid;
            float base_sz = 0.0f;
            float grow_w = 0.0f;
            if (c < count) {
                uint ci = first + c;
                if (ci < uniform.node_count) {
                    GpuLayoutNodeInput child = inputs[ci];
                    float4 meas = outputs[ci].content_rect;
                    float pref_main = is_row ? child.pref_min_size.x : child.pref_min_size.y;
                    float min_main = is_row ? child.pref_min_size.z : child.pref_min_size.w;
                    float meas_main = is_row ? meas.z : meas.w;
                    base_sz = max((pref_main > 0.0f) ? pref_main : meas_main, min_main);
                    grow_w = (mode == 3u) ? 0.0f : max(child.pad_gap_flex.w, 0.0f);
                }
            }
            scan_buf[lid] = base_sz;
            aux_buf[lid] = grow_w;
            threadgroup_barrier(mem_flags::mem_threadgroup);
            for (uint stride = 32u; stride >= 1u; stride >>= 1u) {
                if (lid < stride) {
                    scan_buf[lid] += scan_buf[lid + stride];
                    aux_buf[lid] += aux_buf[lid + stride];
                }
                threadgroup_barrier(mem_flags::mem_threadgroup);
            }
            total_base += scan_buf[0];
            total_grow += aux_buf[0];
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }

        float gap_sum = float(count > 0u ? count - 1u : 0u) * gap_main;
        float free_main = max(0.0f, avail_main - total_base - gap_sum);
        float grow_unit = (total_grow > 0.0001f) ? (free_main / total_grow) : 0.0f;
        float used_main = total_base + gap_sum + ((total_grow > 0.0001f) ? free_main : 0.0f);
        float rem_main = max(0.0f, avail_main - used_main);
        float start_offset = 0.0f;
        float eff_gap = gap_main;
        if (justify == 1u) {
            start_offset = rem_main * 0.5f;
        } else if (justify == 2u) {
            start_offset = rem_main;
        } else if (justify == 3u && count > 1u) {
            eff_gap = gap_main + rem_main / float(count - 1u);
        }

        float running_main = start_offset;
        for (uint base = 0u; base < count; base += 64u) {
            uint c = base + lid;
            float resolved_main = 0.0f;
            float resolved_cross = 0.0f;
            if (c < count) {
                uint ci = first + c;
                if (ci < uniform.node_count) {
                    GpuLayoutNodeInput child = inputs[ci];
                    float4 meas = outputs[ci].content_rect;
                    float pref_main = is_row ? child.pref_min_size.x : child.pref_min_size.y;
                    float min_main = is_row ? child.pref_min_size.z : child.pref_min_size.w;
                    float meas_main = is_row ? meas.z : meas.w;
                    float grow_w = (mode == 3u) ? 0.0f : max(child.pad_gap_flex.w, 0.0f);
                    resolved_main = max((pref_main > 0.0f) ? pref_main : meas_main, min_main) + grow_w * grow_unit;

                    float pref_cross = is_row ? child.pref_min_size.y : child.pref_min_size.x;
                    float min_cross = is_row ? child.pref_min_size.w : child.pref_min_size.z;
                    float meas_cross = is_row ? meas.w : meas.z;
                    if (mode == 3u || align == 0u) {
                        resolved_cross = (pref_cross > 0.0f) ? pref_cross : max(avail_cross, min_cross);
                    } else {
                        resolved_cross = max((pref_cross > 0.0f) ? pref_cross : meas_cross, min_cross);
                    }
                }
            }
            scan_buf[lid] = (c < count) ? (resolved_main + eff_gap) : 0.0f;
            threadgroup_barrier(mem_flags::mem_threadgroup);
            float chunk_span = euv_blelloch_exclusive_scan_64(scan_buf, lid);
            if (c < count) {
                uint ci = first + c;
                if (ci < uniform.node_count) {
                    GpuLayoutNodeInput child = inputs[ci];
                    float main_pos = running_main + scan_buf[lid];
                    float cross_off = 0.0f;
                    if (align == 2u) {
                        cross_off = max(0.0f, avail_cross - resolved_cross) * 0.5f;
                    } else if (align == 3u) {
                        cross_off = max(0.0f, avail_cross - resolved_cross);
                    }
                    float x_pos = is_row ? (cx + main_pos) : (cx + cross_off);
                    float y_pos = is_row ? (cy + cross_off) : (cy + main_pos);
                    float w_val = is_row ? resolved_main : resolved_cross;
                    float h_val = is_row ? resolved_cross : resolved_main;
                    float cph = child.pad_gap_flex.x;
                    float cpv = child.pad_gap_flex.y;
                    outputs[ci].rect = float4(x_pos, y_pos, w_val, h_val);
                    outputs[ci].content_rect = float4(
                        x_pos + cph,
                        y_pos + cpv,
                        max(0.0f, w_val - cph * 2.0f),
                        max(0.0f, h_val - cpv * 2.0f)
                    );
                }
            }
            running_main += chunk_span;
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }
    } else if (mode == 4u) {
        for (uint c = lid; c < count; c += 64u) {
            uint ci = first + c;
            if (ci < uniform.node_count) {
                GpuLayoutNodeInput child = inputs[ci];
                float4 meas = outputs[ci].content_rect;
                float x_pos = cx + child.pad_gap_flex.x;
                float y_pos = cy + child.pad_gap_flex.y;
                float w_val = (child.pref_min_size.x > 0.0f) ? child.pref_min_size.x : max(meas.z, child.pref_min_size.z);
                float h_val = (child.pref_min_size.y > 0.0f) ? child.pref_min_size.y : max(meas.w, child.pref_min_size.w);
                outputs[ci].rect = float4(x_pos, y_pos, w_val, h_val);
                outputs[ci].content_rect = float4(x_pos, y_pos, w_val, h_val);
            }
        }
    } else if (mode == 5u) {
        float slot_w = (count > 0u) ? (cw / float(count)) : cw;
        for (uint c = lid; c < count; c += 64u) {
            uint ci = first + c;
            if (ci < uniform.node_count) {
                GpuLayoutNodeInput child = inputs[ci];
                float norm_v = clamp(child.extra_or_intrinsic.x, 0.0f, 1.0f);
                float norm_x = clamp(child.extra_or_intrinsic.y, 0.0f, 1.0f);
                float viz_kind = child.extra_or_intrinsic.w;
                float x_pos = 0.0f;
                float y_pos = 0.0f;
                float w_val = 0.0f;
                float h_val = 0.0f;
                if (viz_kind < 0.5f) {
                    w_val = max(1.0f, slot_w - gap_main);
                    h_val = max(1.0f, norm_v * ch);
                    x_pos = cx + float(c) * slot_w + gap_main * 0.5f;
                    y_pos = cy + (ch - h_val);
                } else {
                    w_val = max(child.pref_min_size.x, 4.0f);
                    h_val = max(child.pref_min_size.y, 4.0f);
                    x_pos = cx + norm_x * max(0.0f, cw - w_val);
                    y_pos = cy + (1.0f - norm_v) * max(0.0f, ch - h_val);
                }
                outputs[ci].rect = float4(x_pos, y_pos, w_val, h_val);
                outputs[ci].content_rect = float4(x_pos, y_pos, w_val, h_val);
            }
        }
    } else if (mode == 6u) {
        float dt = clamp(uniform.dt_secs, 0.0001f, 0.05f);
        for (uint c = lid; c < count; c += 64u) {
            uint ci = first + c;
            if (ci < uniform.node_count) {
                GpuLayoutNodeInput child = inputs[ci];
                float tx = child.pref_min_size.x;
                float ty = child.pref_min_size.y;
                float w_val = max(child.pref_min_size.z, 1.0f);
                float h_val = max(child.pref_min_size.w, 1.0f);
                float stiffness = max(child.pad_gap_flex.x, 0.0f);
                float damping = max(child.pad_gap_flex.y, 0.0f);
                float vx = child.pad_gap_flex.z;
                float vy = child.pad_gap_flex.w;
                float px = child.extra_or_intrinsic.x;
                float py = child.extra_or_intrinsic.y;
                float inv_mass = 1.0f / max(child.extra_or_intrinsic.z, 0.1f);
                float ax = ((tx - px) * stiffness - vx * damping) * inv_mass;
                float ay = ((ty - py) * stiffness - vy * damping) * inv_mass;
                float nvx = vx + ax * dt;
                float nvy = vy + ay * dt;
                float npx = px + nvx * dt;
                float npy = py + nvy * dt;
                outputs[ci].rect = float4(cx + npx, cy + npy, w_val, h_val);
                outputs[ci].content_rect = float4(npx, npy, nvx, nvy);
            }
        }
    }
}

kernel void euv_layout_measure_flat_leaves(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint gid [[thread_position_in_grid]]
) {
    if (gid >= uniform.level_count) {
        return;
    }
    uint node_idx = uniform.level_start + gid;
    if (node_idx >= uniform.node_count) {
        return;
    }
    GpuLayoutNodeInput node = inputs[node_idx];
    float pref_w = node.pref_min_size.x;
    float pref_h = node.pref_min_size.y;
    float min_w = node.pref_min_size.z;
    float min_h = node.pref_min_size.w;
    float mw = max((pref_w > 0.0f) ? pref_w : node.extra_or_intrinsic.z, min_w);
    float mh = max((pref_h > 0.0f) ? pref_h : node.extra_or_intrinsic.w, min_h);
    outputs[node_idx].content_rect = float4(0.0f, 0.0f, mw, mh);
}

kernel void euv_layout_solve_flat_children(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint gid [[thread_position_in_grid]]
) {
    uint parent_idx = uniform.level_start;
    if (parent_idx >= uniform.node_count) {
        return;
    }
    GpuLayoutNodeInput parent = inputs[parent_idx];
    float pad_h = parent.pad_gap_flex.x;
    float pad_v = parent.pad_gap_flex.y;
    float gap_main = parent.pad_gap_flex.z;
    float col_gap = parent.pad_gap_flex.w;
    uint mode = parent.flags_kind & 0xFu;
    float4 p_rect = outputs[parent_idx].rect;
    if (parent.parent_bfs == 0xFFFFFFFFu) {
        p_rect = uniform.root_boundary_rect;
        if (p_rect.z <= 0.0f || p_rect.w <= 0.0f) {
            p_rect = float4(0.0f, 0.0f, uniform.viewport_size.x, uniform.viewport_size.y);
        }
        if (gid == 0u) {
            outputs[parent_idx].rect = p_rect;
            outputs[parent_idx].content_rect = float4(
                p_rect.x + pad_h,
                p_rect.y + pad_v,
                max(0.0f, p_rect.z - pad_h * 2.0f),
                max(0.0f, p_rect.w - pad_v * 2.0f)
            );
        }
    }
    uint count = parent.child_count;
    if (gid >= count) {
        return;
    }
    uint ci = parent.first_child + gid;
    if (ci >= uniform.node_count) {
        return;
    }
    float cx = p_rect.x + pad_h;
    float cy = p_rect.y + pad_v;
    float cw = max(0.0f, p_rect.z - pad_h * 2.0f);
    float ch = max(0.0f, p_rect.w - pad_v * 2.0f);
    GpuLayoutNodeInput child = inputs[ci];
    if (mode == 0u) {
        uint cols = max(1u, uint(round(max(parent.extra_or_intrinsic.x, 1.0f))));
        uint row_idx = gid / cols;
        uint col = gid - row_idx * cols;
        float cell_w = max(0.0f, (cw - float(cols > 0u ? cols - 1u : 0u) * col_gap) / float(cols));
        float row_h = uniform.pad_tail.x;
        float x_pos = cx + float(col) * (cell_w + col_gap);
        float y_pos = cy + float(row_idx) * (row_h + gap_main);
        float child_w = (child.pref_min_size.x > 0.0f) ? min(child.pref_min_size.x, cell_w) : cell_w;
        float child_h = (child.pref_min_size.y > 0.0f) ? child.pref_min_size.y : row_h;
        float cph = child.pad_gap_flex.x;
        float cpv = child.pad_gap_flex.y;
        outputs[ci].rect = float4(x_pos, y_pos, child_w, child_h);
        outputs[ci].content_rect = float4(
            x_pos + cph,
            y_pos + cpv,
            max(0.0f, child_w - cph * 2.0f),
            max(0.0f, child_h - cpv * 2.0f)
        );
    } else if (mode == 4u) {
        float4 meas = outputs[ci].content_rect;
        float x_pos = cx + child.pad_gap_flex.x;
        float y_pos = cy + child.pad_gap_flex.y;
        float w_val = (child.pref_min_size.x > 0.0f) ? child.pref_min_size.x : max(meas.z, child.pref_min_size.z);
        float h_val = (child.pref_min_size.y > 0.0f) ? child.pref_min_size.y : max(meas.w, child.pref_min_size.w);
        outputs[ci].rect = float4(x_pos, y_pos, w_val, h_val);
        outputs[ci].content_rect = float4(x_pos, y_pos, w_val, h_val);
    } else if (mode == 5u) {
        float slot_w = (count > 0u) ? (cw / float(count)) : cw;
        float norm_v = clamp(child.extra_or_intrinsic.x, 0.0f, 1.0f);
        float norm_x = clamp(child.extra_or_intrinsic.y, 0.0f, 1.0f);
        float viz_kind = child.extra_or_intrinsic.w;
        float x_pos = 0.0f;
        float y_pos = 0.0f;
        float w_val = 0.0f;
        float h_val = 0.0f;
        if (viz_kind < 0.5f) {
            w_val = max(1.0f, slot_w - gap_main);
            h_val = max(1.0f, norm_v * ch);
            x_pos = cx + float(gid) * slot_w + gap_main * 0.5f;
            y_pos = cy + (ch - h_val);
        } else {
            w_val = max(child.pref_min_size.x, 4.0f);
            h_val = max(child.pref_min_size.y, 4.0f);
            x_pos = cx + norm_x * max(0.0f, cw - w_val);
            y_pos = cy + (1.0f - norm_v) * max(0.0f, ch - h_val);
        }
        outputs[ci].rect = float4(x_pos, y_pos, w_val, h_val);
        outputs[ci].content_rect = float4(x_pos, y_pos, w_val, h_val);
    } else if (mode == 6u) {
        float dt = clamp(uniform.dt_secs, 0.0001f, 0.05f);
        float tx = child.pref_min_size.x;
        float ty = child.pref_min_size.y;
        float w_val = max(child.pref_min_size.z, 1.0f);
        float h_val = max(child.pref_min_size.w, 1.0f);
        float stiffness = max(child.pad_gap_flex.x, 0.0f);
        float damping = max(child.pad_gap_flex.y, 0.0f);
        float vx = child.pad_gap_flex.z;
        float vy = child.pad_gap_flex.w;
        float px = child.extra_or_intrinsic.x;
        float py = child.extra_or_intrinsic.y;
        float inv_mass = 1.0f / max(child.extra_or_intrinsic.z, 0.1f);
        float ax = ((tx - px) * stiffness - vx * damping) * inv_mass;
        float ay = ((ty - py) * stiffness - vy * damping) * inv_mass;
        float nvx = vx + ax * dt;
        float nvy = vy + ay * dt;
        float npx = px + nvx * dt;
        float npy = py + nvy * dt;
        outputs[ci].rect = float4(cx + npx, cy + npy, w_val, h_val);
        outputs[ci].content_rect = float4(npx, npy, nvx, nvy);
    }
}

kernel void euv_layout_cull_and_emit(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    const device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    const device GpuVisualStyleInput* visuals [[buffer(2)]],
    device GpuPrimitiveInstance* out_prims [[buffer(3)]],
    device GpuDrawIndirectArgs* indirect_args [[buffer(4)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint gid [[thread_position_in_grid]],
    uint lid [[thread_position_in_threadgroup]]
) {
    threadgroup uint vis_scan[64];
    threadgroup uint group_base;

    bool emit = false;
    float4 rect = float4(0.0f);
    float4 clip = float4(0.0f, 0.0f, uniform.viewport_size.x, uniform.viewport_size.y);
    GpuVisualStyleInput vis;
    vis.color_rgba = 0u;
    vis.aux_color_rgba = 0u;
    vis.uv_rect_packed0 = 0u;
    vis.uv_rect_packed1 = 0u;
    vis.radii_packed0 = 0u;
    vis.radii_packed1 = 0u;
    vis.kind_flags = 0u;
    vis.extra_param = 0u;
    vis.clip_ancestor_bfs = 0xFFFFFFFFu;
    vis.scroll_layer_id = 0u;
    vis.reserved0 = 0u;
    vis.reserved1 = 0u;

    if (gid < uniform.node_count) {
        uint flags = inputs[gid].flags_kind;
        bool visible_flag = (flags & (1u << 12u)) != 0u;
        bool emit_flag = (flags & (1u << 14u)) != 0u;
        if (visible_flag && emit_flag) {
            rect = outputs[gid].rect;
            vis = visuals[gid];
            if (vis.clip_ancestor_bfs < uniform.node_count) {
                float4 anc = outputs[vis.clip_ancestor_bfs].rect;
                clip.x = max(clip.x, anc.x);
                clip.y = max(clip.y, anc.y);
                clip.z = min(clip.z, anc.x + anc.z);
                clip.w = min(clip.w, anc.y + anc.w);
            }
            bool non_empty = rect.z > 0.0f && rect.w > 0.0f && clip.z > clip.x && clip.w > clip.y;
            bool intersects = (rect.x + rect.z) > clip.x && rect.x < clip.z && (rect.y + rect.w) > clip.y && rect.y < clip.w;
            emit = non_empty && intersects;
        }
    }

    vis_scan[lid] = emit ? 1u : 0u;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint group_count = euv_blelloch_exclusive_scan_u32_64(vis_scan, lid);
    if (lid == 0u) {
        if (group_count > 0u) {
            group_base = atomic_fetch_add_explicit(&indirect_args->instance_count, group_count, memory_order_relaxed);
        } else {
            group_base = 0u;
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (emit) {
        uint slot = group_base + vis_scan[lid];
        GpuPrimitiveInstance prim;
        prim.rect = rect;
        prim.clip_rect = clip;
        prim.color_rgba = vis.color_rgba;
        prim.aux_color_rgba = vis.aux_color_rgba;
        prim.uv_rect_packed0 = vis.uv_rect_packed0;
        prim.uv_rect_packed1 = vis.uv_rect_packed1;
        prim.radii_packed0 = vis.radii_packed0;
        prim.radii_packed1 = vis.radii_packed1;
        prim.kind_flags = vis.kind_flags;
        prim.extra_param = vis.extra_param;
        out_prims[slot] = prim;
    }
}

kernel void euv_layout_hit_test(
    const device GpuLayoutNodeInput* inputs [[buffer(0)]],
    const device GpuLayoutNodeOutput* outputs [[buffer(1)]],
    const device GpuVisualStyleInput* visuals [[buffer(2)]],
    device atomic_uint* hit_result [[buffer(4)]],
    constant GpuLevelUniform& uniform [[buffer(5)]],
    uint gid [[thread_position_in_grid]],
    uint lid [[thread_position_in_threadgroup]]
) {
    threadgroup uint local_max[64];
    uint cand = 0u;
    if (gid < uniform.node_count) {
        uint flags = inputs[gid].flags_kind;
        if ((flags & (1u << 12u)) != 0u) {
            float4 r = outputs[gid].rect;
            float4 clip = float4(0.0f, 0.0f, uniform.viewport_size.x, uniform.viewport_size.y);
            uint anc_idx = visuals[gid].clip_ancestor_bfs;
            if (anc_idx < uniform.node_count) {
                float4 anc = outputs[anc_idx].rect;
                clip.x = max(clip.x, anc.x);
                clip.y = max(clip.y, anc.y);
                clip.z = min(clip.z, anc.x + anc.z);
                clip.w = min(clip.w, anc.y + anc.w);
            }
            float px = uniform.pick_point.x;
            float py = uniform.pick_point.y;
            bool in_rect = px >= r.x && px < (r.x + r.z) && py >= r.y && py < (r.y + r.w);
            bool in_clip = px >= clip.x && px < clip.z && py >= clip.y && py < clip.w;
            if (in_rect && in_clip) {
                cand = gid + 1u;
            }
        }
    }
    local_max[lid] = cand;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint stride = 32u; stride >= 1u; stride >>= 1u) {
        if (lid < stride) {
            local_max[lid] = max(local_max[lid], local_max[lid + stride]);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    if (lid == 0u && local_max[0] > 0u) {
        atomic_fetch_max_explicit(hit_result, local_max[0], memory_order_relaxed);
    }
}
"#;
/// Portable WebGPU (WGSL) 4-kernel compute layout, Blelloch scan/reduce, culling, indirect emission, and hit-test shader.
pub const WGSL_COMPUTE_LAYOUT_SHADER: &str = r#"struct GpuLayoutNodeInput {
    parent_bfs: u32,
    first_child: u32,
    child_count: u32,
    flags_kind: u32,
    pref_min_size: vec4<f32>,
    pad_gap_flex: vec4<f32>,
    extra_or_intrinsic: vec4<f32>,
};
struct GpuLayoutNodeOutput {
    rect: vec4<f32>,
    content_rect: vec4<f32>,
};
struct GpuVisualStyleInput {
    color_rgba: u32,
    aux_color_rgba: u32,
    uv_rect: vec2<u32>,
    radii_border: vec2<u32>,
    kind_flags: u32,
    extra_param: u32,
    clip_ancestor_bfs: u32,
    scroll_layer_id: u32,
    reserved: vec2<u32>,
};
struct GpuPrimitiveInstance {
    rect: vec4<f32>,
    clip_rect: vec4<f32>,
    color_rgba: u32,
    aux_color_rgba: u32,
    uv_rect: vec2<u32>,
    radii_border: vec2<u32>,
    kind_flags: u32,
    extra_param: u32,
};
struct GpuDrawIndirectArgs {
    vertex_count: u32,
    instance_count: atomic<u32>,
    vertex_start: u32,
    base_instance: u32,
};
struct GpuLevelUniform {
    level_start: u32,
    level_count: u32,
    node_count: u32,
    pass_flags: u32,
    viewport_size: vec2<f32>,
    dt_secs: f32,
    reserved: u32,
    root_boundary_rect: vec4<f32>,
    pick_point: vec2<f32>,
    pad_tail: vec2<f32>,
};
@group(0) @binding(0) var<storage, read> inputs: array<GpuLayoutNodeInput>;
@group(0) @binding(1) var<storage, read_write> outputs: array<GpuLayoutNodeOutput>;
@group(0) @binding(2) var<storage, read> visuals: array<GpuVisualStyleInput>;
@group(0) @binding(3) var<storage, read_write> out_prims: array<GpuPrimitiveInstance>;
@group(0) @binding(4) var<storage, read_write> indirect_args: GpuDrawIndirectArgs;
@group(0) @binding(5) var<uniform> u_level: GpuLevelUniform;
var<workgroup> wg_sum_w: array<f32, 64>;
var<workgroup> wg_sum_h: array<f32, 64>;
var<workgroup> wg_max_w: array<f32, 64>;
var<workgroup> wg_max_h: array<f32, 64>;
var<workgroup> wg_vis_scan: array<u32, 64>;
var<workgroup> wg_group_base: u32;
@compute @workgroup_size(64)
fn euv_layout_measure_bottom_up(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
    if (wg.x >= u_level.level_count) { return; }
    let node_idx = u_level.level_start + wg.x;
    if (node_idx >= u_level.node_count) { return; }
    let node = inputs[node_idx];
    var sw = 0.0; var sh = 0.0; var mw = 0.0; var mh = 0.0;
    for (var c = lid; c < node.child_count; c = c + 64u) {
        let ci = node.first_child + c;
        if (ci < u_level.node_count) {
            let m = outputs[ci].content_rect;
            sw = sw + m.z; sh = sh + m.w; mw = max(mw, m.z); mh = max(mh, m.w);
        }
    }
    wg_sum_w[lid] = sw; wg_sum_h[lid] = sh; wg_max_w[lid] = mw; wg_max_h[lid] = mh;
    workgroupBarrier();
    for (var stride = 32u; stride >= 1u; stride = stride >> 1u) {
        if (lid < stride) {
            wg_sum_w[lid] = wg_sum_w[lid] + wg_sum_w[lid + stride];
            wg_sum_h[lid] = wg_sum_h[lid] + wg_sum_h[lid + stride];
            wg_max_w[lid] = max(wg_max_w[lid], wg_max_w[lid + stride]);
            wg_max_h[lid] = max(wg_max_h[lid], wg_max_h[lid + stride]);
        }
        workgroupBarrier();
    }
    if (lid == 0u) {
        let mw_out = max(select(node.extra_or_intrinsic.z, node.pref_min_size.x, node.pref_min_size.x > 0.0), node.pref_min_size.z);
        let mh_out = max(select(node.extra_or_intrinsic.w, node.pref_min_size.y, node.pref_min_size.y > 0.0), node.pref_min_size.w);
        outputs[node_idx].content_rect = vec4<f32>(0.0, 0.0, max(mw_out, wg_max_w[0]), max(mh_out, wg_max_h[0]));
    }
}
@compute @workgroup_size(64)
fn euv_layout_solve_top_down(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
    if (wg.x >= u_level.level_count) { return; }
    let parent_idx = u_level.level_start + wg.x;
    if (parent_idx >= u_level.node_count) { return; }
    let parent = inputs[parent_idx];
    if (lid == 0u && parent.parent_bfs == 0xFFFFFFFFu) {
        outputs[parent_idx].rect = u_level.root_boundary_rect;
        outputs[parent_idx].content_rect = u_level.root_boundary_rect;
    }
    workgroupBarrier();
    let p_rect = outputs[parent_idx].rect;
    let cols = max(1u, u32(round(max(parent.extra_or_intrinsic.x, 1.0))));
    let cell_w = max(0.0, (p_rect.z - parent.pad_gap_flex.x * 2.0 - f32(cols - 1u) * parent.pad_gap_flex.w) / f32(cols));
    for (var c = lid; c < parent.child_count; c = c + 64u) {
        let ci = parent.first_child + c;
        if (ci < u_level.node_count) {
            let child = inputs[ci];
            let col = c % cols;
            let row = c / cols;
            let h_val = max(child.pref_min_size.y, max(outputs[ci].content_rect.w, child.pref_min_size.w));
            let x_pos = p_rect.x + parent.pad_gap_flex.x + f32(col) * (cell_w + parent.pad_gap_flex.w);
            let y_pos = p_rect.y + parent.pad_gap_flex.y + f32(row) * (h_val + parent.pad_gap_flex.z);
            outputs[ci].rect = vec4<f32>(x_pos, y_pos, cell_w, h_val);
            outputs[ci].content_rect = vec4<f32>(x_pos, y_pos, cell_w, h_val);
        }
    }
}
@compute @workgroup_size(64)
fn euv_layout_cull_and_emit(@builtin(global_invocation_id) gid3: vec3<u32>, @builtin(local_invocation_index) lid: u32) {
    let gid = gid3.x;
    var emit = false;
    var rect = vec4<f32>(0.0);
    let clip = vec4<f32>(0.0, 0.0, u_level.viewport_size.x, u_level.viewport_size.y);
    if (gid < u_level.node_count) {
        let flags = inputs[gid].flags_kind;
        if ((flags & (1u << 12u)) != 0u && (flags & (1u << 14u)) != 0u) {
            rect = outputs[gid].rect;
            emit = rect.z > 0.0 && rect.w > 0.0 && (rect.x + rect.z) > clip.x && rect.x < clip.z && (rect.y + rect.w) > clip.y && rect.y < clip.w;
        }
    }
    wg_vis_scan[lid] = select(0u, 1u, emit);
    workgroupBarrier();
    for (var offset = 1u; offset < 64u; offset = offset << 1u) {
        let idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) { wg_vis_scan[idx] = wg_vis_scan[idx] + wg_vis_scan[idx - offset]; }
        workgroupBarrier();
    }
    let total = wg_vis_scan[63u];
    workgroupBarrier();
    if (lid == 0u) {
        wg_vis_scan[63u] = 0u;
        wg_group_base = select(0u, atomicAdd(&indirect_args.instance_count, total), total > 0u);
    }
    workgroupBarrier();
    for (var offset = 32u; offset >= 1u; offset = offset >> 1u) {
        let idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            let tmp = wg_vis_scan[idx - offset];
            wg_vis_scan[idx - offset] = wg_vis_scan[idx];
            wg_vis_scan[idx] = wg_vis_scan[idx] + tmp;
        }
        workgroupBarrier();
    }
    if (emit) {
        let slot = wg_group_base + wg_vis_scan[lid];
        let vis = visuals[gid];
        out_prims[slot] = GpuPrimitiveInstance(rect, clip, vis.color_rgba, vis.aux_color_rgba, vis.uv_rect, vis.radii_border, vis.kind_flags, vis.extra_param);
    }
}
@compute @workgroup_size(64)
fn euv_layout_hit_test(@builtin(global_invocation_id) gid3: vec3<u32>) {
    let gid = gid3.x;
    if (gid >= u_level.node_count) { return; }
    let r = outputs[gid].rect;
    let p = u_level.pick_point;
    if (p.x >= r.x && p.x < r.x + r.z && p.y >= r.y && p.y < r.y + r.w) {
        atomicMax(&indirect_args.instance_count, gid + 1u);
    }
}
"#;
/// Portable OpenGL ES 3.1 / Vulkan GLSL compute layout, Blelloch compaction, and indirect emission shader.
pub const GLSL_ES31_COMPUTE_LAYOUT_SHADER: &str = r#"#version 310 es
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
struct GpuLayoutNodeInput {
    uvec4 topo_flags;
    vec4 pref_min_size;
    vec4 pad_gap_flex;
    vec4 extra_or_intrinsic;
};
struct GpuLayoutNodeOutput {
    vec4 rect;
    vec4 content_rect;
};
struct GpuVisualStyleInput {
    uvec4 colors_uv;
    uvec4 radii_kind_extra;
    uvec4 clip_scroll_pad;
};
struct GpuPrimitiveInstance {
    vec4 rect;
    vec4 clip_rect;
    uvec4 colors_uv;
    uvec4 radii_kind_extra;
};
layout(std430, binding = 0) readonly buffer InputsBuf { GpuLayoutNodeInput inputs[]; };
layout(std430, binding = 1) buffer OutputsBuf { GpuLayoutNodeOutput outputs[]; };
layout(std430, binding = 2) readonly buffer VisualsBuf { GpuVisualStyleInput visuals[]; };
layout(std430, binding = 3) writeonly buffer PrimitivesBuf { GpuPrimitiveInstance out_prims[]; };
layout(std430, binding = 4) buffer IndirectArgsBuf {
    uint vertex_count;
    uint instance_count;
    uint vertex_start;
    uint base_instance;
} indirect_args;
uniform uvec4 u_level_meta;
uniform vec4 u_viewport_dt;
shared uint sh_vis_scan[64];
shared uint sh_group_base;
void main() {
    uint gid = gl_GlobalInvocationID.x;
    uint lid = gl_LocalInvocationID.x;
    bool emit = false;
    vec4 rect = vec4(0.0);
    vec4 clip = vec4(0.0, 0.0, u_viewport_dt.x, u_viewport_dt.y);
    if (gid < u_level_meta.z) {
        uint flags = inputs[gid].topo_flags.w;
        if ((flags & (1u << 12u)) != 0u && (flags & (1u << 14u)) != 0u) {
            rect = outputs[gid].rect;
            emit = rect.z > 0.0 && rect.w > 0.0 && (rect.x + rect.z) > clip.x && rect.x < clip.z && (rect.y + rect.w) > clip.y && rect.y < clip.w;
        }
    }
    sh_vis_scan[lid] = emit ? 1u : 0u;
    barrier();
    for (uint offset = 1u; offset < 64u; offset <<= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) { sh_vis_scan[idx] += sh_vis_scan[idx - offset]; }
        barrier();
    }
    uint total = sh_vis_scan[63u];
    barrier();
    if (lid == 0u) {
        sh_vis_scan[63u] = 0u;
        sh_group_base = (total > 0u) ? atomicAdd(indirect_args.instance_count, total) : 0u;
    }
    barrier();
    for (uint offset = 32u; offset >= 1u; offset >>= 1u) {
        uint idx = (lid + 1u) * offset * 2u - 1u;
        if (idx < 64u) {
            uint tmp = sh_vis_scan[idx - offset];
            sh_vis_scan[idx - offset] = sh_vis_scan[idx];
            sh_vis_scan[idx] += tmp;
        }
        barrier();
    }
    if (emit) {
        uint slot = sh_group_base + sh_vis_scan[lid];
        out_prims[slot].rect = rect;
        out_prims[slot].clip_rect = clip;
        out_prims[slot].colors_uv = visuals[gid].colors_uv;
        out_prims[slot].radii_kind_extra = visuals[gid].radii_kind_extra;
    }
}
"#;

#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_MEASURE: &str = "euv_layout_measure_bottom_up";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_MEASURE_LEAVES: &str = "euv_layout_measure_flat_leaves";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_SOLVE: &str = "euv_layout_solve_top_down";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_SOLVE_FLAT: &str = "euv_layout_solve_flat_children";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_CULL_EMIT: &str = "euv_layout_cull_and_emit";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_COMPUTE_FN_HIT_TEST: &str = "euv_layout_hit_test";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_NEW_COMPUTE_PSO: &str = "newComputePipelineStateWithFunction:error:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_COMPUTE_ENCODER: &str = "computeCommandEncoder\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_SET_COMPUTE_PSO: &str = "setComputePipelineState:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_SET_COMPUTE_BUFFER: &str = "setBuffer:offset:atIndex:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_SET_COMPUTE_BYTES: &str = "setBytes:length:atIndex:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_DISPATCH_THREADGROUPS: &str =
    "dispatchThreadgroups:threadsPerThreadgroup:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_DRAW_PRIMITIVES_INDIRECT: &str =
    "drawPrimitives:indirectBuffer:indirectBufferOffset:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_GET_BYTES_REGION: &str = "getBytes:bytesPerRow:fromRegion:mipmapLevel:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_SET_STORAGE_MODE: &str = "setStorageMode:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_HAS_UNIFIED_MEMORY: &str = "hasUnifiedMemory\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_BLIT_ENCODER: &str = "blitCommandEncoder\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_SYNC_RESOURCE: &str = "synchronizeResource:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_SEL_COPY_FROM_BUFFER: &str =
    "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:\0";
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_TEX_USAGE_SHADER_READ_RENDER_TARGET: usize = 5;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_STORAGE_MODE_SHARED: usize = 0;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_STORAGE_MODE_MANAGED: usize = 1;
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) const MTL_RESOURCE_STORAGE_MODE_PRIVATE: usize = 32;