-
-
Notifications
You must be signed in to change notification settings - Fork 338
/
mod.rs
1833 lines (1617 loc) · 69.8 KB
/
mod.rs
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
//! Everything related to terrains. See [`Terrain`] docs for more info.
use crate::material::MaterialResourceExtension;
use crate::renderer::bundle::PersistentIdentifier;
use crate::scene::node::RdcControlFlow;
use crate::{
asset::Resource,
core::{
algebra::{Matrix4, Point3, Vector2, Vector3, Vector4},
arrayvec::ArrayVec,
log::Log,
math::{aabb::AxisAlignedBoundingBox, ray::Ray, ray_rect_intersection, Rect},
pool::Handle,
reflect::prelude::*,
sstorage::ImmutableString,
uuid::{uuid, Uuid},
variable::InheritableVariable,
visitor::{prelude::*, PodVecView},
TypeUuidProvider,
},
material::{Material, MaterialResource, PropertyValue},
renderer::{
self,
bundle::{RenderContext, SurfaceInstanceData},
framework::geometry_buffer::ElementRange,
},
resource::texture::{
Texture, TextureKind, TexturePixelKind, TextureResource, TextureResourceExtension,
TextureWrapMode,
},
scene::{
base::{Base, BaseBuilder},
debug::SceneDrawingContext,
graph::Graph,
mesh::RenderPath,
node::{Node, NodeTrait},
terrain::{geometry::TerrainGeometry, quadtree::QuadTree},
},
};
use fyrox_core::uuid_provider;
use fyrox_graph::BaseSceneGraph;
use fyrox_resource::untyped::ResourceKind;
use half::f16;
use image::{imageops::FilterType, ImageBuffer, Luma};
use std::{
cell::Cell,
cmp::Ordering,
collections::HashMap,
ops::{Deref, DerefMut, Range},
};
mod geometry;
mod quadtree;
/// Current implementation version marker.
pub const VERSION: u8 = 1;
/// Layers is a material Terrain can have as many layers as you want, but each layer slightly decreases
/// performance, so keep amount of layers on reasonable level (1 - 5 should be enough for most
/// cases).
#[derive(Debug, Clone, Visit, Reflect, PartialEq)]
pub struct Layer {
/// Material of the layer.
pub material: MaterialResource,
/// Name of the mask sampler property in the material.
pub mask_property_name: String,
/// Name of the height map sampler property in the material.
#[visit(optional)]
pub height_map_property_name: String,
/// Name of the node uv offsets property in the material.
#[visit(optional)]
pub node_uv_offsets_property_name: String,
}
uuid_provider!(Layer = "7439d5fd-43a9-45f0-bd7c-76cf4d2ec22e");
impl Default for Layer {
fn default() -> Self {
Self {
material: MaterialResource::new_ok(Default::default(), Material::standard_terrain()),
mask_property_name: "maskTexture".to_string(),
height_map_property_name: "heightMapTexture".to_string(),
node_uv_offsets_property_name: "nodeUvOffsets".to_string(),
}
}
}
fn make_quad_tree(
texture: &Option<TextureResource>,
height_map_size: Vector2<u32>,
block_size: Vector2<u32>,
) -> QuadTree {
let texture = texture.as_ref().unwrap().data_ref();
let height_map = texture.data_of_type::<f32>().unwrap();
QuadTree::new(height_map, height_map_size, block_size)
}
fn make_height_map_texture_internal(
height_map: Vec<f32>,
size: Vector2<u32>,
) -> Option<TextureResource> {
let mut data = Texture::from_bytes(
TextureKind::Rectangle {
width: size.x,
height: size.y,
},
TexturePixelKind::R32F,
crate::core::transmute_vec_as_bytes(height_map),
)?;
data.set_t_wrap_mode(TextureWrapMode::ClampToEdge);
data.set_s_wrap_mode(TextureWrapMode::ClampToEdge);
Some(Resource::new_ok(Default::default(), data))
}
fn make_height_map_texture(height_map: Vec<f32>, size: Vector2<u32>) -> TextureResource {
make_height_map_texture_internal(height_map, size).unwrap()
}
/// Chunk is smaller block of a terrain. Terrain can have as many chunks as you need, which always arranged in a
/// grid. You can add chunks from any side of a terrain. Chunks could be considered as a "sub-terrain", which could
/// use its own set of materials for layers. This could be useful for different biomes, to prevent high amount of
/// layers which could harm the performance.
#[derive(Debug, Reflect, PartialEq)]
pub struct Chunk {
#[reflect(hidden)]
quad_tree: QuadTree,
#[reflect(hidden)]
version: u8,
#[reflect(
setter = "set_height_map",
description = "Height map of the chunk. You can assign a custom height map image here. Keep in mind, that \
only Red channel will be used! The assigned texture will be automatically converted to internal format suitable \
for terrain needs."
)]
heightmap: Option<TextureResource>,
#[reflect(hidden)]
position: Vector3<f32>,
#[reflect(hidden)]
physical_size: Vector2<f32>,
#[reflect(hidden)]
height_map_size: Vector2<u32>,
#[reflect(hidden)]
block_size: Vector2<u32>,
#[reflect(hidden)]
grid_position: Vector2<i32>,
/// Layer blending masks of the chunk.
#[reflect(hidden)]
pub layer_masks: Vec<TextureResource>,
}
uuid_provider!(Chunk = "ae996754-69c1-49ba-9c17-a7bd4be072a9");
impl Clone for Chunk {
// Deep cloning.
fn clone(&self) -> Self {
Self {
version: self.version,
heightmap: Some(self.heightmap.as_ref().unwrap().deep_clone()),
position: self.position,
physical_size: self.physical_size,
height_map_size: self.height_map_size,
block_size: self.block_size,
grid_position: self.grid_position,
layer_masks: self
.layer_masks
.iter()
.map(|m| m.deep_clone())
.collect::<Vec<_>>(),
quad_tree: make_quad_tree(&self.heightmap, self.height_map_size, self.block_size),
}
}
}
// Manual implementation of the trait because we need to serialize heightmap differently.
impl Visit for Chunk {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
let mut region = visitor.enter_region(name)?;
let mut version = if region.is_reading() {
0u8
} else {
self.version
};
let _ = version.visit("Version", &mut region);
match version {
0 => {
let mut height_map = Vec::<f32>::new();
let mut view = PodVecView::from_pod_vec(&mut height_map);
view.visit("Heightmap", &mut region)?;
self.position.visit("Position", &mut region)?;
let mut width = 0.0f32;
width.visit("Width", &mut region)?;
let mut length = 0.0f32;
length.visit("Length", &mut region)?;
self.physical_size = Vector2::new(width, length);
let mut width_point_count = 0u32;
width_point_count.visit("WidthPointCount", &mut region)?;
let mut length_point_count = 0u32;
length_point_count.visit("LengthPointCount", &mut region)?;
self.height_map_size = Vector2::new(width_point_count, length_point_count);
self.grid_position = Vector2::new(
(self.position.x / width) as i32,
(self.position.y / length) as i32,
);
self.heightmap = Some(make_height_map_texture(
height_map,
Vector2::new(width_point_count, length_point_count),
));
}
VERSION => {
self.heightmap.visit("Heightmap", &mut region)?;
self.position.visit("Position", &mut region)?;
self.physical_size.visit("PhysicalSize", &mut region)?;
self.height_map_size.visit("HeightMapSize", &mut region)?;
self.layer_masks.visit("LayerMasks", &mut region)?;
self.grid_position.visit("GridPosition", &mut region)?;
let _ = self.block_size.visit("BlockSize", &mut region);
}
_ => (),
}
self.quad_tree = make_quad_tree(&self.heightmap, self.height_map_size, self.block_size);
Ok(())
}
}
impl Default for Chunk {
fn default() -> Self {
Self {
quad_tree: Default::default(),
version: VERSION,
heightmap: Default::default(),
position: Default::default(),
physical_size: Default::default(),
height_map_size: Default::default(),
block_size: Vector2::new(32, 32),
grid_position: Default::default(),
layer_masks: Default::default(),
}
}
}
impl Chunk {
/// Returns position of the chunk in local 2D coordinates relative to origin of the
/// terrain.
pub fn local_position(&self) -> Vector2<f32> {
map_to_local(self.position)
}
/// Returns a reference to height map.
pub fn heightmap(&self) -> &TextureResource {
self.heightmap.as_ref().unwrap()
}
/// Sets new height map to the chunk.
pub fn set_height_map(
&mut self,
height_map: Option<TextureResource>,
) -> Option<TextureResource> {
if let Some(new_height_map) = height_map {
let mut state = new_height_map.state();
if let Some(new_height_map_texture) = state.data() {
if let TextureKind::Rectangle { width, height } = new_height_map_texture.kind() {
if width == self.height_map_size.x && height == self.height_map_size.y {
fn convert<T, C>(texture: &Texture, mut mapper: C) -> Option<Vec<f32>>
where
T: Sized,
C: Fn(&T) -> f32,
{
texture
.mip_level_data_of_type::<T>(0)
.map(|v| v.iter().map(&mut mapper).collect::<Vec<_>>())
}
// Try to convert Red component of pixels to R32F format.
let pixels = match new_height_map_texture.pixel_kind() {
TexturePixelKind::R8 | TexturePixelKind::Luminance8 => {
convert::<u8, _>(new_height_map_texture, |v| {
*v as f32 / u8::MAX as f32
})
}
TexturePixelKind::RGB8 => {
#[repr(C)]
struct Rgb8 {
r: u8,
g: u8,
b: u8,
}
convert::<Rgb8, _>(new_height_map_texture, |v| {
v.r as f32 / u8::MAX as f32
})
}
TexturePixelKind::RGBA8 => {
#[repr(C)]
struct Rgba8 {
r: u8,
g: u8,
b: u8,
a: u8,
}
convert::<Rgba8, _>(new_height_map_texture, |v| {
v.r as f32 / u8::MAX as f32
})
}
TexturePixelKind::RG8 | TexturePixelKind::LuminanceAlpha8 => {
#[repr(C)]
struct Rg8 {
r: u8,
g: u8,
}
convert::<Rg8, _>(new_height_map_texture, |v| {
v.r as f32 / u8::MAX as f32
})
}
TexturePixelKind::R16 | TexturePixelKind::Luminance16 => {
convert::<u16, _>(new_height_map_texture, |v| {
*v as f32 / u16::MAX as f32
})
}
TexturePixelKind::RG16 | TexturePixelKind::LuminanceAlpha16 => {
#[repr(C)]
struct Rg16 {
r: u16,
g: u16,
}
convert::<Rg16, _>(new_height_map_texture, |v| {
v.r as f32 / u16::MAX as f32
})
}
TexturePixelKind::BGR8 => {
#[repr(C)]
struct Bgr8 {
b: u8,
g: u8,
r: u8,
}
convert::<Bgr8, _>(new_height_map_texture, |v| {
v.r as f32 / u8::MAX as f32
})
}
TexturePixelKind::BGRA8 => {
#[repr(C)]
struct Bgra8 {
r: u8,
g: u8,
b: u8,
a: u8,
}
convert::<Bgra8, _>(new_height_map_texture, |v| {
v.r as f32 / u8::MAX as f32
})
}
TexturePixelKind::RGB16 => {
#[repr(C)]
struct Rgb16 {
r: u16,
g: u16,
b: u16,
}
convert::<Rgb16, _>(new_height_map_texture, |v| {
v.r as f32 / u16::MAX as f32
})
}
TexturePixelKind::RGBA16 => {
#[repr(C)]
struct Rgba16 {
r: u16,
g: u16,
b: u16,
a: u16,
}
convert::<Rgba16, _>(new_height_map_texture, |v| {
v.r as f32 / u16::MAX as f32
})
}
TexturePixelKind::RGB32F => {
#[repr(C)]
struct Rgb32F {
r: f32,
g: f32,
b: f32,
}
convert::<Rgb32F, _>(new_height_map_texture, |v| v.r)
}
TexturePixelKind::RGBA32F => {
#[repr(C)]
struct Rgba32F {
r: f32,
g: f32,
b: f32,
a: f32,
}
convert::<Rgba32F, _>(new_height_map_texture, |v| v.r)
}
TexturePixelKind::RGB16F => {
#[repr(C)]
struct Rgb16F {
r: f16,
g: f16,
b: f16,
}
convert::<Rgb16F, _>(new_height_map_texture, |v| v.r.to_f32())
}
TexturePixelKind::R32F => {
convert::<f32, _>(new_height_map_texture, |v| *v)
}
TexturePixelKind::R16F => {
convert::<f16, _>(new_height_map_texture, |v| v.to_f32())
}
_ => None,
};
if let Some(pixels) = pixels {
if let Some(texture) =
make_height_map_texture_internal(pixels, self.height_map_size)
{
return std::mem::replace(&mut self.heightmap, Some(texture));
}
}
}
}
}
}
// In case of any error, ignore the new value and return current height map.
self.heightmap.clone()
}
/// Returns the height map of the terrain as an array of `f32`s.
pub fn heightmap_owned(&self) -> Vec<f32> {
self.heightmap
.as_ref()
.unwrap()
.data_ref()
.data_of_type::<f32>()
.unwrap()
.to_vec()
}
/// Replaces the current height map with a new one. New height map must be equal with size of current.
pub fn replace_height_map(
&mut self,
heightmap: TextureResource,
) -> Result<(), TextureResource> {
let data = heightmap.data_ref();
if let TextureKind::Rectangle { width, height } = data.kind() {
if data.pixel_kind() == TexturePixelKind::R32F
&& self.height_map_size.x == width
&& self.height_map_size.y == height
{
drop(data);
self.heightmap = Some(heightmap);
return Ok(());
}
}
drop(data);
Err(heightmap)
}
/// Returns the size of the chunk in meters.
pub fn physical_size(&self) -> Vector2<f32> {
self.physical_size
}
/// Returns amount of pixels in the height map along each dimension.
pub fn height_map_size(&self) -> Vector2<u32> {
self.height_map_size
}
/// Performs debug drawing of the chunk. It draws internal quad-tree structure for debugging purposes.
pub fn debug_draw(&self, transform: &Matrix4<f32>, ctx: &mut SceneDrawingContext) {
let transform = *transform * Matrix4::new_translation(&self.position);
self.quad_tree
.debug_draw(&transform, self.height_map_size, self.physical_size, ctx)
}
fn set_block_size(&mut self, block_size: Vector2<u32>) {
self.block_size = block_size;
self.quad_tree = make_quad_tree(&self.heightmap, self.height_map_size, block_size);
}
}
fn map_to_local(v: Vector3<f32>) -> Vector2<f32> {
// Terrain is a XZ oriented surface so we can map X -> X, Z -> Y
Vector2::new(v.x, v.z)
}
/// Ray-terrain intersection result.
#[derive(Debug)]
pub struct TerrainRayCastResult {
/// World-space position of impact point.
pub position: Vector3<f32>,
/// Height value at the intersection point (this value could be interpolated between four neighbour pixels
/// of a height map).
pub height: f32,
/// World-space normal of triangle at impact point.
pub normal: Vector3<f32>,
/// Index of a chunk that was hit.
pub chunk_index: usize,
/// Time of impact. Usually in [0; 1] range where 0 - origin of a ray, 1 - its end.
pub toi: f32,
}
/// Terrain is a height field where each point has fixed coordinates in XZ plane, but variable Y coordinate.
/// It can be used to create landscapes. It supports multiple layers, where each layer has its own material
/// and mask.
///
/// ## Chunking
///
/// Terrain itself does not define any geometry or rendering data, instead it uses one or more chunks for that
/// purpose. Each chunk could be considered as a "sub-terrain". You can "stack" any amount of chunks from any
/// side of the terrain. To do that, you define a range of chunks along each axes. This is very useful if you
/// need to extend your terrain in a particular direction. Imagine that you've created a terrain with just one
/// chunk (`0..1` range on both axes), but suddenly you found that you need to extend the terrain to add some
/// new game locations. In this case you can change the range of chunks at the desired axis. For instance, if
/// you want to add a new location to the right from your single chunk, then you should change `width_chunks`
/// range to `0..2` and leave `length_chunks` as is (`0..1`). This way terrain will be extended and you can
/// start shaping the new location.
///
/// ## Layers
///
/// Layer is a material with a blending mask. Layers helps you to build a terrain with wide variety of details.
/// For example, you can have a terrain with 3 layers: grass, rock, snow. This combination can be used to
/// create a terrain with grassy plateaus, rocky mountains with snowy tops. Each chunk (see above) can have its
/// own set of materials for each layer, however the overall layer count is defined by the terrain itself.
/// An ability to have different set of materials for different chunks is very useful to support various biomes.
///
/// ## Level of detail (LOD)
///
/// Terrain has automatic LOD system, which means that the closest portions of it will be rendered with highest
/// possible quality (defined by the resolution of height map and masks), while the furthest portions will be
/// rendered with lowest quality. This effectively balances GPU load and allows you to render huge terrains with
/// low overhead.
///
/// The main parameter that affects LOD system is `block_size` (`Terrain::set_block_size`), which defines size
/// of the patch that will be used for rendering. It is used to divide the size of the height map into a fixed
/// set of blocks using quad-tree algorithm.
///
/// Current implementation uses modified version of CDLOD algorithm without patch morphing. Apparently it is not
/// needed, since bilinear filtration in vertex shader prevents seams to occur.
///
/// ## Painting
///
/// Terrain has a single method for "painting" - [`Terrain::draw`], it accepts a brush with specific parameters,
/// which can either alternate height map or a layer mask. See method's documentation for more info.
///
/// ## Ray casting
///
/// You have two options to perform a ray casting:
///
/// 1) By using ray casting feature of the physics engine. In this case you need to create a `Heighfield` collider
/// and use standard [`crate::scene::graph::physics::PhysicsWorld::cast_ray`] method.
/// 2) By using [`Terrain::raycast`] - this method could provide you more information about intersection point, than
/// physics-based.
///
/// ## Physics
///
/// As usual, to have collisions working you need to create a rigid body and add an appropriate collider to it.
/// In case of terrains you need to create a collider with `Heightfield` shape and specify your terrain as a
/// geometry source.
#[derive(Debug, Reflect, Clone)]
pub struct Terrain {
base: Base,
#[reflect(setter = "set_layers")]
layers: InheritableVariable<Vec<Layer>>,
#[reflect(setter = "set_decal_layer_index")]
decal_layer_index: InheritableVariable<u8>,
#[reflect(
min_value = 0.001,
description = "Size of the chunk, in meters.",
setter = "set_chunk_size"
)]
chunk_size: InheritableVariable<Vector2<f32>>,
#[reflect(
step = 1.0,
description = "Min and max 'coordinate' of chunks along X axis.",
setter = "set_width_chunks"
)]
width_chunks: InheritableVariable<Range<i32>>,
#[reflect(
step = 1.0,
description = "Min and max 'coordinate' of chunks along Y axis.",
setter = "set_length_chunks"
)]
length_chunks: InheritableVariable<Range<i32>>,
#[reflect(
min_value = 2.0,
step = 1.0,
description = "Size of the height map per chunk, in pixels. Warning: any change to this value will result in resampling!",
setter = "set_height_map_size"
)]
height_map_size: InheritableVariable<Vector2<u32>>,
#[reflect(min_value = 8.0, step = 1.0, setter = "set_block_size")]
block_size: InheritableVariable<Vector2<u32>>,
#[reflect(
min_value = 1.0,
step = 1.0,
description = "Size of the blending mask per chunk, in pixels. Warning: any change to this value will result in resampling!",
setter = "set_mask_size"
)]
mask_size: InheritableVariable<Vector2<u32>>,
#[reflect(immutable_collection)]
chunks: InheritableVariable<Vec<Chunk>>,
#[reflect(hidden)]
bounding_box_dirty: Cell<bool>,
#[reflect(hidden)]
bounding_box: Cell<AxisAlignedBoundingBox>,
#[reflect(hidden)]
geometry: TerrainGeometry,
#[reflect(hidden)]
version: u8,
}
impl Default for Terrain {
fn default() -> Self {
Self {
base: Default::default(),
layers: Default::default(),
decal_layer_index: Default::default(),
chunk_size: Vector2::new(16.0, 16.0).into(),
width_chunks: Default::default(),
length_chunks: Default::default(),
height_map_size: Default::default(),
block_size: Vector2::new(32, 32).into(),
mask_size: Default::default(),
chunks: Default::default(),
bounding_box_dirty: Cell::new(true),
bounding_box: Cell::new(Default::default()),
geometry: Default::default(),
version: VERSION,
}
}
}
#[derive(Visit)]
struct OldLayer {
pub material: MaterialResource,
pub mask_property_name: String,
pub chunk_masks: Vec<TextureResource>,
}
impl Default for OldLayer {
fn default() -> Self {
Self {
material: MaterialResource::new_ok(Default::default(), Material::standard_terrain()),
mask_property_name: "maskTexture".to_string(),
chunk_masks: Default::default(),
}
}
}
impl Visit for Terrain {
fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
let mut region = visitor.enter_region(name)?;
let mut version = if region.is_reading() {
0u8
} else {
self.version
};
let _ = version.visit("Version", &mut region);
match version {
0 => {
// Old version.
self.base.visit("Base", &mut region)?;
self.decal_layer_index
.visit("DecalLayerIndex", &mut region)?;
let mut layers =
InheritableVariable::<Vec<OldLayer>>::new_modified(Default::default());
layers.visit("Layers", &mut region)?;
let mut width = 0.0f32;
width.visit("Width", &mut region)?;
let mut length = 0.0f32;
length.visit("Length", &mut region)?;
let mut mask_resolution = 0.0f32;
mask_resolution.visit("MaskResolution", &mut region)?;
let mut height_map_resolution = 0.0f32;
height_map_resolution.visit("HeightMapResolution", &mut region)?;
let mut chunks = Vec::<Chunk>::new();
chunks.visit("Chunks", &mut region)?;
let mut width_chunks = 0u32;
width_chunks.visit("WidthChunks", &mut region)?;
self.width_chunks = (0..(width_chunks as i32)).into();
let mut length_chunks = 0u32;
length_chunks.visit("LengthChunks", &mut region)?;
self.length_chunks = (0..(length_chunks as i32)).into();
self.chunk_size =
Vector2::new(width / width_chunks as f32, length / length_chunks as f32).into();
self.mask_size = Vector2::new(
(self.chunk_size.x * mask_resolution) as u32,
(self.chunk_size.y * mask_resolution) as u32,
)
.into();
self.height_map_size = Vector2::new(
(self.chunk_size.x * height_map_resolution) as u32,
(self.chunk_size.y * height_map_resolution) as u32,
)
.into();
// Convert to new format.
for mut layer in layers.take() {
for chunk in chunks.iter_mut().rev() {
chunk.layer_masks.push(layer.chunk_masks.pop().unwrap());
}
// TODO: Due to the bug in resource system, material properties are not kept in sync
// so here we must re-create the material and put every property from the old material
// to the new.
let mut new_material = Material::standard_terrain();
let mut material_state = layer.material.state();
if let Some(material) = material_state.data() {
for (name, value) in material.properties() {
Log::verify(new_material.set_property(name, value.clone()));
}
}
self.layers.push(Layer {
material: MaterialResource::new_ok(Default::default(), new_material),
mask_property_name: layer.mask_property_name,
..Default::default()
});
}
self.chunks = chunks.into();
}
VERSION => {
// Current version
self.base.visit("Base", &mut region)?;
self.layers.visit("Layers", &mut region)?;
self.decal_layer_index
.visit("DecalLayerIndex", &mut region)?;
self.chunk_size.visit("ChunkSize", &mut region)?;
self.width_chunks.visit("WidthChunks", &mut region)?;
self.length_chunks.visit("LengthChunks", &mut region)?;
self.height_map_size.visit("HeightMapSize", &mut region)?;
let _ = self.block_size.visit("BlockSize", &mut region);
self.mask_size.visit("MaskSize", &mut region)?;
self.chunks.visit("Chunks", &mut region)?;
}
_ => (),
}
if region.is_reading() {
self.geometry = TerrainGeometry::new(*self.block_size);
}
Ok(())
}
}
impl Deref for Terrain {
type Target = Base;
fn deref(&self) -> &Self::Target {
&self.base
}
}
impl DerefMut for Terrain {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.base
}
}
fn project(global_transform: Matrix4<f32>, p: Vector3<f32>) -> Option<Vector2<f32>> {
// Transform point in coordinate system of the terrain.
if let Some(inv_global_transform) = global_transform.try_inverse() {
let local_p = inv_global_transform
.transform_point(&Point3::from(p))
.coords;
Some(map_to_local(local_p))
} else {
None
}
}
impl TypeUuidProvider for Terrain {
fn type_uuid() -> Uuid {
uuid!("4b0a7927-bcd8-41a3-949a-dd10fba8e16a")
}
}
impl Terrain {
/// Returns chunk size in meters.
pub fn chunk_size(&self) -> Vector2<f32> {
*self.chunk_size
}
/// Sets new chunk size of the terrain (in meters). All chunks in the terrain will be repositioned according
/// to their positions on the grid.
pub fn set_chunk_size(&mut self, chunk_size: Vector2<f32>) -> Vector2<f32> {
let old = *self.chunk_size;
self.chunk_size.set_value_and_mark_modified(chunk_size);
// Re-position each chunk according to its position on the grid.
for (z, iy) in (*self.length_chunks)
.clone()
.zip(0..self.length_chunks.len())
{
for (x, ix) in (*self.width_chunks).clone().zip(0..self.width_chunks.len()) {
let position = Vector3::new(
x as f32 * self.chunk_size.x,
0.0,
z as f32 * self.chunk_size.y,
);
let chunk = &mut self.chunks[iy * self.width_chunks.len() + ix];
chunk.position = position;
chunk.physical_size = chunk_size;
}
}
self.bounding_box_dirty.set(true);
old
}
/// Returns height map dimensions along each axis.
pub fn height_map_size(&self) -> Vector2<u32> {
*self.height_map_size
}
/// Sets new size of the height map for every chunk. Heightmaps in every chunk will be resampled which may
/// cause precision loss if the size was decreased. **Warning:** This method is very heavy and should not be
/// used at every frame!
pub fn set_height_map_size(&mut self, height_map_size: Vector2<u32>) -> Vector2<u32> {
let old = *self.height_map_size;
self.resize_height_maps(height_map_size);
old
}
/// Sets the new block size. Block size defines "granularity" of the terrain; the minimal terrain patch that
/// will be used for rendering. It directly affects level-of-detail system of the terrain. **Warning:** This
/// method is very heavy and should not be used at every frame!
pub fn set_block_size(&mut self, block_size: Vector2<u32>) -> Vector2<u32> {
let old = *self.block_size;
self.block_size.set_value_and_mark_modified(block_size);
self.geometry = TerrainGeometry::new(*self.block_size);
for chunk in self.chunks.iter_mut() {
chunk.set_block_size(*self.block_size);
}
old
}
/// Returns current block size of the terrain.
pub fn block_size(&self) -> Vector2<u32> {
*self.block_size
}
/// Returns the total amount of pixels along each axis of the layer blending mask.
pub fn mask_size(&self) -> Vector2<u32> {
*self.mask_size
}
/// Sets new size of the layer blending mask in pixels. Every layer mask will be resampled which may cause
/// precision loss if the size was decreased.
pub fn set_mask_size(&mut self, mask_size: Vector2<u32>) -> Vector2<u32> {
let old = *self.mask_size;
self.resize_masks(mask_size);
old
}
/// Returns a numeric range along width axis which defines start and end chunk indices on a chunks grid.
pub fn width_chunks(&self) -> Range<i32> {
(*self.width_chunks).clone()
}
/// Sets amount of chunks along width axis.
pub fn set_width_chunks(&mut self, chunks: Range<i32>) -> Range<i32> {
let old = (*self.width_chunks).clone();
self.resize(chunks, self.length_chunks());
old
}
/// Returns a numeric range along length axis which defines start and end chunk indices on a chunks grid.
pub fn length_chunks(&self) -> Range<i32> {
(*self.length_chunks).clone()
}
/// Sets amount of chunks along length axis.
pub fn set_length_chunks(&mut self, chunks: Range<i32>) -> Range<i32> {
let old = (*self.length_chunks).clone();
self.resize(self.width_chunks(), chunks);
old
}
/// Sets new chunks ranges for each axis of the terrain. This function automatically adds new chunks if you're
/// increasing size of the terrain and removes existing if you shrink the terrain.
pub fn resize(&mut self, width_chunks: Range<i32>, length_chunks: Range<i32>) {
let mut chunks = self
.chunks
.drain(..)
.map(|c| (c.grid_position, c))
.collect::<HashMap<_, _>>();
self.width_chunks.set_value_and_mark_modified(width_chunks);
self.length_chunks
.set_value_and_mark_modified(length_chunks);
for z in (*self.length_chunks).clone() {
for x in (*self.width_chunks).clone() {
let chunk = if let Some(existing_chunk) = chunks.remove(&Vector2::new(x, z)) {
// Put existing chunk back at its position.
existing_chunk
} else {
// Create new chunk.
let heightmap =
vec![0.0; (self.height_map_size.x * self.height_map_size.y) as usize];
let new_chunk = Chunk {
quad_tree: QuadTree::new(&heightmap, *self.block_size, *self.block_size),
heightmap: Some(make_height_map_texture(heightmap, self.height_map_size())),
position: Vector3::new(
x as f32 * self.chunk_size.x,
0.0,
z as f32 * self.chunk_size.y,
),
physical_size: *self.chunk_size,
height_map_size: *self.height_map_size,
block_size: *self.block_size,
grid_position: Vector2::new(x, z),
layer_masks: self
.layers
.iter()
.enumerate()
.map(|(i, _)| {
create_layer_mask(
self.mask_size.x,
self.mask_size.y,
if i == 0 { 255 } else { 0 },
)
})
.collect::<Vec<_>>(),
version: VERSION,
};
new_chunk
};
self.chunks.push(chunk);
}
}
self.bounding_box_dirty.set(true);
}
/// Returns a reference to chunks of the terrain.
pub fn chunks_ref(&self) -> &[Chunk] {
&self.chunks
}
/// Returns a mutable reference to chunks of the terrain.
pub fn chunks_mut(&mut self) -> &mut [Chunk] {
self.bounding_box_dirty.set(true);
&mut self.chunks
}
/// Sets new decal layer index. It defines which decals will be applies to the mesh,
/// for example iff a decal has index == 0 and a mesh has index == 0, then decals will
/// be applied. This allows you to apply decals only on needed surfaces.
pub fn set_decal_layer_index(&mut self, index: u8) -> u8 {
self.decal_layer_index.set_value_and_mark_modified(index)
}