-
-
Notifications
You must be signed in to change notification settings - Fork 21.3k
/
csg_shape.cpp
2606 lines (2119 loc) · 79.1 KB
/
csg_shape.cpp
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
/**************************************************************************/
/* csg_shape.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "csg_shape.h"
#include "core/math/geometry_2d.h"
#include <manifold/manifold.h>
void CSGShape3D::set_use_collision(bool p_enable) {
if (use_collision == p_enable) {
return;
}
use_collision = p_enable;
if (!is_inside_tree() || !is_root_shape()) {
return;
}
if (use_collision) {
root_collision_shape.instantiate();
root_collision_instance = PhysicsServer3D::get_singleton()->body_create();
PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC);
PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
PhysicsServer3D::get_singleton()->body_add_shape(root_collision_instance, root_collision_shape->get_rid());
PhysicsServer3D::get_singleton()->body_set_space(root_collision_instance, get_world_3d()->get_space());
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id());
set_collision_layer(collision_layer);
set_collision_mask(collision_mask);
set_collision_priority(collision_priority);
_make_dirty(); //force update
} else {
PhysicsServer3D::get_singleton()->free(root_collision_instance);
root_collision_instance = RID();
root_collision_shape.unref();
}
notify_property_list_changed();
}
bool CSGShape3D::is_using_collision() const {
return use_collision;
}
void CSGShape3D::set_collision_layer(uint32_t p_layer) {
collision_layer = p_layer;
if (root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->body_set_collision_layer(root_collision_instance, p_layer);
}
}
uint32_t CSGShape3D::get_collision_layer() const {
return collision_layer;
}
void CSGShape3D::set_collision_mask(uint32_t p_mask) {
collision_mask = p_mask;
if (root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->body_set_collision_mask(root_collision_instance, p_mask);
}
}
uint32_t CSGShape3D::get_collision_mask() const {
return collision_mask;
}
void CSGShape3D::set_collision_layer_value(int p_layer_number, bool p_value) {
ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
uint32_t layer = get_collision_layer();
if (p_value) {
layer |= 1 << (p_layer_number - 1);
} else {
layer &= ~(1 << (p_layer_number - 1));
}
set_collision_layer(layer);
}
bool CSGShape3D::get_collision_layer_value(int p_layer_number) const {
ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
return get_collision_layer() & (1 << (p_layer_number - 1));
}
void CSGShape3D::set_collision_mask_value(int p_layer_number, bool p_value) {
ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
uint32_t mask = get_collision_mask();
if (p_value) {
mask |= 1 << (p_layer_number - 1);
} else {
mask &= ~(1 << (p_layer_number - 1));
}
set_collision_mask(mask);
}
bool CSGShape3D::get_collision_mask_value(int p_layer_number) const {
ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
return get_collision_mask() & (1 << (p_layer_number - 1));
}
void CSGShape3D::set_collision_priority(real_t p_priority) {
collision_priority = p_priority;
if (root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->body_set_collision_priority(root_collision_instance, p_priority);
}
}
real_t CSGShape3D::get_collision_priority() const {
return collision_priority;
}
bool CSGShape3D::is_root_shape() const {
return !parent_shape;
}
void CSGShape3D::set_snap(float p_snap) {
if (snap == p_snap) {
return;
}
snap = p_snap;
_make_dirty();
}
float CSGShape3D::get_snap() const {
return snap;
}
void CSGShape3D::_make_dirty(bool p_parent_removing) {
if ((p_parent_removing || is_root_shape()) && !dirty) {
callable_mp(this, &CSGShape3D::_update_shape).call_deferred(); // Must be deferred; otherwise, is_root_shape() will use the previous parent.
}
if (!is_root_shape()) {
parent_shape->_make_dirty();
} else if (!dirty) {
callable_mp(this, &CSGShape3D::_update_shape).call_deferred();
}
dirty = true;
}
enum ManifoldProperty {
MANIFOLD_PROPERTY_POSITION_X = 0,
MANIFOLD_PROPERTY_POSITION_Y,
MANIFOLD_PROPERTY_POSITION_Z,
MANIFOLD_PROPERTY_INVERT,
MANIFOLD_PROPERTY_SMOOTH_GROUP,
MANIFOLD_PROPERTY_UV_X_0,
MANIFOLD_PROPERTY_UV_Y_0,
MANIFOLD_PROPERTY_MAX
};
static void _unpack_manifold(
const manifold::Manifold &p_manifold,
const HashMap<int32_t, Ref<Material>> &p_mesh_materials,
CSGBrush *r_mesh_merge) {
manifold::MeshGL64 mesh = p_manifold.GetMeshGL64();
constexpr int32_t order[3] = { 0, 2, 1 };
for (size_t run_i = 0; run_i < mesh.runIndex.size() - 1; run_i++) {
uint32_t original_id = -1;
if (run_i < mesh.runOriginalID.size()) {
original_id = mesh.runOriginalID[run_i];
}
Ref<Material> material;
if (p_mesh_materials.has(original_id)) {
material = p_mesh_materials[original_id];
}
// Find or reserve a material ID in the brush.
int32_t material_id = r_mesh_merge->materials.find(material);
if (material_id == -1) {
material_id = r_mesh_merge->materials.size();
r_mesh_merge->materials.push_back(material);
}
size_t begin = mesh.runIndex[run_i];
size_t end = mesh.runIndex[run_i + 1];
for (size_t vert_i = begin; vert_i < end; vert_i += 3) {
CSGBrush::Face face;
face.material = material_id;
int32_t first_property_index = mesh.triVerts[vert_i + order[0]];
face.smooth = mesh.vertProperties[first_property_index * mesh.numProp + MANIFOLD_PROPERTY_SMOOTH_GROUP] > 0.5f;
face.invert = mesh.vertProperties[first_property_index * mesh.numProp + MANIFOLD_PROPERTY_INVERT] > 0.5f;
for (int32_t tri_order_i = 0; tri_order_i < 3; tri_order_i++) {
int32_t property_i = mesh.triVerts[vert_i + order[tri_order_i]];
ERR_FAIL_COND_MSG(property_i * mesh.numProp >= mesh.vertProperties.size(), "Invalid index into vertex properties");
face.vertices[tri_order_i] = Vector3(
mesh.vertProperties[property_i * mesh.numProp + MANIFOLD_PROPERTY_POSITION_X],
mesh.vertProperties[property_i * mesh.numProp + MANIFOLD_PROPERTY_POSITION_Y],
mesh.vertProperties[property_i * mesh.numProp + MANIFOLD_PROPERTY_POSITION_Z]);
face.uvs[tri_order_i] = Vector2(
mesh.vertProperties[property_i * mesh.numProp + MANIFOLD_PROPERTY_UV_X_0],
mesh.vertProperties[property_i * mesh.numProp + MANIFOLD_PROPERTY_UV_Y_0]);
}
r_mesh_merge->faces.push_back(face);
}
}
r_mesh_merge->_regen_face_aabbs();
}
static void _pack_manifold(
const CSGBrush *const p_mesh_merge,
manifold::Manifold &r_manifold,
HashMap<int32_t, Ref<Material>> &p_mesh_materials,
float p_snap) {
ERR_FAIL_NULL_MSG(p_mesh_merge, "p_mesh_merge is null");
HashMap<uint32_t, Vector<CSGBrush::Face>> faces_by_material;
for (int face_i = 0; face_i < p_mesh_merge->faces.size(); face_i++) {
const CSGBrush::Face &face = p_mesh_merge->faces[face_i];
faces_by_material[face.material].push_back(face);
}
manifold::MeshGL64 mesh;
mesh.tolerance = p_snap;
mesh.numProp = MANIFOLD_PROPERTY_MAX;
mesh.runOriginalID.reserve(faces_by_material.size());
mesh.runIndex.reserve(faces_by_material.size() + 1);
mesh.vertProperties.reserve(p_mesh_merge->faces.size() * 3 * MANIFOLD_PROPERTY_MAX);
// Make a run of triangles for each material.
for (const KeyValue<uint32_t, Vector<CSGBrush::Face>> &E : faces_by_material) {
const uint32_t material_id = E.key;
const Vector<CSGBrush::Face> &faces = E.value;
mesh.runIndex.push_back(mesh.triVerts.size());
// Associate the material with an ID.
uint32_t reserved_id = r_manifold.ReserveIDs(1);
mesh.runOriginalID.push_back(reserved_id);
Ref<Material> material;
if (material_id < p_mesh_merge->materials.size()) {
material = p_mesh_merge->materials[material_id];
}
p_mesh_materials.insert(reserved_id, material);
for (const CSGBrush::Face &face : faces) {
for (int32_t tri_order_i = 0; tri_order_i < 3; tri_order_i++) {
constexpr int32_t order[3] = { 0, 2, 1 };
int i = order[tri_order_i];
mesh.triVerts.push_back(mesh.vertProperties.size() / MANIFOLD_PROPERTY_MAX);
size_t begin = mesh.vertProperties.size();
mesh.vertProperties.resize(mesh.vertProperties.size() + MANIFOLD_PROPERTY_MAX);
// Add the vertex properties.
// Use CSGBrush constants rather than push_back for clarity.
double *vert = &mesh.vertProperties[begin];
vert[MANIFOLD_PROPERTY_POSITION_X] = face.vertices[i].x;
vert[MANIFOLD_PROPERTY_POSITION_Y] = face.vertices[i].y;
vert[MANIFOLD_PROPERTY_POSITION_Z] = face.vertices[i].z;
vert[MANIFOLD_PROPERTY_UV_X_0] = face.uvs[i].x;
vert[MANIFOLD_PROPERTY_UV_Y_0] = face.uvs[i].y;
vert[MANIFOLD_PROPERTY_SMOOTH_GROUP] = face.smooth ? 1.0f : 0.0f;
vert[MANIFOLD_PROPERTY_INVERT] = face.invert ? 1.0f : 0.0f;
}
}
}
// runIndex needs an explicit end value.
mesh.runIndex.push_back(mesh.triVerts.size());
ERR_FAIL_COND_MSG(mesh.vertProperties.size() % mesh.numProp != 0, "Invalid vertex properties size.");
mesh.Merge();
r_manifold = manifold::Manifold(mesh);
manifold::Manifold::Error err = r_manifold.Status();
if (err != manifold::Manifold::Error::NoError) {
print_error(String("Manifold creation from mesh failed:" + itos((int)err)));
}
}
struct ManifoldOperation {
manifold::Manifold manifold;
manifold::OpType operation;
static manifold::OpType convert_csg_op(CSGShape3D::Operation op) {
switch (op) {
case CSGShape3D::OPERATION_SUBTRACTION:
return manifold::OpType::Subtract;
case CSGShape3D::OPERATION_INTERSECTION:
return manifold::OpType::Intersect;
default:
return manifold::OpType::Add;
}
}
ManifoldOperation() :
operation(manifold::OpType::Add) {}
ManifoldOperation(const manifold::Manifold &m, manifold::OpType op) :
manifold(m), operation(op) {}
};
CSGBrush *CSGShape3D::_get_brush() {
if (!dirty) {
return brush;
}
if (brush) {
memdelete(brush);
}
brush = nullptr;
CSGBrush *n = _build_brush();
HashMap<int32_t, Ref<Material>> mesh_materials;
manifold::Manifold root_manifold;
_pack_manifold(n, root_manifold, mesh_materials, get_snap());
manifold::OpType current_op = ManifoldOperation::convert_csg_op(get_operation());
std::vector<manifold::Manifold> manifolds;
manifolds.push_back(root_manifold);
for (int i = 0; i < get_child_count(); i++) {
CSGShape3D *child = Object::cast_to<CSGShape3D>(get_child(i));
if (!child || !child->is_visible()) {
continue;
}
CSGBrush *child_brush = child->_get_brush();
if (!child_brush) {
continue;
}
CSGBrush transformed_brush;
transformed_brush.copy_from(*child_brush, child->get_transform());
manifold::Manifold child_manifold;
_pack_manifold(&transformed_brush, child_manifold, mesh_materials, get_snap());
manifold::OpType child_operation = ManifoldOperation::convert_csg_op(child->get_operation());
if (child_operation != current_op) {
manifold::Manifold result = manifold::Manifold::BatchBoolean(manifolds, current_op);
manifolds.clear();
manifolds.push_back(result);
current_op = child_operation;
}
manifolds.push_back(child_manifold);
}
if (!manifolds.empty()) {
manifold::Manifold manifold_result = manifold::Manifold::BatchBoolean(manifolds, current_op);
if (n) {
memdelete(n);
}
n = memnew(CSGBrush);
_unpack_manifold(manifold_result, mesh_materials, n);
}
AABB aabb;
if (n && !n->faces.is_empty()) {
aabb.position = n->faces[0].vertices[0];
for (const CSGBrush::Face &face : n->faces) {
for (int i = 0; i < 3; ++i) {
aabb.expand_to(face.vertices[i]);
}
}
}
node_aabb = aabb;
brush = n;
dirty = false;
return brush;
}
int CSGShape3D::mikktGetNumFaces(const SMikkTSpaceContext *pContext) {
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
return surface.vertices.size() / 3;
}
int CSGShape3D::mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace) {
// always 3
return 3;
}
void CSGShape3D::mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert) {
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
Vector3 v = surface.verticesw[iFace * 3 + iVert];
fvPosOut[0] = v.x;
fvPosOut[1] = v.y;
fvPosOut[2] = v.z;
}
void CSGShape3D::mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert) {
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
Vector3 n = surface.normalsw[iFace * 3 + iVert];
fvNormOut[0] = n.x;
fvNormOut[1] = n.y;
fvNormOut[2] = n.z;
}
void CSGShape3D::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert) {
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
Vector2 t = surface.uvsw[iFace * 3 + iVert];
fvTexcOut[0] = t.x;
fvTexcOut[1] = t.y;
}
void CSGShape3D::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT,
const tbool bIsOrientationPreserving, const int iFace, const int iVert) {
ShapeUpdateSurface &surface = *((ShapeUpdateSurface *)pContext->m_pUserData);
int i = iFace * 3 + iVert;
Vector3 normal = surface.normalsw[i];
Vector3 tangent = Vector3(fvTangent[0], fvTangent[1], fvTangent[2]);
Vector3 bitangent = Vector3(-fvBiTangent[0], -fvBiTangent[1], -fvBiTangent[2]); // for some reason these are reversed, something with the coordinate system in Godot
float d = bitangent.dot(normal.cross(tangent));
i *= 4;
surface.tansw[i++] = tangent.x;
surface.tansw[i++] = tangent.y;
surface.tansw[i++] = tangent.z;
surface.tansw[i++] = d < 0 ? -1 : 1;
}
void CSGShape3D::_update_shape() {
if (!is_root_shape()) {
return;
}
set_base(RID());
root_mesh.unref(); //byebye root mesh
CSGBrush *n = _get_brush();
ERR_FAIL_NULL_MSG(n, "Cannot get CSGBrush.");
OAHashMap<Vector3, Vector3> vec_map;
Vector<int> face_count;
face_count.resize(n->materials.size() + 1);
for (int i = 0; i < face_count.size(); i++) {
face_count.write[i] = 0;
}
for (int i = 0; i < n->faces.size(); i++) {
int mat = n->faces[i].material;
ERR_CONTINUE(mat < -1 || mat >= face_count.size());
int idx = mat == -1 ? face_count.size() - 1 : mat;
if (n->faces[i].smooth) {
Plane p(n->faces[i].vertices[0], n->faces[i].vertices[1], n->faces[i].vertices[2]);
for (int j = 0; j < 3; j++) {
Vector3 v = n->faces[i].vertices[j];
Vector3 add;
if (vec_map.lookup(v, add)) {
add += p.normal;
} else {
add = p.normal;
}
vec_map.set(v, add);
}
}
face_count.write[idx]++;
}
Vector<ShapeUpdateSurface> surfaces;
surfaces.resize(face_count.size());
//create arrays
for (int i = 0; i < surfaces.size(); i++) {
surfaces.write[i].vertices.resize(face_count[i] * 3);
surfaces.write[i].normals.resize(face_count[i] * 3);
surfaces.write[i].uvs.resize(face_count[i] * 3);
if (calculate_tangents) {
surfaces.write[i].tans.resize(face_count[i] * 3 * 4);
}
surfaces.write[i].last_added = 0;
if (i != surfaces.size() - 1) {
surfaces.write[i].material = n->materials[i];
}
surfaces.write[i].verticesw = surfaces.write[i].vertices.ptrw();
surfaces.write[i].normalsw = surfaces.write[i].normals.ptrw();
surfaces.write[i].uvsw = surfaces.write[i].uvs.ptrw();
if (calculate_tangents) {
surfaces.write[i].tansw = surfaces.write[i].tans.ptrw();
}
}
//fill arrays
{
for (int i = 0; i < n->faces.size(); i++) {
int order[3] = { 0, 1, 2 };
if (n->faces[i].invert) {
SWAP(order[1], order[2]);
}
int mat = n->faces[i].material;
ERR_CONTINUE(mat < -1 || mat >= face_count.size());
int idx = mat == -1 ? face_count.size() - 1 : mat;
int last = surfaces[idx].last_added;
Plane p(n->faces[i].vertices[0], n->faces[i].vertices[1], n->faces[i].vertices[2]);
for (int j = 0; j < 3; j++) {
Vector3 v = n->faces[i].vertices[j];
Vector3 normal = p.normal;
if (n->faces[i].smooth && vec_map.lookup(v, normal)) {
normal.normalize();
}
if (n->faces[i].invert) {
normal = -normal;
}
int k = last + order[j];
surfaces[idx].verticesw[k] = v;
surfaces[idx].uvsw[k] = n->faces[i].uvs[j];
surfaces[idx].normalsw[k] = normal;
if (calculate_tangents) {
// zero out our tangents for now
k *= 4;
surfaces[idx].tansw[k++] = 0.0;
surfaces[idx].tansw[k++] = 0.0;
surfaces[idx].tansw[k++] = 0.0;
surfaces[idx].tansw[k++] = 0.0;
}
}
surfaces.write[idx].last_added += 3;
}
}
root_mesh.instantiate();
//create surfaces
for (int i = 0; i < surfaces.size(); i++) {
// calculate tangents for this surface
bool have_tangents = calculate_tangents;
if (have_tangents) {
SMikkTSpaceInterface mkif;
mkif.m_getNormal = mikktGetNormal;
mkif.m_getNumFaces = mikktGetNumFaces;
mkif.m_getNumVerticesOfFace = mikktGetNumVerticesOfFace;
mkif.m_getPosition = mikktGetPosition;
mkif.m_getTexCoord = mikktGetTexCoord;
mkif.m_setTSpace = mikktSetTSpaceDefault;
mkif.m_setTSpaceBasic = nullptr;
SMikkTSpaceContext msc;
msc.m_pInterface = &mkif;
msc.m_pUserData = &surfaces.write[i];
have_tangents = genTangSpaceDefault(&msc);
}
if (surfaces[i].last_added == 0) {
continue;
}
// and convert to surface array
Array array;
array.resize(Mesh::ARRAY_MAX);
array[Mesh::ARRAY_VERTEX] = surfaces[i].vertices;
array[Mesh::ARRAY_NORMAL] = surfaces[i].normals;
array[Mesh::ARRAY_TEX_UV] = surfaces[i].uvs;
if (have_tangents) {
array[Mesh::ARRAY_TANGENT] = surfaces[i].tans;
}
int idx = root_mesh->get_surface_count();
root_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, array);
root_mesh->surface_set_material(idx, surfaces[i].material);
}
set_base(root_mesh->get_rid());
_update_collision_faces();
}
Vector<Vector3> CSGShape3D::_get_brush_collision_faces() {
Vector<Vector3> collision_faces;
CSGBrush *n = _get_brush();
ERR_FAIL_NULL_V_MSG(n, collision_faces, "Cannot get CSGBrush.");
collision_faces.resize(n->faces.size() * 3);
Vector3 *collision_faces_ptrw = collision_faces.ptrw();
for (int i = 0; i < n->faces.size(); i++) {
int order[3] = { 0, 1, 2 };
if (n->faces[i].invert) {
SWAP(order[1], order[2]);
}
collision_faces_ptrw[i * 3 + 0] = n->faces[i].vertices[order[0]];
collision_faces_ptrw[i * 3 + 1] = n->faces[i].vertices[order[1]];
collision_faces_ptrw[i * 3 + 2] = n->faces[i].vertices[order[2]];
}
return collision_faces;
}
void CSGShape3D::_update_collision_faces() {
if (use_collision && is_root_shape() && root_collision_shape.is_valid()) {
root_collision_shape->set_faces(_get_brush_collision_faces());
if (_is_debug_collision_shape_visible()) {
_update_debug_collision_shape();
}
}
}
Ref<ArrayMesh> CSGShape3D::bake_static_mesh() {
Ref<ArrayMesh> baked_mesh;
if (is_root_shape() && root_mesh.is_valid()) {
baked_mesh = root_mesh;
}
return baked_mesh;
}
Ref<ConcavePolygonShape3D> CSGShape3D::bake_collision_shape() {
Ref<ConcavePolygonShape3D> baked_collision_shape;
if (is_root_shape() && root_collision_shape.is_valid()) {
baked_collision_shape.instantiate();
baked_collision_shape->set_faces(root_collision_shape->get_faces());
} else if (is_root_shape()) {
baked_collision_shape.instantiate();
baked_collision_shape->set_faces(_get_brush_collision_faces());
}
return baked_collision_shape;
}
bool CSGShape3D::_is_debug_collision_shape_visible() {
return !Engine::get_singleton()->is_editor_hint() && is_inside_tree() && get_tree()->is_debugging_collisions_hint();
}
void CSGShape3D::_update_debug_collision_shape() {
if (!use_collision || !is_root_shape() || !root_collision_shape.is_valid() || !_is_debug_collision_shape_visible()) {
return;
}
ERR_FAIL_NULL(RenderingServer::get_singleton());
if (root_collision_debug_instance.is_null()) {
root_collision_debug_instance = RS::get_singleton()->instance_create();
}
Ref<Mesh> debug_mesh = root_collision_shape->get_debug_mesh();
RS::get_singleton()->instance_set_scenario(root_collision_debug_instance, get_world_3d()->get_scenario());
RS::get_singleton()->instance_set_base(root_collision_debug_instance, debug_mesh->get_rid());
RS::get_singleton()->instance_set_transform(root_collision_debug_instance, get_global_transform());
}
void CSGShape3D::_clear_debug_collision_shape() {
if (root_collision_debug_instance.is_valid()) {
RS::get_singleton()->free(root_collision_debug_instance);
root_collision_debug_instance = RID();
}
}
void CSGShape3D::_on_transform_changed() {
if (root_collision_debug_instance.is_valid() && !debug_shape_old_transform.is_equal_approx(get_global_transform())) {
debug_shape_old_transform = get_global_transform();
RS::get_singleton()->instance_set_transform(root_collision_debug_instance, debug_shape_old_transform);
}
}
AABB CSGShape3D::get_aabb() const {
return node_aabb;
}
Vector<Vector3> CSGShape3D::get_brush_faces() {
ERR_FAIL_COND_V(!is_inside_tree(), Vector<Vector3>());
CSGBrush *b = _get_brush();
if (!b) {
return Vector<Vector3>();
}
Vector<Vector3> faces;
int fc = b->faces.size();
faces.resize(fc * 3);
{
Vector3 *w = faces.ptrw();
for (int i = 0; i < fc; i++) {
w[i * 3 + 0] = b->faces[i].vertices[0];
w[i * 3 + 1] = b->faces[i].vertices[1];
w[i * 3 + 2] = b->faces[i].vertices[2];
}
}
return faces;
}
void CSGShape3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_PARENTED: {
Node *parentn = get_parent();
if (parentn) {
parent_shape = Object::cast_to<CSGShape3D>(parentn);
if (parent_shape) {
set_base(RID());
root_mesh.unref();
}
}
if (!brush || parent_shape) {
// Update this node if uninitialized, or both this node and its new parent if it gets added to another CSG shape
_make_dirty();
}
last_visible = is_visible();
} break;
case NOTIFICATION_UNPARENTED: {
if (!is_root_shape()) {
// Update this node and its previous parent only if it's currently being removed from another CSG shape
_make_dirty(true); // Must be forced since is_root_shape() uses the previous parent
}
parent_shape = nullptr;
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
if (!is_root_shape() && last_visible != is_visible()) {
// Update this node's parent only if its own visibility has changed, not the visibility of parent nodes
parent_shape->_make_dirty();
}
last_visible = is_visible();
} break;
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
if (!is_root_shape()) {
// Update this node's parent only if its own transformation has changed, not the transformation of parent nodes
parent_shape->_make_dirty();
}
} break;
case NOTIFICATION_ENTER_TREE: {
if (use_collision && is_root_shape()) {
root_collision_shape.instantiate();
root_collision_instance = PhysicsServer3D::get_singleton()->body_create();
PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC);
PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
PhysicsServer3D::get_singleton()->body_add_shape(root_collision_instance, root_collision_shape->get_rid());
PhysicsServer3D::get_singleton()->body_set_space(root_collision_instance, get_world_3d()->get_space());
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(root_collision_instance, get_instance_id());
set_collision_layer(collision_layer);
set_collision_mask(collision_mask);
set_collision_priority(collision_priority);
debug_shape_old_transform = get_global_transform();
_make_dirty();
}
} break;
case NOTIFICATION_EXIT_TREE: {
if (use_collision && is_root_shape() && root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->free(root_collision_instance);
root_collision_instance = RID();
root_collision_shape.unref();
_clear_debug_collision_shape();
}
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (use_collision && is_root_shape() && root_collision_instance.is_valid()) {
PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
}
_on_transform_changed();
} break;
}
}
void CSGShape3D::set_operation(Operation p_operation) {
operation = p_operation;
_make_dirty();
update_gizmos();
}
CSGShape3D::Operation CSGShape3D::get_operation() const {
return operation;
}
void CSGShape3D::set_calculate_tangents(bool p_calculate_tangents) {
calculate_tangents = p_calculate_tangents;
_make_dirty();
}
bool CSGShape3D::is_calculating_tangents() const {
return calculate_tangents;
}
void CSGShape3D::_validate_property(PropertyInfo &p_property) const {
bool is_collision_prefixed = p_property.name.begins_with("collision_");
if ((is_collision_prefixed || p_property.name.begins_with("use_collision")) && is_inside_tree() && !is_root_shape()) {
//hide collision if not root
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
} else if (is_collision_prefixed && !bool(get("use_collision"))) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
Array CSGShape3D::get_meshes() const {
if (root_mesh.is_valid()) {
Array arr;
arr.resize(2);
arr[0] = Transform3D();
arr[1] = root_mesh;
return arr;
}
return Array();
}
void CSGShape3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("_update_shape"), &CSGShape3D::_update_shape);
ClassDB::bind_method(D_METHOD("is_root_shape"), &CSGShape3D::is_root_shape);
ClassDB::bind_method(D_METHOD("set_operation", "operation"), &CSGShape3D::set_operation);
ClassDB::bind_method(D_METHOD("get_operation"), &CSGShape3D::get_operation);
ClassDB::bind_method(D_METHOD("set_snap", "snap"), &CSGShape3D::set_snap);
ClassDB::bind_method(D_METHOD("get_snap"), &CSGShape3D::get_snap);
ClassDB::bind_method(D_METHOD("set_use_collision", "operation"), &CSGShape3D::set_use_collision);
ClassDB::bind_method(D_METHOD("is_using_collision"), &CSGShape3D::is_using_collision);
ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &CSGShape3D::set_collision_layer);
ClassDB::bind_method(D_METHOD("get_collision_layer"), &CSGShape3D::get_collision_layer);
ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &CSGShape3D::set_collision_mask);
ClassDB::bind_method(D_METHOD("get_collision_mask"), &CSGShape3D::get_collision_mask);
ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &CSGShape3D::set_collision_mask_value);
ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &CSGShape3D::get_collision_mask_value);
ClassDB::bind_method(D_METHOD("set_collision_layer_value", "layer_number", "value"), &CSGShape3D::set_collision_layer_value);
ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &CSGShape3D::get_collision_layer_value);
ClassDB::bind_method(D_METHOD("set_collision_priority", "priority"), &CSGShape3D::set_collision_priority);
ClassDB::bind_method(D_METHOD("get_collision_priority"), &CSGShape3D::get_collision_priority);
ClassDB::bind_method(D_METHOD("set_calculate_tangents", "enabled"), &CSGShape3D::set_calculate_tangents);
ClassDB::bind_method(D_METHOD("is_calculating_tangents"), &CSGShape3D::is_calculating_tangents);
ClassDB::bind_method(D_METHOD("get_meshes"), &CSGShape3D::get_meshes);
ClassDB::bind_method(D_METHOD("bake_static_mesh"), &CSGShape3D::bake_static_mesh);
ClassDB::bind_method(D_METHOD("bake_collision_shape"), &CSGShape3D::bake_collision_shape);
ADD_PROPERTY(PropertyInfo(Variant::INT, "operation", PROPERTY_HINT_ENUM, "Union,Intersection,Subtraction"), "set_operation", "get_operation");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "snap", PROPERTY_HINT_RANGE, "0.000001,1,0.000001,suffix:m"), "set_snap", "get_snap");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "calculate_tangents"), "set_calculate_tangents", "is_calculating_tangents");
ADD_GROUP("Collision", "collision_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_collision"), "set_use_collision", "is_using_collision");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_priority"), "set_collision_priority", "get_collision_priority");
BIND_ENUM_CONSTANT(OPERATION_UNION);
BIND_ENUM_CONSTANT(OPERATION_INTERSECTION);
BIND_ENUM_CONSTANT(OPERATION_SUBTRACTION);
}
CSGShape3D::CSGShape3D() {
set_notify_local_transform(true);
}
CSGShape3D::~CSGShape3D() {
if (brush) {
memdelete(brush);
brush = nullptr;
}
}
//////////////////////////////////
CSGBrush *CSGCombiner3D::_build_brush() {
return memnew(CSGBrush); //does not build anything
}
CSGCombiner3D::CSGCombiner3D() {
}
/////////////////////
CSGBrush *CSGPrimitive3D::_create_brush_from_arrays(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uv, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials) {
CSGBrush *new_brush = memnew(CSGBrush);
Vector<bool> invert;
invert.resize(p_vertices.size() / 3);
{
int ic = invert.size();
bool *w = invert.ptrw();
for (int i = 0; i < ic; i++) {
w[i] = flip_faces;
}
}
new_brush->build_from_faces(p_vertices, p_uv, p_smooth, p_materials, invert);
return new_brush;
}
void CSGPrimitive3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_flip_faces", "flip_faces"), &CSGPrimitive3D::set_flip_faces);
ClassDB::bind_method(D_METHOD("get_flip_faces"), &CSGPrimitive3D::get_flip_faces);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_faces"), "set_flip_faces", "get_flip_faces");
}
void CSGPrimitive3D::set_flip_faces(bool p_invert) {
if (flip_faces == p_invert) {
return;
}
flip_faces = p_invert;
_make_dirty();
}
bool CSGPrimitive3D::get_flip_faces() {
return flip_faces;
}
CSGPrimitive3D::CSGPrimitive3D() {
flip_faces = false;
}
/////////////////////
CSGBrush *CSGMesh3D::_build_brush() {
if (!mesh.is_valid()) {
return memnew(CSGBrush);
}
Vector<Vector3> vertices;
Vector<bool> smooth;
Vector<Ref<Material>> materials;
Vector<Vector2> uvs;
Ref<Material> base_material = get_material();
for (int i = 0; i < mesh->get_surface_count(); i++) {
if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue;
}
Array arrays = mesh->surface_get_arrays(i);
if (arrays.size() == 0) {
_make_dirty();
ERR_FAIL_COND_V(arrays.is_empty(), memnew(CSGBrush));
}
Vector<Vector3> avertices = arrays[Mesh::ARRAY_VERTEX];
if (avertices.size() == 0) {
continue;
}
const Vector3 *vr = avertices.ptr();
Vector<Vector3> anormals = arrays[Mesh::ARRAY_NORMAL];
const Vector3 *nr = nullptr;
if (anormals.size()) {
nr = anormals.ptr();
}
Vector<Vector2> auvs = arrays[Mesh::ARRAY_TEX_UV];
const Vector2 *uvr = nullptr;
if (auvs.size()) {
uvr = auvs.ptr();
}
Ref<Material> mat;
if (base_material.is_valid()) {
mat = base_material;
} else {
mat = mesh->surface_get_material(i);
}
Vector<int> aindices = arrays[Mesh::ARRAY_INDEX];
if (aindices.size()) {
int as = vertices.size();
int is = aindices.size();