generated from nathanfranke/gdextension
-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathterrain_3d.cpp
1227 lines (1104 loc) · 48.5 KB
/
terrain_3d.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
// Copyright © 2025 Cory Petkovsek, Roope Palmroos, and Contributors.
#include <godot_cpp/classes/compositor.hpp>
#include <godot_cpp/classes/editor_interface.hpp>
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/environment.hpp>
#include <godot_cpp/classes/height_map_shape3d.hpp>
#include <godot_cpp/classes/label3d.hpp>
#include <godot_cpp/classes/os.hpp>
#include <godot_cpp/classes/project_settings.hpp>
#include <godot_cpp/classes/quad_mesh.hpp>
#include <godot_cpp/classes/rendering_server.hpp>
#include <godot_cpp/classes/shader_material.hpp>
#include <godot_cpp/classes/surface_tool.hpp>
#include <godot_cpp/classes/time.hpp>
#include <godot_cpp/classes/viewport.hpp>
#include <godot_cpp/classes/viewport_texture.hpp>
#include <godot_cpp/classes/world3d.hpp>
#include "logger.h"
#include "terrain_3d.h"
#include "terrain_3d_util.h"
///////////////////////////
// Private Functions
///////////////////////////
// Initialize static member variable
int Terrain3D::debug_level{ ERROR };
void Terrain3D::_initialize() {
LOG(INFO, "Instantiating main subsystems");
// Make blank objects if needed
if (!_data) {
LOG(DEBUG, "Creating blank data object");
_data = memnew(Terrain3DData);
}
if (_material.is_null()) {
LOG(DEBUG, "Creating blank material");
_material.instantiate();
}
if (_assets.is_null()) {
LOG(DEBUG, "Creating blank texture list");
_assets.instantiate();
}
if (!_collision) {
LOG(DEBUG, "Creating collision manager");
_collision = memnew(Terrain3DCollision);
}
if (!_instancer) {
LOG(DEBUG, "Creating instancer");
_instancer = memnew(Terrain3DInstancer);
}
if (!_mesher) {
LOG(DEBUG, "Creating mesher");
_mesher = new Terrain3DMesher();
}
// Connect signals
// Any region was changed, update region labels
if (!_data->is_connected("region_map_changed", callable_mp(this, &Terrain3D::update_region_labels))) {
LOG(DEBUG, "Connecting _data::region_map_changed signal to set_show_region_locations()");
_data->connect("region_map_changed", callable_mp(this, &Terrain3D::update_region_labels));
}
// Any region was changed, regenerate collision if enabled
if (!_data->is_connected("region_map_changed", callable_mp(_collision, &Terrain3DCollision::build))) {
LOG(DEBUG, "Connecting _data::region_map_changed signal to build()");
_data->connect("region_map_changed", callable_mp(_collision, &Terrain3DCollision::build));
}
// Any map was regenerated or regions changed, update material
if (!_data->is_connected("maps_changed", callable_mp(_material.ptr(), &Terrain3DMaterial::_update_maps))) {
LOG(DEBUG, "Connecting _data::maps_changed signal to _material->_update_maps()");
_data->connect("maps_changed", callable_mp(_material.ptr(), &Terrain3DMaterial::_update_maps));
}
// Height map was regenerated, update aabbs
if (!_data->is_connected("height_maps_changed", callable_mp(this, &Terrain3D::_update_mesher_aabbs))) {
LOG(DEBUG, "Connecting _data::height_maps_changed signal to update_aabbs()");
_data->connect("height_maps_changed", callable_mp(this, &Terrain3D::_update_mesher_aabbs));
}
// Texture assets changed, update material
if (!_assets->is_connected("textures_changed", callable_mp(_material.ptr(), &Terrain3DMaterial::_update_texture_arrays))) {
LOG(DEBUG, "Connecting _assets.textures_changed to _material->_update_texture_arrays()");
_assets->connect("textures_changed", callable_mp(_material.ptr(), &Terrain3DMaterial::_update_texture_arrays));
}
// MeshAssets changed, update instancer
if (!_assets->is_connected("meshes_changed", callable_mp(_instancer, &Terrain3DInstancer::_update_mmis).bind(V2I_MAX, -1))) {
LOG(DEBUG, "Connecting _assets.meshes_changed to _instancer->_update_mmis()");
_assets->connect("meshes_changed", callable_mp(_instancer, &Terrain3DInstancer::_update_mmis).bind(V2I_MAX, -1));
}
// Initialize the system
if (!_initialized && _is_inside_world && is_inside_tree()) {
LOG(INFO, "Initializing main subsystems");
_data->initialize(this);
_material->initialize(this);
_assets->initialize(this);
_collision->initialize(this);
_instancer->initialize(this);
_mesher->initialize(this);
_initialized = true;
}
update_configuration_warnings();
}
/**
* This is a proxy for _process(delta) called by _notification() due to
* https://github.com/godotengine/godot-cpp/issues/1022
*/
void Terrain3D::__physics_process(const double p_delta) {
if (!_initialized)
return;
// If the game/editor camera is not set, find it
if (!is_instance_valid(_camera_instance_id, _camera)) {
LOG(DEBUG, "Camera is null, getting the current one");
_grab_camera();
}
if (is_instance_valid(_camera_instance_id) && _camera->is_inside_tree()) {
Vector3 cam_pos = _camera->get_global_position();
Vector2 cam_pos_2d = Vector2(cam_pos.x, cam_pos.z);
RS->material_set_param(_material->get_material_rid(), "_camera_pos", cam_pos);
if (_camera_last_position.distance_to(cam_pos_2d) > 0.2f) {
if (_mesher) {
_mesher->snap(cam_pos);
}
_snapped_position = (cam_pos / _vertex_spacing).floor() * _vertex_spacing;
_camera_last_position = cam_pos_2d;
if (_collision && _collision->is_dynamic_mode()) {
_collision->update();
}
}
if (_data) {
_data->_process_streaming();
}
if (_enable_streaming && _data) {
static double stream_timer = 0.0;
stream_timer += p_delta;
if (stream_timer >= 0.1) {
stream_timer = 0.0;
_data->update_streaming(cam_pos);
}
}
}
}
/**
* If running in the editor, grab the first editor viewport camera.
* The edited_scene_root is excluded in case the user already has a Camera3D in their scene.
*/
void Terrain3D::_grab_camera() {
if (IS_EDITOR) {
_camera = EditorInterface::get_singleton()->get_editor_viewport_3d(0)->get_camera_3d();
LOG(DEBUG, "Grabbing the first editor viewport camera: ", _camera);
} else {
_camera = get_viewport()->get_camera_3d();
LOG(DEBUG, "Grabbing the in-game viewport camera: ", _camera);
}
if (_camera) {
_camera_instance_id = _camera->get_instance_id();
} else {
_camera_instance_id = 0;
set_physics_process(false); // disable snapping
LOG(ERROR, "Cannot find the active camera. Set it manually with Terrain3D.set_camera(). Stopping _physics_process()");
}
}
void Terrain3D::_build_containers() {
_label_parent = memnew(Node3D);
_label_parent->set_name("Labels");
add_child(_label_parent, true);
_mmi_parent = memnew(Node3D);
_mmi_parent->set_name("MMI");
add_child(_mmi_parent, true);
}
void Terrain3D::_destroy_containers() {
memdelete_safely(_label_parent);
memdelete_safely(_mmi_parent);
}
void Terrain3D::_destroy_labels() {
Array labels = _label_parent->get_children();
LOG(DEBUG, "Destroying ", labels.size(), " region labels");
for (int i = 0; i < labels.size(); i++) {
Node *label = cast_to<Node>(labels[i]);
memdelete_safely(label);
}
}
void Terrain3D::_destroy_instancer() {
LOG(INFO, "Destroying Instancer");
memdelete_safely(_instancer);
}
void Terrain3D::_destroy_collision(const bool p_final) {
LOG(INFO, "Destroying Collision");
if (_collision) {
_collision->destroy();
}
if (p_final) {
memdelete_safely(_collision);
}
}
void Terrain3D::_destroy_mesher(const bool p_final) {
LOG(INFO, "Destroying GeoMesh");
if (_mesher) {
_mesher->destroy();
if (p_final) {
delete _mesher;
_mesher = nullptr;
}
}
}
void Terrain3D::_setup_mouse_picking() {
if (!is_inside_tree()) {
LOG(ERROR, "Not inside the tree, skipping mouse setup");
return;
}
LOG(INFO, "Setting up mouse picker and get_intersection viewport, camera & screen quad");
_mouse_vp = memnew(SubViewport);
_mouse_vp->set_name("MouseViewport");
add_child(_mouse_vp, true);
_mouse_vp->set_size(Vector2i(2, 2));
_mouse_vp->set_update_mode(SubViewport::UPDATE_ONCE);
_mouse_vp->set_handle_input_locally(false);
_mouse_vp->set_canvas_cull_mask(0);
_mouse_vp->set_use_hdr_2d(true);
_mouse_vp->set_default_canvas_item_texture_filter(Viewport::DEFAULT_CANVAS_ITEM_TEXTURE_FILTER_NEAREST);
_mouse_vp->set_positional_shadow_atlas_size(0);
_mouse_vp->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
_mouse_vp->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
_mouse_vp->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
_mouse_vp->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
_mouse_cam = memnew(Camera3D);
_mouse_cam->set_name("MouseCamera");
_mouse_vp->add_child(_mouse_cam, true);
Ref<Environment> env;
env.instantiate();
env->set_tonemapper(Environment::TONE_MAPPER_LINEAR);
_mouse_cam->set_environment(env);
Ref<Compositor> comp;
comp.instantiate();
_mouse_cam->set_compositor(comp);
_mouse_cam->set_projection(Camera3D::PROJECTION_ORTHOGONAL);
_mouse_cam->set_size(0.1f);
_mouse_cam->set_far(100000.f);
_mouse_quad = memnew(MeshInstance3D);
_mouse_quad->set_name("MouseQuad");
_mouse_cam->add_child(_mouse_quad, true);
Ref<QuadMesh> quad;
quad.instantiate();
quad->set_size(Vector2(0.1f, 0.1f));
_mouse_quad->set_mesh(quad);
String shader_code = String(
#include "shaders/gpu_depth.glsl"
);
Ref<Shader> shader;
shader.instantiate();
shader->set_code(shader_code);
Ref<ShaderMaterial> shader_material;
shader_material.instantiate();
shader_material->set_shader(shader);
_mouse_quad->set_surface_override_material(0, shader_material);
_mouse_quad->set_position(Vector3(0.f, 0.f, -0.5f));
// Set terrain, terrain shader, mouse camera, and screen quad to mouse layer
set_mouse_layer(_mouse_layer);
}
void Terrain3D::_destroy_mouse_picking() {
LOG(DEBUG, "Freeing mouse_quad");
memdelete_safely(_mouse_quad);
LOG(DEBUG, "Freeing mouse_cam");
memdelete_safely(_mouse_cam);
LOG(DEBUG, "Freeing mouse_vp");
memdelete_safely(_mouse_vp);
}
void Terrain3D::_generate_triangles(PackedVector3Array &p_vertices, PackedVector2Array *p_uvs, const int32_t p_lod,
const Terrain3DData::HeightFilter p_filter, const bool p_require_nav, const AABB &p_global_aabb) const {
ERR_FAIL_COND(_data == nullptr);
int32_t step = 1 << CLAMP(p_lod, 0, 8);
// Bake whole mesh, e.g. bake_mesh and painted navigation
if (!p_global_aabb.has_volume()) {
int32_t region_size = (int32_t)_region_size;
TypedArray<Vector2i> region_locations = _data->get_region_locations();
for (int r = 0; r < region_locations.size(); ++r) {
Vector2i region_loc = (Vector2i)region_locations[r] * region_size;
for (int32_t z = region_loc.y; z < region_loc.y + region_size; z += step) {
for (int32_t x = region_loc.x; x < region_loc.x + region_size; x += step) {
_generate_triangle_pair(p_vertices, p_uvs, p_lod, p_filter, p_require_nav, x, z);
}
}
}
} else {
// Bake within an AABB, e.g. runtime navigation baker
int32_t z_start = (int32_t)Math::ceil(p_global_aabb.position.z / _vertex_spacing);
int32_t z_end = (int32_t)Math::floor(p_global_aabb.get_end().z / _vertex_spacing) + 1;
int32_t x_start = (int32_t)Math::ceil(p_global_aabb.position.x / _vertex_spacing);
int32_t x_end = (int32_t)Math::floor(p_global_aabb.get_end().x / _vertex_spacing) + 1;
for (int32_t z = z_start; z < z_end; ++z) {
for (int32_t x = x_start; x < x_end; ++x) {
real_t height = _data->get_height(Vector3(x, 0.f, z));
if (height >= p_global_aabb.position.y && height <= p_global_aabb.get_end().y) {
_generate_triangle_pair(p_vertices, p_uvs, p_lod, p_filter, p_require_nav, x, z);
}
}
}
}
}
// Generates two triangles: Top 124, Bottom 143
// 1 __ 2
// |\ |
// | \|
// 3 -- 4
// p_vertices is assumed to exist and the destination for data
// p_uvs might not exist, so a pointer is fine
// p_require_nav is false for the runtime baker, which ignores navigation
void Terrain3D::_generate_triangle_pair(PackedVector3Array &p_vertices, PackedVector2Array *p_uvs,
const int32_t p_lod, const Terrain3DData::HeightFilter p_filter, const bool p_require_nav,
const int32_t x, const int32_t z) const {
int32_t step = 1 << CLAMP(p_lod, 0, 8);
Vector3 xz = Vector3(x, 0.0f, z) * _vertex_spacing;
Vector3 xsz = Vector3(x + step, 0.0f, z) * _vertex_spacing;
Vector3 xzs = Vector3(x, 0.0f, z + step) * _vertex_spacing;
Vector3 xszs = Vector3(x + step, 0.0f, z + step) * _vertex_spacing;
Vector3 v1 = _data->get_mesh_vertex(p_lod, p_filter, xz);
bool nan1 = std::isnan(v1.y);
if (nan1) {
return;
}
Vector3 v2 = _data->get_mesh_vertex(p_lod, p_filter, xsz);
Vector3 v3 = _data->get_mesh_vertex(p_lod, p_filter, xzs);
Vector3 v4 = _data->get_mesh_vertex(p_lod, p_filter, xszs);
bool nan2 = std::isnan(v2.y);
bool nan3 = std::isnan(v3.y);
bool nan4 = std::isnan(v4.y);
// If on the region edge, duplicate the edge pixels
// Check #2 upper right
if (nan2) {
v2.y = v1.y;
}
// Check #3 lower left
if (nan3) {
v3.y = v1.y;
}
// Check #4 lower right
if (nan4) {
if (!nan2) {
v4.y = v2.y;
} else if (!nan3) {
v4.y = v3.y;
} else {
v4.y = v1.y;
}
}
uint32_t ctrl1 = _data->get_control(xz);
uint32_t ctrl2 = _data->get_control(xsz);
uint32_t ctrl3 = _data->get_control(xzs);
uint32_t ctrl4 = _data->get_control(xszs);
// Holes are only where the control map is valid and the bit is set
bool hole1 = ctrl1 != UINT32_MAX && is_hole(ctrl1);
bool hole2 = ctrl2 != UINT32_MAX && is_hole(ctrl2);
bool hole3 = ctrl3 != UINT32_MAX && is_hole(ctrl3);
bool hole4 = ctrl4 != UINT32_MAX && is_hole(ctrl4);
// Navigation is where the control map is valid and the bit is set, or it's the region edge and nav1 is set
bool nav1 = ctrl1 != UINT32_MAX && is_nav(ctrl1);
bool nav2 = ctrl2 != UINT32_MAX && is_nav(ctrl2) || nan2 && nav1;
bool nav3 = ctrl3 != UINT32_MAX && is_nav(ctrl3) || nan3 && nav1;
bool nav4 = ctrl4 != UINT32_MAX && is_nav(ctrl4) || nan4 && nav1;
//Bottom 143 triangle
if (!(hole1 || hole4 || hole3) && (!p_require_nav || (nav1 && nav4 && nav3))) {
p_vertices.push_back(v1);
p_vertices.push_back(v4);
p_vertices.push_back(v3);
if (p_uvs) {
p_uvs->push_back(Vector2(v1.x, v1.z));
p_uvs->push_back(Vector2(v4.x, v4.z));
p_uvs->push_back(Vector2(v3.x, v3.z));
}
}
// Top 124 triangle
if (!(hole1 || hole2 || hole4) && (!p_require_nav || (nav1 && nav2 && nav4))) {
p_vertices.push_back(v1);
p_vertices.push_back(v2);
p_vertices.push_back(v4);
if (p_uvs) {
p_uvs->push_back(Vector2(v1.x, v1.z));
p_uvs->push_back(Vector2(v2.x, v2.z));
p_uvs->push_back(Vector2(v4.x, v4.z));
}
}
}
///////////////////////////
// Public Functions
///////////////////////////
Terrain3D::Terrain3D() {
// Process the command line
PackedStringArray args = OS::get_singleton()->get_cmdline_args();
for (int i = args.size() - 1; i >= 0; i--) {
String arg = args[i];
if (arg.begins_with("--terrain3d-debug=")) {
String value = arg.rsplit("=")[1];
if (value == "ERROR") {
set_debug_level(ERROR);
} else if (value == "INFO") {
set_debug_level(INFO);
} else if (value == "DEBUG") {
set_debug_level(DEBUG);
} else if (value == "EXTREME") {
set_debug_level(EXTREME);
}
}
}
}
void Terrain3D::set_debug_level(const int p_level) {
LOG(INFO, "Setting debug level: ", p_level);
debug_level = CLAMP(p_level, 0, EXTREME);
}
void Terrain3D::set_data_directory(String p_dir) {
LOG(INFO, "Setting data directory to ", p_dir);
if (_data_directory != p_dir) {
if (_data_directory.is_empty() && Util::get_files(p_dir, "terrain3d*.res").size() == 0) {
// If _data_directory was empty and now specified, and has no data
// assume we want to retain the current data
_data_directory = p_dir;
} else {
// Else clear data and if not null, load
_initialized = false;
_destroy_labels();
_destroy_collision();
_destroy_instancer();
memdelete_safely(_data);
_data_directory = p_dir;
_initialize();
}
}
update_configuration_warnings();
}
void Terrain3D::set_material(const Ref<Terrain3DMaterial> &p_material) {
if (_material != p_material) {
_initialized = false;
LOG(INFO, "Setting material");
_material = p_material;
_initialize();
emit_signal("material_changed");
}
}
void Terrain3D::set_assets(const Ref<Terrain3DAssets> &p_assets) {
if (_assets != p_assets) {
_initialized = false;
LOG(INFO, "Setting asset list");
_assets = p_assets;
_initialize();
emit_signal("assets_changed");
}
}
void Terrain3D::set_editor(Terrain3DEditor *p_editor) {
_editor = p_editor;
if (_material.is_valid()) {
_material->update();
}
LOG(DEBUG, "Received Terrain3DEditor: ", p_editor);
}
void Terrain3D::set_plugin(EditorPlugin *p_plugin) {
_plugin = p_plugin;
LOG(DEBUG, "Received editor plugin: ", p_plugin);
}
void Terrain3D::set_camera(Camera3D *p_camera) {
if (_camera != p_camera) {
_camera = p_camera;
if (!p_camera) {
LOG(DEBUG, "Received null camera. Calling _grab_camera()");
_grab_camera();
} else {
_camera = p_camera;
_camera_instance_id = _camera->get_instance_id();
LOG(DEBUG, "Setting camera: ", _camera);
_initialize();
set_physics_process(true); // enable snapping
}
}
}
void Terrain3D::set_region_size(const RegionSize p_size) {
LOG(INFO, "Setting region size: ", p_size);
ERR_FAIL_COND(p_size < SIZE_64);
ERR_FAIL_COND(p_size > SIZE_2048);
_region_size = p_size;
if (_data) {
_data->_region_size = _region_size;
_data->_region_sizev = Vector2i(_region_size, _region_size);
}
if (_material.is_valid()) {
_material->_update_maps();
}
}
void Terrain3D::set_save_16_bit(const bool p_enabled) {
LOG(INFO, p_enabled);
_save_16_bit = p_enabled;
}
void Terrain3D::set_label_distance(const real_t p_distance) {
real_t distance = CLAMP(p_distance, 0.f, 100000.f);
LOG(INFO, "Setting region label distance: ", distance);
if (_label_distance != distance) {
_label_distance = distance;
update_region_labels();
}
}
void Terrain3D::set_label_size(const int p_size) {
int size = CLAMP(p_size, 24, 128);
LOG(INFO, "Setting region label size: ", size);
if (_label_size != size) {
_label_size = size;
update_region_labels();
}
}
void Terrain3D::update_region_labels() {
_destroy_labels();
if (_label_distance > 0.f && _data) {
Array region_locations = _data->get_region_locations();
LOG(DEBUG, "Creating ", region_locations.size(), " region labels");
for (int i = 0; i < region_locations.size(); i++) {
Label3D *label = memnew(Label3D);
String text = region_locations[i];
label->set_name("Label3D" + text.replace(" ", ""));
label->set_pixel_size(.001f);
label->set_billboard_mode(BaseMaterial3D::BILLBOARD_ENABLED);
label->set_draw_flag(Label3D::FLAG_DOUBLE_SIDED, true);
label->set_draw_flag(Label3D::FLAG_DISABLE_DEPTH_TEST, true);
label->set_draw_flag(Label3D::FLAG_FIXED_SIZE, true);
label->set_text(text);
label->set_modulate(Color(1.f, 1.f, 1.f, .5f));
label->set_outline_modulate(Color(0.f, 0.f, 0.f, .5f));
label->set_font_size(_label_size);
label->set_outline_size(_label_size / 6);
label->set_visibility_range_end(_label_distance);
label->set_visibility_range_end_margin(_label_distance / 10.f);
label->set_visibility_range_fade_mode(GeometryInstance3D::VISIBILITY_RANGE_FADE_SELF);
_label_parent->add_child(label, true);
Vector2i loc = region_locations[i];
Vector3 pos = Vector3(real_t(loc.x) + .5f, 0.f, real_t(loc.y) + .5f) * _region_size * _vertex_spacing;
real_t height = _data->get_height(pos);
pos.y = (std::isnan(height)) ? 0 : height;
label->set_position(pos);
}
}
}
void Terrain3D::set_mesh_lods(const int p_count) {
if (_mesh_lods != p_count) {
LOG(INFO, "Setting mesh levels: ", p_count);
_mesh_lods = p_count;
if (_mesher) {
_mesher->initialize(this);
}
}
}
void Terrain3D::set_mesh_size(const int p_size) {
if (_mesh_size != p_size) {
LOG(INFO, "Setting mesh size: ", p_size);
_mesh_size = p_size;
if (_mesher && _material.is_valid()) {
_material->_update_maps();
_mesher->initialize(this);
}
}
}
void Terrain3D::set_vertex_spacing(const real_t p_spacing) {
real_t spacing = CLAMP(p_spacing, 0.25f, 100.0f);
if (_vertex_spacing != spacing) {
_vertex_spacing = spacing;
LOG(INFO, "Setting vertex spacing: ", _vertex_spacing);
if (_collision && _data && _instancer && _material.is_valid()) {
_data->_vertex_spacing = _vertex_spacing;
update_region_labels();
_instancer->_update_vertex_spacing(_vertex_spacing);
_camera_last_position = V2_MAX;
_material->_update_maps();
_collision->destroy();
_collision->build();
}
}
if (IS_EDITOR && _plugin) {
_plugin->call("update_region_grid");
}
}
void Terrain3D::set_render_layers(const uint32_t p_layers) {
LOG(INFO, "Setting terrain render layers to: ", p_layers);
_render_layers = p_layers;
if (_mesher) {
_mesher->update();
}
}
void Terrain3D::set_mouse_layer(const uint32_t p_layer) {
uint32_t layer = CLAMP(p_layer, 21, 32);
_mouse_layer = layer;
uint32_t mouse_mask = 1 << (_mouse_layer - 1);
LOG(INFO, "Setting mouse layer: ", layer, " (", mouse_mask, ") on terrain mesh, material, mouse camera, mouse quad");
// Set terrain meshes to mouse layer
// Mask off editor render layers by ORing user layers 1-20 and current mouse layer
set_render_layers((_render_layers & 0xFFFFF) | mouse_mask);
// Set terrain shader to exclude mouse camera from showing holes
if (_material.is_valid()) {
_material->set_shader_param("_mouse_layer", mouse_mask);
}
// Set mouse camera to see only mouse layer
if (_mouse_cam) {
_mouse_cam->set_cull_mask(mouse_mask);
}
// Set screenquad to mouse layer
if (_mouse_quad) {
_mouse_quad->set_layer_mask(mouse_mask);
}
}
void Terrain3D::set_cast_shadows(const RenderingServer::ShadowCastingSetting p_cast_shadows) {
_cast_shadows = p_cast_shadows;
if (_mesher) {
_mesher->update();
}
}
void Terrain3D::set_gi_mode(const GeometryInstance3D::GIMode p_gi_mode) {
_gi_mode = p_gi_mode;
if (_mesher) {
_mesher->update();
}
}
void Terrain3D::set_cull_margin(const real_t p_margin) {
LOG(INFO, "Setting extra cull margin: ", p_margin);
_cull_margin = p_margin;
if (_mesher) {
_mesher->update_aabbs();
}
}
/* Returns the point a ray intersects the ground using either raymarching or the GPU depth texture
* p_src_pos (camera position)
* p_direction (camera direction looking at the terrain)
* p_gpu_mode - false: use raymarching, true: use GPU mode
* Returns Vec3(NAN) on error or vec3(3.402823466e+38F) on no intersection. Test w/ if (var.x < 3.4e38)
*/
Vector3 Terrain3D::get_intersection(const Vector3 &p_src_pos, const Vector3 &p_direction, const bool p_gpu_mode) {
if (!is_instance_valid(_camera_instance_id)) {
LOG(ERROR, "Invalid camera");
return Vector3(NAN, NAN, NAN);
}
if (!_mouse_cam) {
LOG(ERROR, "Invalid mouse camera");
return Vector3(NAN, NAN, NAN);
}
Vector3 direction = p_direction.normalized();
Vector3 point;
// Position mouse cam one unit behind the requested position
_mouse_cam->set_global_position(p_src_pos - direction);
// If looking straight down (eg orthogonal camera), just return height. look_at won't work
if ((direction - Vector3(0.f, -1.f, 0.f)).length_squared() < 0.00001f) {
_mouse_cam->set_rotation_degrees(Vector3(-90.f, 0.f, 0.f));
point = p_src_pos;
point.y = _data->get_height(p_src_pos);
if (std::isnan(point.y)) {
point.y = 0;
}
} else if (!p_gpu_mode) {
// Else if not gpu mode, use raymarching mode
point = p_src_pos;
for (int i = 0; i < 4000; i++) {
real_t height = _data->get_height(point);
if (point.y - height <= 0) {
return point;
}
point += direction;
}
return V3_MAX;
} else {
// Else use GPU mode, which requires multiple calls
// Get depth from perspective camera snapshot
_mouse_cam->look_at(_mouse_cam->get_global_position() + direction, Vector3(0.f, 1.f, 0.f));
_mouse_vp->set_update_mode(SubViewport::UPDATE_ONCE);
Ref<ViewportTexture> vp_tex = _mouse_vp->get_texture();
Ref<Image> vp_img = vp_tex->get_image();
// Read the depth pixel from the camera viewport
Color screen_depth = vp_img->get_pixel(0, 0);
// Get position from depth packed in RGB - unpack back to float.
// Forward+ is 16bit, mobile and compatibility is 10bit.
// Compatibility also has precision loss for values below 0.5, so
// we use only the top half of the range, for 21bit depth encoded.
real_t r = floor((screen_depth.r * 256.0) - 128.0);
real_t g = floor((screen_depth.g * 256.0) - 128.0);
real_t b = floor((screen_depth.b * 256.0) - 128.0);
// Decode the full depth value
real_t decoded_depth = (r + g / 127.0 + b / (127.0 * 127.0)) / 127.0;
if (decoded_depth < 0.00001f) {
return V3_MAX;
}
// Necessary for a correct value depth = 1
if (decoded_depth > 0.99999f) {
decoded_depth = 1.0f;
}
// Denormalize distance to get real depth and terrain position.
decoded_depth *= _mouse_cam->get_far();
// Project the camera position by the depth value to get the intersection point.
point = _mouse_cam->get_global_position() + direction * decoded_depth;
}
return point;
}
/**
* Generates a static ArrayMesh for the terrain.
* p_lod (0-8): Determines the granularity of the generated mesh.
* p_filter: Controls how vertices' Y coordinates are generated from the height map.
* HEIGHT_FILTER_NEAREST: Samples the height map in a 'nearest neighbour' fashion.
* HEIGHT_FILTER_MINIMUM: Samples a range of heights around each vertex and returns the lowest.
* This takes longer than ..._NEAREST, but can be used to create occluders, since it can guarantee the
* generated mesh will not extend above or outside the clipmap at any LOD.
*/
Ref<Mesh> Terrain3D::bake_mesh(const int p_lod, const Terrain3DData::HeightFilter p_filter) const {
LOG(INFO, "Baking mesh at lod: ", p_lod, " with filter: ", p_filter);
Ref<Mesh> result;
ERR_FAIL_COND_V(_data == nullptr, result);
Ref<SurfaceTool> st;
st.instantiate();
st->begin(Mesh::PRIMITIVE_TRIANGLES);
PackedVector3Array vertices;
PackedVector2Array uvs;
_generate_triangles(vertices, &uvs, p_lod, p_filter, false, AABB());
ERR_FAIL_COND_V(vertices.size() != uvs.size(), result);
for (int i = 0; i < vertices.size(); ++i) {
st->set_uv(uvs[i]);
st->add_vertex(vertices[i]);
}
st->index();
st->generate_normals();
st->generate_tangents();
st->optimize_indices_for_cache();
result = st->commit();
return result;
}
/**
* Generates source geometry faces for input to nav mesh baking. Geometry is only generated where there
* are no holes and the terrain has been painted as navigable.
* p_global_aabb: If non-empty, geometry will be generated only within this AABB. If empty, geometry
* will be generated for the entire terrain.
* p_require_nav: If true, this function will only generate geometry for terrain marked navigable.
* Otherwise, geometry is generated for the entire terrain within the AABB (which can be useful for
* dynamic and/or runtime nav mesh baking).
*/
PackedVector3Array Terrain3D::generate_nav_mesh_source_geometry(const AABB &p_global_aabb, const bool p_require_nav) const {
LOG(INFO, "Generating NavMesh source geometry from terrain");
PackedVector3Array faces;
_generate_triangles(faces, nullptr, 0, Terrain3DData::HEIGHT_FILTER_NEAREST, p_require_nav, p_global_aabb);
return faces;
}
void Terrain3D::set_warning(const uint8_t p_warning, const bool p_enabled) {
if (p_enabled) {
_warnings |= p_warning;
} else {
_warnings &= ~p_warning;
}
update_configuration_warnings();
}
void Terrain3D::set_enable_streaming(const bool p_enabled) {
LOG(INFO, "Setting enable streaming: ", p_enabled);
_enable_streaming = p_enabled;
if (_data) {
_data->set_enable_streaming(p_enabled);
}
}
bool Terrain3D::get_enable_streaming() const {
return _enable_streaming;
}
void Terrain3D::set_streaming_rings(const int p_rings) {
if (!_data) {
return;
}
int rings = CLAMP(p_rings, 1, 15);
_streaming_rings = rings;
_data->set_streaming_rings(rings);
}
int Terrain3D::get_streaming_rings() const {
return _streaming_rings;
}
void Terrain3D::set_streaming_distance(const real_t p_distance) {
if (!_data) {
return;
}
int rings = CLAMP(int(p_distance / 250.0f), 1, 20);
set_streaming_rings(rings);
}
real_t Terrain3D::get_streaming_distance() const {
return _streaming_rings * 250.0f;
}
PackedStringArray Terrain3D::_get_configuration_warnings() const {
PackedStringArray psa;
if (_data_directory.is_empty()) {
psa.push_back("No data directory specified. Select a directory then save the scene to write data.");
}
if (_warnings & WARN_MISMATCHED_SIZE) {
psa.push_back("Texture dimensions don't match. Double-click a texture in the FileSystem panel to see its size. Read Texture Prep in docs.");
}
if (_warnings & WARN_MISMATCHED_FORMAT) {
psa.push_back("Texture formats don't match. Double-click a texture in the FileSystem panel to see its format. Check Import panel. Read Texture Prep in docs.");
}
if (_warnings & WARN_MISMATCHED_MIPMAPS) {
psa.push_back("Texture mipmap settings don't match. Change on the Import panel.");
}
return psa;
}
///////////////////////////
// Protected Functions
///////////////////////////
// Notifications are defined in individual classes: Object, Node, Node3D
// Listed below in order of operation
void Terrain3D::_notification(const int p_what) {
switch (p_what) {
/// Startup notifications
case NOTIFICATION_POSTINITIALIZE: {
// Object initialized, before script is attached
LOG(INFO, "NOTIFICATION_POSTINITIALIZE");
_build_containers();
break;
}
case NOTIFICATION_ENTER_WORLD: {
// Node3D registered to new World3D resource
// Sent on scene changes
LOG(INFO, "NOTIFICATION_ENTER_WORLD");
_is_inside_world = true;
if (_mesher) {
_mesher->update();
}
break;
}
case NOTIFICATION_ENTER_TREE: {
// Node entered a SceneTree
// Sent on scene changes
LOG(INFO, "NOTIFICATION_ENTER_TREE");
set_as_top_level(true); // Don't inherit transforms from parent. Global only.
set_notify_transform(true);
set_meta("_edit_lock_", true);
_setup_mouse_picking();
_initialize(); // Rebuild anything freed: meshes, collision, instancer
set_physics_process(true);
break;
}
case NOTIFICATION_READY: {
// Node is ready
LOG(INFO, "NOTIFICATION_READY");
if (_free_editor_textures && !IS_EDITOR && _assets.is_valid()) {
_assets->clear_textures();
}
break;
}
/// Game Loop notifications
case NOTIFICATION_PHYSICS_PROCESS: {
// Node is processing one physics frame
__physics_process(get_process_delta_time());
break;
}
case NOTIFICATION_TRANSFORM_CHANGED: {
// Node3D or parent transform changed
if (get_transform() != Transform3D()) {
set_transform(Transform3D());
}
break;
}
case NOTIFICATION_VISIBILITY_CHANGED: {
// Node3D visibility changed
LOG(INFO, "NOTIFICATION_VISIBILITY_CHANGED");
if (_mesher) {
_mesher->update();
}
break;
}
case NOTIFICATION_EXTENSION_RELOADED: {
// Object finished hot reloading
LOG(INFO, "NOTIFICATION_EXTENSION_RELOADED");
break;
}
case NOTIFICATION_EDITOR_PRE_SAVE: {
// Editor Node is about to save the current scene
LOG(INFO, "NOTIFICATION_EDITOR_PRE_SAVE");
if (_data_directory.is_empty()) {
LOG(ERROR, "Data directory is empty. Set it to save regions to disk.");
} else if (!_data) {
LOG(DEBUG, "Save requested, but no valid data object. Skipping");
} else {
_data->save_directory(_data_directory);
}
if (!_material.is_valid()) {
LOG(DEBUG, "Save requested, but no valid material. Skipping");
} else {
_material->save();
}
if (!_assets.is_valid()) {
LOG(DEBUG, "Save requested, but no valid texture list. Skipping");
} else {
_assets->save();
}
break;
}
case NOTIFICATION_EDITOR_POST_SAVE: {
// Editor Node finished saving current scene
break;
}
case NOTIFICATION_CRASH: {
// Godot's crash handler reports engine is about to crash
// Only works on desktop if the crash handler is enabled
LOG(WARN, "NOTIFICATION_CRASH");
break;
}
/// Shut down notifications
case NOTIFICATION_EXIT_TREE: {
// Node is about to exit a SceneTree
// Sent on scene changes
LOG(INFO, "NOTIFICATION_EXIT_TREE");
set_physics_process(false);
_destroy_mesher();
_destroy_mouse_picking();
if (_assets.is_valid()) {
_assets->uninitialize();
}