-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathphpglfw_drawcall_assembler.c
More file actions
2334 lines (1989 loc) · 88.8 KB
/
Copy pathphpglfw_drawcall_assembler.c
File metadata and controls
2334 lines (1989 loc) · 88.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PHP-glfw
*
* Extension: DrawCallAssembler
*
* Copyright (c) 2018-2024 Mario Döring
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "phpglfw_drawcall_assembler.h"
#include "phpglfw_arginfo.h"
#include <math.h>
#include <string.h>
#include <float.h>
#include "cvector.h"
zend_class_entry *phpglfw_drawcall_assembler_ce;
zend_class_entry *phpglfw_get_drawcall_assembler_ce()
{
return phpglfw_drawcall_assembler_ce;
}
phpglfw_drawcall_assembler_object *phpglfw_drawcall_assembler_objectptr_from_zobj_p(zend_object *obj)
{
return (phpglfw_drawcall_assembler_object *)((char *)(obj)-XtOffsetOf(phpglfw_drawcall_assembler_object, std));
}
static zend_object_handlers phpglfw_drawcall_assembler_object_handlers;
static void phpglfw_drawcall_store_plane(vec4 dest, float a, float b, float c, float d);
static void phpglfw_drawcall_extract_frustum(phpglfw_drawcall_assembler_object *intern);
static uint32_t phpglfw_drawcall_collect_visible_indices(phpglfw_drawcall_assembler_object *intern, uint32_t *visible_indices);
static uint32_t phpglfw_drawcall_select_lod(phpglfw_drawcall_assembler_object *intern, phpglfw_drawcall_instance *instance, float distance);
static void phpglfw_drawcall_update_instance_lod(phpglfw_drawcall_assembler_object *intern, phpglfw_drawcall_instance *instance);
static void phpglfw_drawcall_refresh_instance_lods(phpglfw_drawcall_assembler_object *intern, const uint32_t *visible_indices, uint32_t visible_count);
static inline void phpglfw_drawcall_release_zval(zval *value)
{
if (!Z_ISUNDEF(*value))
{
zval_ptr_dtor(value);
ZVAL_UNDEF(value);
}
}
// release every PHP object a mesh holds a reference to and clear the raw
// typed pointers so they can never be read after the object is gone.
static void phpglfw_drawcall_release_mesh_refs(phpglfw_drawcall_mesh *mesh)
{
phpglfw_drawcall_release_zval(&mesh->aabb_min_zv);
phpglfw_drawcall_release_zval(&mesh->aabb_max_zv);
phpglfw_drawcall_release_zval(&mesh->lod_distances_zv);
phpglfw_drawcall_release_zval(&mesh->lod_handles_zv);
mesh->aabb_min = NULL;
mesh->aabb_max = NULL;
mesh->lod_distances = NULL;
mesh->lod_handles = NULL;
}
static zend_object *phpglfw_drawcall_assembler_create_object(zend_class_entry *class_type)
{
phpglfw_drawcall_assembler_object *intern = zend_object_alloc(sizeof(phpglfw_drawcall_assembler_object), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &phpglfw_drawcall_assembler_object_handlers;
// initialize all pointers to null
intern->command_buffer = NULL;
intern->instance_transform_buffer = NULL;
intern->instance_meta_buffer = NULL;
intern->instance_payload_buffer = NULL;
intern->meshes = NULL;
intern->instances = NULL;
intern->visible_index_buffer = NULL;
intern->sort_keys_a = NULL;
intern->sort_keys_b = NULL;
intern->sort_indices_b = NULL;
intern->sort_scratch_capacity = 0;
intern->oct_nodes = NULL;
intern->oct_node_capacity = 0;
intern->oct_node_count = 0;
intern->oct_instance_indices = NULL;
intern->oct_instance_scratch = NULL;
intern->oct_centers = NULL;
intern->oct_radii = NULL;
intern->oct_ignored_indices = NULL;
intern->oct_ignored_count = 0;
intern->oct_scratch_capacity = 0;
intern->oct_dirty = true;
intern->oct_max_depth = PHPGLFW_OCT_MAX_DEPTH;
intern->oct_min_leaf = PHPGLFW_OCT_MIN_LEAF_INSTANCES;
intern->camera_position = NULL;
intern->view_matrix = NULL;
intern->projection_matrix = NULL;
ZVAL_UNDEF(&intern->payload_data_buffer_zv);
ZVAL_UNDEF(&intern->camera_position_zv);
ZVAL_UNDEF(&intern->view_matrix_zv);
ZVAL_UNDEF(&intern->projection_matrix_zv);
memset(intern->frustum_planes, 0, sizeof(intern->frustum_planes));
intern->mesh_capacity = 0;
intern->mesh_count = 0;
intern->instance_capacity = 0;
intern->instance_count = 0;
intern->has_frustum = false;
intern->frustum_from_matrices = false;
intern->sort_mode = PHPGLFW_SORT_NONE;
intern->cull_strategy = PHPGLFW_CULL_LINEAR;
intern->auto_instancing = true;
intern->final_command_count = 0;
intern->final_instance_count = 0;
// rendering dispatch
intern->rendering_transform_buffer_data = NULL;
intern->rendering_payload_buffer_data = NULL;
return &intern->std;
}
static void phpglfw_drawcall_assembler_free_handler(zend_object *object)
{
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(object);
// release internal-only zvals
phpglfw_drawcall_release_zval(&intern->payload_data_buffer_zv);
phpglfw_drawcall_release_zval(&intern->camera_position_zv);
phpglfw_drawcall_release_zval(&intern->view_matrix_zv);
phpglfw_drawcall_release_zval(&intern->projection_matrix_zv);
// free mesh array, releasing every reference each mesh holds first.
// we iterate the full capacity because clearMeshes()/reset() only lower
// mesh_count, and every slot is either a live mesh or zero-initialized
// (all-UNDEF) memory, so releasing is always safe.
if (intern->meshes) {
for (uint32_t i = 0; i < intern->mesh_capacity; i++) {
phpglfw_drawcall_release_mesh_refs(&intern->meshes[i]);
}
efree(intern->meshes);
}
// free instance array
if (intern->instances) {
efree(intern->instances);
}
if (intern->visible_index_buffer) {
cvector_free(intern->visible_index_buffer);
}
// radix sort scratch buffers
if (intern->sort_keys_a) {
efree(intern->sort_keys_a);
}
if (intern->sort_keys_b) {
efree(intern->sort_keys_b);
}
if (intern->sort_indices_b) {
efree(intern->sort_indices_b);
}
// octree scratch buffers
if (intern->oct_nodes) {
efree(intern->oct_nodes);
}
if (intern->oct_instance_indices) {
efree(intern->oct_instance_indices);
}
if (intern->oct_instance_scratch) {
efree(intern->oct_instance_scratch);
}
if (intern->oct_centers) {
efree(intern->oct_centers);
}
if (intern->oct_radii) {
efree(intern->oct_radii);
}
if (intern->oct_ignored_indices) {
efree(intern->oct_ignored_indices);
}
// rendering dispatch
cvector_free(intern->rendering_transform_buffer_data);
cvector_free(intern->rendering_payload_buffer_data);
// we do own the internal VBOs, so make sure to delete them
if (intern->internal_transform_vbo != 0) {
glDeleteBuffers(1, &intern->internal_transform_vbo);
}
if (intern->internal_payload_vbo != 0) {
glDeleteBuffers(1, &intern->internal_payload_vbo);
}
zend_object_std_dtor(&intern->std);
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, __construct)
{
zend_long initial_mesh_capacity = 256;
zend_long initial_instance_capacity = 2048;
zend_long initial_command_capacity = 512;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|lll",
&initial_mesh_capacity,
&initial_instance_capacity,
&initial_command_capacity
) == FAILURE) {
RETURN_THROWS();
}
// a zero or negative seed would corrupt the heap: ecalloc(0, ...) allocates
// nothing and the capacity *= 2 growth path never grows 0, so the first
// write lands out of bounds. negatives also wrap to huge uint32_t values.
if (initial_mesh_capacity < 1 || initial_instance_capacity < 1 || initial_command_capacity < 1) {
zend_value_error("DrawCallAssembler capacities must be >= 1");
RETURN_THROWS();
}
if (initial_mesh_capacity > PHPGLFW_MAX_CAPACITY ||
initial_instance_capacity > PHPGLFW_MAX_CAPACITY ||
initial_command_capacity > PHPGLFW_MAX_CAPACITY) {
zend_value_error("DrawCallAssembler capacities exceed the maximum");
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
// allocate mesh storage
intern->mesh_capacity = initial_mesh_capacity;
intern->meshes = ecalloc(intern->mesh_capacity, sizeof(phpglfw_drawcall_mesh));
// allocate instance storage
intern->instance_capacity = initial_instance_capacity;
intern->instances = ecalloc(intern->instance_capacity, sizeof(phpglfw_drawcall_instance));
// for readonly properties, we must write directly to the properties table
// zend_update_property doesn't work with readonly properties declared in stubs
zend_object *this_obj = Z_OBJ_P(ZEND_THIS);
zval *prop;
// command buffer
prop = OBJ_PROP_NUM(this_obj, 0);
object_init_ex(prop, phpglfw_get_buffer_gluint_ce());
intern->command_buffer = phpglfw_buffer_gluint_objectptr_from_zobj_p(Z_OBJ_P(prop));
cvector_reserve(intern->command_buffer->vec, initial_command_capacity * PHPGLFW_COMMAND_STRIDE);
// instance transform buffer
prop = OBJ_PROP_NUM(this_obj, 1);
object_init_ex(prop, phpglfw_get_buffer_glfloat_ce());
intern->instance_transform_buffer = phpglfw_buffer_glfloat_objectptr_from_zobj_p(Z_OBJ_P(prop));
cvector_reserve(intern->instance_transform_buffer->vec, initial_instance_capacity * PHPGLFW_TRANSFORM_STRIDE);
// instance meta buffer
prop = OBJ_PROP_NUM(this_obj, 2);
object_init_ex(prop, phpglfw_get_buffer_gluint_ce());
intern->instance_meta_buffer = phpglfw_buffer_gluint_objectptr_from_zobj_p(Z_OBJ_P(prop));
cvector_reserve(intern->instance_meta_buffer->vec, initial_instance_capacity * PHPGLFW_INSTANCE_META_STRIDE);
// instance payload buffer
prop = OBJ_PROP_NUM(this_obj, 3);
object_init_ex(prop, phpglfw_get_buffer_glfloat_ce());
intern->instance_payload_buffer = phpglfw_buffer_glfloat_objectptr_from_zobj_p(Z_OBJ_P(prop));
// stride constants
prop = OBJ_PROP_NUM(this_obj, 4);
ZVAL_LONG(prop, PHPGLFW_COMMAND_STRIDE);
prop = OBJ_PROP_NUM(this_obj, 5);
ZVAL_LONG(prop, PHPGLFW_TRANSFORM_STRIDE);
prop = OBJ_PROP_NUM(this_obj, 6);
ZVAL_LONG(prop, PHPGLFW_INSTANCE_META_STRIDE);
// initialize internal VBO (will be created on first use)
intern->internal_transform_vbo = 0;
intern->internal_payload_vbo = 0;
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setCameraData)
{
zval *camera_position = NULL;
zval *view_matrix = NULL;
zval *projection_matrix = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|O!O!O!",
&camera_position, phpglfw_get_math_vec3_ce(),
&view_matrix, phpglfw_get_math_mat4_ce(),
&projection_matrix, phpglfw_get_math_mat4_ce()) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
// store camera data if provided. the "O!O!O!" parameter spec already
// guarantees each argument is either NULL or an object of the required
// class, so a non-NULL zval is always the expected object type.
phpglfw_drawcall_release_zval(&intern->camera_position_zv);
if (camera_position)
{
ZVAL_OBJ_COPY(&intern->camera_position_zv, Z_OBJ_P(camera_position));
intern->camera_position = phpglfw_math_vec3_objectptr_from_zobj_p(Z_OBJ(intern->camera_position_zv));
}
else
{
intern->camera_position = NULL;
}
phpglfw_drawcall_release_zval(&intern->view_matrix_zv);
if (view_matrix)
{
ZVAL_OBJ_COPY(&intern->view_matrix_zv, Z_OBJ_P(view_matrix));
intern->view_matrix = phpglfw_math_mat4_objectptr_from_zobj_p(Z_OBJ(intern->view_matrix_zv));
}
else
{
intern->view_matrix = NULL;
}
phpglfw_drawcall_release_zval(&intern->projection_matrix_zv);
if (projection_matrix)
{
ZVAL_OBJ_COPY(&intern->projection_matrix_zv, Z_OBJ_P(projection_matrix));
intern->projection_matrix = phpglfw_math_mat4_objectptr_from_zobj_p(Z_OBJ(intern->projection_matrix_zv));
}
else
{
intern->projection_matrix = NULL;
}
if (intern->view_matrix && intern->projection_matrix)
{
phpglfw_drawcall_extract_frustum(intern); // sets frustum_from_matrices = true
}
else if (intern->frustum_from_matrices)
{
// we no longer have both matrices to derive a frustum from (incomplete
// matrix update, or a position-only update). a previously matrix-derived
// frustum is now stale, so disable culling (safe default). a manually set
// frustum (setFrustumPlanes) is left intact.
intern->has_frustum = false;
intern->frustum_from_matrices = false;
}
}
static void phpglfw_drawcall_store_plane(vec4 dest, float a, float b, float c, float d)
{
float len = sqrtf((a * a) + (b * b) + (c * c));
if (len > 0.0f)
{
dest[0] = a / len;
dest[1] = b / len;
dest[2] = c / len;
dest[3] = d / len;
}
else
{
dest[0] = a;
dest[1] = b;
dest[2] = c;
dest[3] = d;
}
}
static void phpglfw_drawcall_extract_frustum(phpglfw_drawcall_assembler_object *intern)
{
mat4x4 clip;
mat4x4_mul(clip, intern->projection_matrix->data, intern->view_matrix->data);
float m[4][4];
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
m[row][col] = clip[col][row];
}
}
// left
phpglfw_drawcall_store_plane(
intern->frustum_planes[0],
m[3][0] + m[0][0],
m[3][1] + m[0][1],
m[3][2] + m[0][2],
m[3][3] + m[0][3]
);
// right
phpglfw_drawcall_store_plane(
intern->frustum_planes[1],
m[3][0] - m[0][0],
m[3][1] - m[0][1],
m[3][2] - m[0][2],
m[3][3] - m[0][3]
);
// bottom
phpglfw_drawcall_store_plane(
intern->frustum_planes[2],
m[3][0] + m[1][0],
m[3][1] + m[1][1],
m[3][2] + m[1][2],
m[3][3] + m[1][3]
);
// top
phpglfw_drawcall_store_plane(
intern->frustum_planes[3],
m[3][0] - m[1][0],
m[3][1] - m[1][1],
m[3][2] - m[1][2],
m[3][3] - m[1][3]
);
// near
phpglfw_drawcall_store_plane(
intern->frustum_planes[4],
m[3][0] + m[2][0],
m[3][1] + m[2][1],
m[3][2] + m[2][2],
m[3][3] + m[2][3]
);
// far
phpglfw_drawcall_store_plane(
intern->frustum_planes[5],
m[3][0] - m[2][0],
m[3][1] - m[2][1],
m[3][2] - m[2][2],
m[3][3] - m[2][3]
);
intern->has_frustum = true;
intern->frustum_from_matrices = true;
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, registerMesh)
{
zend_long vao_id;
zend_long vertex_offset = 0, vertex_count = 0;
zend_long index_offset = 0, index_count = 0;
zval *aabb_min = NULL, *aabb_max = NULL;
zend_long material_hint = 0;
zend_long primitive = 0x0004; // gl_triangles
if (zend_parse_parameters(ZEND_NUM_ARGS(),
"l|llllO!O!ll",
&vao_id,
&vertex_offset, &vertex_count,
&index_offset, &index_count,
&aabb_min, phpglfw_get_math_vec3_ce(),
&aabb_max, phpglfw_get_math_vec3_ce(),
&material_hint,
&primitive
) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
// resize mesh array if needed
if (intern->mesh_count >= intern->mesh_capacity) {
uint32_t old_capacity = intern->mesh_capacity;
intern->mesh_capacity *= 2;
intern->meshes = erealloc(intern->meshes, intern->mesh_capacity * sizeof(phpglfw_drawcall_mesh));
// erealloc does not zero the grown region; do it ourselves so the new
// slots have UNDEF zvals (releasing/overwriting them stays safe).
memset(&intern->meshes[old_capacity], 0, (intern->mesh_capacity - old_capacity) * sizeof(phpglfw_drawcall_mesh));
}
phpglfw_drawcall_mesh *mesh = &intern->meshes[intern->mesh_count];
// release anything a reused slot may still hold (after clearMeshes/reset)
phpglfw_drawcall_release_mesh_refs(mesh);
mesh->vao_id = vao_id;
mesh->vertex_offset = vertex_offset;
mesh->vertex_count = vertex_count;
mesh->index_offset = index_offset;
mesh->index_count = index_count;
mesh->material_hint = material_hint;
mesh->primitive = primitive;
// store bounding box if provided (holding a reference so it can't dangle).
// the "O!" spec guarantees a non-NULL arg is already a Vec3 object.
if (aabb_min) {
ZVAL_OBJ_COPY(&mesh->aabb_min_zv, Z_OBJ_P(aabb_min));
mesh->aabb_min = phpglfw_math_vec3_objectptr_from_zobj_p(Z_OBJ(mesh->aabb_min_zv));
} else {
mesh->aabb_min = NULL;
}
if (aabb_max) {
ZVAL_OBJ_COPY(&mesh->aabb_max_zv, Z_OBJ_P(aabb_max));
mesh->aabb_max = phpglfw_math_vec3_objectptr_from_zobj_p(Z_OBJ(mesh->aabb_max_zv));
} else {
mesh->aabb_max = NULL;
}
if (mesh->aabb_min && mesh->aabb_max)
{
mesh->has_bounds = true;
float half_extents[3];
for (int axis = 0; axis < 3; axis++) {
float min_val = mesh->aabb_min->data[axis];
float max_val = mesh->aabb_max->data[axis];
mesh->bounds_center[axis] = (min_val + max_val) * 0.5f;
half_extents[axis] = (max_val - min_val) * 0.5f;
}
mesh->bounds_radius = sqrtf(
(half_extents[0] * half_extents[0]) +
(half_extents[1] * half_extents[1]) +
(half_extents[2] * half_extents[2])
);
}
else
{
mesh->has_bounds = false;
mesh->bounds_radius = 0.0f;
mesh->bounds_center[0] = 0.0f;
mesh->bounds_center[1] = 0.0f;
mesh->bounds_center[2] = 0.0f;
}
// initialize lod data
mesh->lod_distances = NULL;
mesh->lod_handles = NULL;
uint32_t handle = intern->mesh_count;
intern->mesh_count++;
RETURN_LONG(handle);
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setLodTable)
{
zend_long mesh_handle;
zval *distance_thresholds, *mesh_handles;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "lOO",
&mesh_handle,
&distance_thresholds, phpglfw_get_buffer_glfloat_ce(),
&mesh_handles, phpglfw_get_buffer_gluint_ce()) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
if (mesh_handle < 0 || (uint32_t)mesh_handle >= intern->mesh_count) {
zend_throw_error(NULL, "invalid mesh handle");
RETURN_THROWS();
}
phpglfw_drawcall_mesh *mesh = &intern->meshes[mesh_handle];
// release any previously bound lod buffers before rebinding
phpglfw_drawcall_release_zval(&mesh->lod_distances_zv);
mesh->lod_distances = NULL;
phpglfw_drawcall_release_zval(&mesh->lod_handles_zv);
mesh->lod_handles = NULL;
// "O" guarantees objects of the expected buffer classes
ZVAL_OBJ_COPY(&mesh->lod_distances_zv, Z_OBJ_P(distance_thresholds));
mesh->lod_distances = phpglfw_buffer_glfloat_objectptr_from_zobj_p(Z_OBJ(mesh->lod_distances_zv));
ZVAL_OBJ_COPY(&mesh->lod_handles_zv, Z_OBJ_P(mesh_handles));
mesh->lod_handles = phpglfw_buffer_gluint_objectptr_from_zobj_p(Z_OBJ(mesh->lod_handles_zv));
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setMeshMaterial)
{
zend_long mesh_handle, material_id;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll", &mesh_handle, &material_id) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
if (mesh_handle < 0 || (uint32_t)mesh_handle >= intern->mesh_count) {
zend_throw_error(NULL, "invalid mesh handle");
RETURN_THROWS();
}
intern->meshes[mesh_handle].material_hint = material_id;
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setAutoInstancing)
{
zend_bool enabled;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "b", &enabled) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
intern->auto_instancing = enabled;
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setFrustumPlanes)
{
// note: avoid the identifiers "near"/"far" here, they are legacy macros
// predefined by the Windows headers (windef.h) and break compilation on MSVC
zval *left, *right, *bottom, *top, *near_plane, *far_plane;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "OOOOOO",
&left, phpglfw_get_math_vec4_ce(),
&right, phpglfw_get_math_vec4_ce(),
&bottom, phpglfw_get_math_vec4_ce(),
&top, phpglfw_get_math_vec4_ce(),
&near_plane, phpglfw_get_math_vec4_ce(),
&far_plane, phpglfw_get_math_vec4_ce()) == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
phpglfw_math_vec4_object *planes[6] = {
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(left)),
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(right)),
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(bottom)),
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(top)),
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(near_plane)),
phpglfw_math_vec4_objectptr_from_zobj_p(Z_OBJ_P(far_plane)),
};
for (int i = 0; i < 6; i++) {
memcpy(intern->frustum_planes[i], planes[i]->data, sizeof(vec4));
}
intern->has_frustum = true;
intern->frustum_from_matrices = false; // manually set, not matrix-derived
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setSortMode)
{
zend_long mode;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &mode) == FAILURE)
{
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
intern->sort_mode = mode;
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, setCullingStrategy)
{
zend_long strategy;
// -1 sentinels: "leave the current octree tuning unchanged"
zend_long octree_max_depth = -1;
zend_long octree_min_leaf = -1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &strategy, &octree_max_depth, &octree_min_leaf) == FAILURE)
{
RETURN_THROWS();
}
if (strategy < PHPGLFW_CULL_NONE || strategy > PHPGLFW_CULL_OCTREE) {
zend_value_error("invalid culling strategy, expected one of DrawCallAssembler::CULL_*");
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
intern->cull_strategy = (int)strategy;
// apply optional octree tuning; changing it invalidates any cached tree
if (octree_max_depth >= 0) {
if (octree_max_depth < 1 || octree_max_depth > PHPGLFW_OCT_MAX_DEPTH_LIMIT) {
zend_value_error("octree max depth must be between 1 and %d", PHPGLFW_OCT_MAX_DEPTH_LIMIT);
RETURN_THROWS();
}
intern->oct_max_depth = (int)octree_max_depth;
intern->oct_dirty = true;
}
if (octree_min_leaf >= 0) {
if (octree_min_leaf < 1) {
zend_value_error("octree min leaf instance count must be >= 1");
RETURN_THROWS();
}
intern->oct_min_leaf = (uint32_t)octree_min_leaf;
intern->oct_dirty = true;
}
}
PHP_METHOD(GL_Rendering_DrawCallAssembler, clearInstances)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_THROWS();
}
phpglfw_drawcall_assembler_object *intern = phpglfw_drawcall_assembler_objectptr_from_zobj_p(Z_OBJ_P(ZEND_THIS));
intern->instance_count = 0;
intern->final_command_count = 0;
intern->final_instance_count = 0;
intern->oct_dirty = true;
cvector_set_size(intern->command_buffer->vec, 0);
cvector_set_size(intern->instance_transform_buffer->vec, 0);
cvector_set_size(intern->instance_meta_buffer->vec, 0);
cvector_set_size(intern->instance_payload_buffer->vec, 0);
}
static float phpglfw_drawcall_distance_to_camera_sq(phpglfw_math_vec3_object *camera_pos, const mat4x4 transform)
{
const float dx = transform[3][0] - camera_pos->data[0];
const float dy = transform[3][1] - camera_pos->data[1];
const float dz = transform[3][2] - camera_pos->data[2];
return dx * dx + dy * dy + dz * dz;
}
// compute the world-space bounding sphere (center + radius) of an instance.
// this is the exact model both the linear and octree culling paths test: the
// mesh bounds center transformed to world space and the radius scaled by the
// largest axis scale of the transform. instances without mesh bounds fall back
// to the translation column and the (unscaled) mesh radius.
static void phpglfw_drawcall_instance_world_sphere(
const phpglfw_drawcall_instance *instance,
const phpglfw_drawcall_mesh *mesh,
float out_center[3],
float *out_radius
) {
float cx = instance->transform[3][0];
float cy = instance->transform[3][1];
float cz = instance->transform[3][2];
float scaled_radius = mesh->bounds_radius;
if (mesh->has_bounds)
{
// transform mesh center to world space
const float local_x = mesh->bounds_center[0];
const float local_y = mesh->bounds_center[1];
const float local_z = mesh->bounds_center[2];
cx = instance->transform[0][0] * local_x + instance->transform[1][0] * local_y + instance->transform[2][0] * local_z + instance->transform[3][0];
cy = instance->transform[0][1] * local_x + instance->transform[1][1] * local_y + instance->transform[2][1] * local_z + instance->transform[3][1];
cz = instance->transform[0][2] * local_x + instance->transform[1][2] * local_y + instance->transform[2][2] * local_z + instance->transform[3][2];
// compute uniform scale factor
const mat4x4 * const t = &instance->transform;
const float scale_x_sq = (*t)[0][0] * (*t)[0][0] + (*t)[0][1] * (*t)[0][1] + (*t)[0][2] * (*t)[0][2];
const float scale_y_sq = (*t)[1][0] * (*t)[1][0] + (*t)[1][1] * (*t)[1][1] + (*t)[1][2] * (*t)[1][2];
const float scale_z_sq = (*t)[2][0] * (*t)[2][0] + (*t)[2][1] * (*t)[2][1] + (*t)[2][2] * (*t)[2][2];
const float max_scale_sq = fmaxf(scale_x_sq, fmaxf(scale_y_sq, scale_z_sq));
scaled_radius *= sqrtf(max_scale_sq);
}
out_center[0] = cx;
out_center[1] = cy;
out_center[2] = cz;
*out_radius = scaled_radius;
}
// test a bounding sphere against the 6 frustum planes. a sphere is visible when
// its signed distance to every plane is >= -radius; we early-out on the first
// plane that rejects it.
static zend_always_inline bool phpglfw_drawcall_sphere_in_frustum(
const float frustum[6][4], float cx, float cy, float cz, float radius
) {
for (int plane = 0; plane < 6; plane++)
{
const float distance = frustum[plane][0] * cx + frustum[plane][1] * cy + frustum[plane][2] * cz + frustum[plane][3];
if (distance < -radius) {
return false;
}
}
return true;
}
// classify an axis-aligned box against the frustum: 0 = fully outside,
// 1 = intersecting, 2 = fully inside. uses the p-vertex / n-vertex test: for
// each plane the box corner farthest along the plane normal (p-vertex) decides
// "fully outside", the nearest corner (n-vertex) decides "not fully inside".
static int phpglfw_drawcall_aabb_frustum_class(const float frustum[6][4], const float mn[3], const float mx[3])
{
bool intersecting = false;
for (int plane = 0; plane < 6; plane++)
{
const float a = frustum[plane][0];
const float b = frustum[plane][1];
const float c = frustum[plane][2];
const float d = frustum[plane][3];
const float px = (a >= 0.0f) ? mx[0] : mn[0];
const float py = (b >= 0.0f) ? mx[1] : mn[1];
const float pz = (c >= 0.0f) ? mx[2] : mn[2];
if (a * px + b * py + c * pz + d < 0.0f) {
return 0; // p-vertex behind the plane => whole box outside
}
const float nx = (a >= 0.0f) ? mn[0] : mx[0];
const float ny = (b >= 0.0f) ? mn[1] : mx[1];
const float nz = (c >= 0.0f) ? mn[2] : mx[2];
if (a * nx + b * ny + c * nz + d < 0.0f) {
intersecting = true; // n-vertex behind the plane => box straddles it
}
}
return intersecting ? 1 : 2;
}
// grow the per-instance octree scratch arrays to hold at least `count` entries.
static void phpglfw_drawcall_oct_reserve_instances(phpglfw_drawcall_assembler_object *intern, uint32_t count)
{
if (intern->oct_scratch_capacity >= count) {
return;
}
uint32_t new_cap = intern->oct_scratch_capacity ? intern->oct_scratch_capacity : 256;
while (new_cap < count) {
new_cap *= 2;
}
intern->oct_instance_indices = erealloc(intern->oct_instance_indices, new_cap * sizeof(uint32_t));
intern->oct_instance_scratch = erealloc(intern->oct_instance_scratch, new_cap * sizeof(uint32_t));
intern->oct_ignored_indices = erealloc(intern->oct_ignored_indices, new_cap * sizeof(uint32_t));
intern->oct_centers = erealloc(intern->oct_centers, new_cap * 3 * sizeof(float));
intern->oct_radii = erealloc(intern->oct_radii, new_cap * sizeof(float));
intern->oct_scratch_capacity = new_cap;
}
// grow the octree node pool to hold at least `needed` nodes.
static void phpglfw_drawcall_oct_reserve_nodes(phpglfw_drawcall_assembler_object *intern, uint32_t needed)
{
if (intern->oct_node_capacity >= needed) {
return;
}
uint32_t new_cap = intern->oct_node_capacity ? intern->oct_node_capacity : 64;
while (new_cap < needed) {
new_cap *= 2;
}
intern->oct_nodes = erealloc(intern->oct_nodes, new_cap * sizeof(phpglfw_drawcall_octnode));
intern->oct_node_capacity = new_cap;
}
// compute a node's bounds as the union of the world-space sphere AABBs of the
// instances in its slice. spheres are indexed by instance id via oct_centers/
// oct_radii; the slice itself is a range of the oct_instance_indices permutation.
static void phpglfw_drawcall_oct_node_bounds(phpglfw_drawcall_assembler_object *intern, phpglfw_drawcall_octnode *node)
{
if (node->instance_count == 0) {
node->aabb_min[0] = node->aabb_min[1] = node->aabb_min[2] = 0.0f;
node->aabb_max[0] = node->aabb_max[1] = node->aabb_max[2] = 0.0f;
return;
}
float mn[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
float mx[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
const uint32_t end = node->first_instance + node->instance_count;
for (uint32_t i = node->first_instance; i < end; i++)
{
const uint32_t idx = intern->oct_instance_indices[i];
const float *c = &intern->oct_centers[idx * 3];
const float r = intern->oct_radii[idx];
for (int axis = 0; axis < 3; axis++) {
const float lo = c[axis] - r;
const float hi = c[axis] + r;
if (lo < mn[axis]) mn[axis] = lo;
if (hi > mx[axis]) mx[axis] = hi;
}
}
node->aabb_min[0] = mn[0]; node->aabb_min[1] = mn[1]; node->aabb_min[2] = mn[2];
node->aabb_max[0] = mx[0]; node->aabb_max[1] = mx[1]; node->aabb_max[2] = mx[2];
}
// recursively subdivide a node into 8 octants. recursion depth is bounded by
// PHPGLFW_OCT_MAX_DEPTH, so the stack usage is trivially bounded.
static void phpglfw_drawcall_oct_subdivide(phpglfw_drawcall_assembler_object *intern, uint32_t node_index, int depth)
{
const uint32_t first = intern->oct_nodes[node_index].first_instance;
const uint32_t count = intern->oct_nodes[node_index].instance_count;
if (count <= intern->oct_min_leaf || depth >= intern->oct_max_depth) {
intern->oct_nodes[node_index].is_leaf = true;
intern->oct_nodes[node_index].child_base = 0;
return;
}
// split at the center of the node bounds
const float sx = 0.5f * (intern->oct_nodes[node_index].aabb_min[0] + intern->oct_nodes[node_index].aabb_max[0]);
const float sy = 0.5f * (intern->oct_nodes[node_index].aabb_min[1] + intern->oct_nodes[node_index].aabb_max[1]);
const float sz = 0.5f * (intern->oct_nodes[node_index].aabb_min[2] + intern->oct_nodes[node_index].aabb_max[2]);
const uint32_t end = first + count;
// count how many instances fall into each octant (by sphere center)
uint32_t counts[8] = {0};
for (uint32_t i = first; i < end; i++)
{
const uint32_t idx = intern->oct_instance_indices[i];
const float *c = &intern->oct_centers[idx * 3];
const int oct = (c[0] >= sx ? 1 : 0) | (c[1] >= sy ? 2 : 0) | (c[2] >= sz ? 4 : 0);
counts[oct]++;
}
// if every instance lands in the same octant, splitting makes no progress
// (e.g. coincident centers), so keep this node as a leaf.
for (int oct = 0; oct < 8; oct++) {
if (counts[oct] == count) {
intern->oct_nodes[node_index].is_leaf = true;
intern->oct_nodes[node_index].child_base = 0;
return;
}
}
// stable-ish scatter of the slice into 8 contiguous octant buckets
uint32_t cursor[8];
uint32_t offset = first;
for (int oct = 0; oct < 8; oct++) {
cursor[oct] = offset;
offset += counts[oct];
}
for (uint32_t i = first; i < end; i++)
{
const uint32_t idx = intern->oct_instance_indices[i];
const float *c = &intern->oct_centers[idx * 3];
const int oct = (c[0] >= sx ? 1 : 0) | (c[1] >= sy ? 2 : 0) | (c[2] >= sz ? 4 : 0);
intern->oct_instance_scratch[cursor[oct]++] = idx;
}
memcpy(&intern->oct_instance_indices[first], &intern->oct_instance_scratch[first], count * sizeof(uint32_t));
// allocate 8 children; this may move the node pool, so we read/write the
// parent purely by index and re-fetch pointers after the reserve.
const uint32_t child_base = intern->oct_node_count;
phpglfw_drawcall_oct_reserve_nodes(intern, child_base + 8);
intern->oct_node_count += 8;
intern->oct_nodes[node_index].is_leaf = false;
intern->oct_nodes[node_index].child_base = child_base;
uint32_t child_first = first;
for (int oct = 0; oct < 8; oct++)
{
phpglfw_drawcall_octnode *child = &intern->oct_nodes[child_base + oct];
child->first_instance = child_first;
child->instance_count = counts[oct];
child->child_base = 0;
child->is_leaf = true;
child_first += counts[oct];
phpglfw_drawcall_oct_node_bounds(intern, child);
}
for (int oct = 0; oct < 8; oct++) {
if (counts[oct] > 0) {
phpglfw_drawcall_oct_subdivide(intern, child_base + oct, depth + 1);
}
}
}
// (re)build the persistent octree from the current instance set. runs only when
// the tree is dirty; the resulting tree is camera-independent and reused across
// frames until the instance set changes.
static void phpglfw_drawcall_build_octree(phpglfw_drawcall_assembler_object *intern)
{
const uint32_t total_instances = intern->instance_count;
const phpglfw_drawcall_instance * const instances = intern->instances;
const phpglfw_drawcall_mesh * const meshes = intern->meshes;
intern->oct_node_count = 0;
intern->oct_ignored_count = 0;
if (total_instances > 0) {
phpglfw_drawcall_oct_reserve_instances(intern, total_instances);
}
// partition instances: IGNORE_CULLING ones are emitted verbatim every frame
// and kept out of the tree; the rest go into the permutation and get their
// world spheres cached (indexed by instance id).
uint32_t culled_count = 0;
for (uint32_t i = 0; i < total_instances; i++)
{
const phpglfw_drawcall_instance * const instance = &instances[i];
if (instance->flags & PHPGLFW_FLAG_IGNORE_CULLING) {