veloren_world/
lib.rs

1#![expect(
2    clippy::option_map_unit_fn,
3    clippy::blocks_in_conditions,
4    clippy::identity_op,
5    clippy::needless_pass_by_ref_mut //until we find a better way for specs
6)]
7#![expect(clippy::branches_sharing_code)] // TODO: evaluate
8#![deny(clippy::clone_on_ref_ptr)]
9#![feature(option_zip, let_chains)]
10#![cfg_attr(feature = "simd", feature(portable_simd))]
11
12mod all;
13mod block;
14pub mod canvas;
15pub mod civ;
16mod column;
17pub mod config;
18pub mod index;
19pub mod land;
20pub mod layer;
21pub mod pathfinding;
22pub mod sim;
23pub mod sim2;
24pub mod site;
25pub mod site2;
26pub mod util;
27
28// Reexports
29pub use crate::{
30    canvas::{Canvas, CanvasInfo},
31    config::{CONFIG, Features},
32    land::Land,
33    layer::PathLocals,
34};
35pub use block::BlockGen;
36use civ::WorldCivStage;
37pub use column::ColumnSample;
38pub use common::terrain::site::{DungeonKindMeta, SettlementKindMeta};
39pub use index::{IndexOwned, IndexRef};
40use sim::WorldSimStage;
41
42use crate::{
43    column::ColumnGen,
44    index::Index,
45    layer::spot::SpotGenerate,
46    site::{SiteKind, SpawnRules},
47    util::{Grid, Sampler},
48};
49use common::{
50    assets,
51    calendar::Calendar,
52    comp::Content,
53    generation::{ChunkSupplement, EntityInfo, SpecialEntity},
54    lod,
55    resources::TimeOfDay,
56    rtsim::ChunkResource,
57    spiral::Spiral2d,
58    spot::Spot,
59    terrain::{
60        Block, BlockKind, CoordinateConversions, SpriteKind, TerrainChunk, TerrainChunkMeta,
61        TerrainChunkSize, TerrainGrid,
62    },
63    vol::{ReadVol, RectVolSize, WriteVol},
64};
65use common_base::prof_span;
66use common_net::msg::{WorldMapMsg, world_msg};
67use enum_map::EnumMap;
68use rand::{Rng, prelude::*};
69use rand_chacha::ChaCha8Rng;
70use serde::Deserialize;
71use std::time::Duration;
72use vek::*;
73
74#[cfg(all(feature = "be-dyn-lib", feature = "use-dyn-lib"))]
75compile_error!("Can't use both \"be-dyn-lib\" and \"use-dyn-lib\" features at once");
76
77#[cfg(feature = "use-dyn-lib")]
78use {common_dynlib::LoadedLib, lazy_static::lazy_static, std::sync::Arc, std::sync::Mutex};
79
80#[cfg(feature = "use-dyn-lib")]
81lazy_static! {
82    pub static ref LIB: Arc<Mutex<Option<LoadedLib>>> =
83        common_dynlib::init("veloren-world", "world", &[]);
84}
85
86#[cfg(feature = "use-dyn-lib")]
87pub fn init() { lazy_static::initialize(&LIB); }
88
89#[derive(Debug)]
90pub enum Error {
91    Other(String),
92}
93
94#[derive(Debug)]
95pub enum WorldGenerateStage {
96    WorldSimGenerate(WorldSimStage),
97    WorldCivGenerate(WorldCivStage),
98    EconomySimulation,
99    SpotGeneration,
100}
101
102pub struct World {
103    sim: sim::WorldSim,
104    civs: civ::Civs,
105}
106
107#[derive(Deserialize)]
108pub struct Colors {
109    pub deep_stone_color: (u8, u8, u8),
110    pub block: block::Colors,
111    pub column: column::Colors,
112    pub layer: layer::Colors,
113    pub site: site::Colors,
114}
115
116impl assets::Asset for Colors {
117    type Loader = assets::RonLoader;
118
119    const EXTENSION: &'static str = "ron";
120}
121
122impl World {
123    pub fn empty() -> (Self, IndexOwned) {
124        let index = Index::new(0);
125        (
126            Self {
127                sim: sim::WorldSim::empty(),
128                civs: civ::Civs::default(),
129            },
130            IndexOwned::new(index),
131        )
132    }
133
134    pub fn generate(
135        seed: u32,
136        opts: sim::WorldOpts,
137        threadpool: &rayon::ThreadPool,
138        report_stage: &(dyn Fn(WorldGenerateStage) + Send + Sync),
139    ) -> (Self, IndexOwned) {
140        prof_span!("World::generate");
141        // NOTE: Generating index first in order to quickly fail if the color manifest
142        // is broken.
143        threadpool.install(|| {
144            let mut index = Index::new(seed);
145            let calendar = opts.calendar.clone();
146
147            let mut sim = sim::WorldSim::generate(seed, opts, threadpool, &|stage| {
148                report_stage(WorldGenerateStage::WorldSimGenerate(stage))
149            });
150
151            let civs =
152                civ::Civs::generate(seed, &mut sim, &mut index, calendar.as_ref(), &|stage| {
153                    report_stage(WorldGenerateStage::WorldCivGenerate(stage))
154                });
155
156            report_stage(WorldGenerateStage::EconomySimulation);
157            sim2::simulate(&mut index, &mut sim);
158
159            report_stage(WorldGenerateStage::SpotGeneration);
160            Spot::generate(&mut sim);
161
162            (Self { sim, civs }, IndexOwned::new(index))
163        })
164    }
165
166    pub fn sim(&self) -> &sim::WorldSim { &self.sim }
167
168    pub fn civs(&self) -> &civ::Civs { &self.civs }
169
170    pub fn tick(&self, _dt: Duration) {
171        // TODO
172    }
173
174    pub fn get_map_data(&self, index: IndexRef, threadpool: &rayon::ThreadPool) -> WorldMapMsg {
175        prof_span!("World::get_map_data");
176        threadpool.install(|| {
177            WorldMapMsg {
178                pois: self
179                    .civs()
180                    .pois
181                    .iter()
182                    .map(|(_, poi)| world_msg::PoiInfo {
183                        name: poi.name.clone(),
184                        kind: match &poi.kind {
185                            civ::PoiKind::Peak(alt) => world_msg::PoiKind::Peak(*alt),
186                            civ::PoiKind::Biome(size) => world_msg::PoiKind::Lake(*size),
187                        },
188                        wpos: poi.loc * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
189                    })
190                    .collect(),
191                sites: self
192                    .civs()
193                    .sites
194                    .iter()
195                    .filter(|(_, site)| {
196                        !matches!(
197                            &site.kind,
198                            civ::SiteKind::PirateHideout
199                                | civ::SiteKind::JungleRuin
200                                | civ::SiteKind::RockCircle
201                                | civ::SiteKind::TrollCave
202                                | civ::SiteKind::Camp
203                        )
204                    })
205                    .map(|(_, site)| {
206                        world_msg::Marker {
207                            id: site.site_tmp.map(|i| i.id()),
208                            name: site
209                                .site_tmp
210                                .map(|id| Content::Plain(index.sites[id].name().to_string())),
211                            // TODO: Probably unify these, at some point
212                            kind: match &site.kind {
213                                civ::SiteKind::Settlement
214                                | civ::SiteKind::Refactor
215                                | civ::SiteKind::CliffTown
216                                | civ::SiteKind::SavannahTown
217                                | civ::SiteKind::CoastalTown
218                                | civ::SiteKind::DesertCity
219                                | civ::SiteKind::PirateHideout
220                                | civ::SiteKind::JungleRuin
221                                | civ::SiteKind::RockCircle
222                                | civ::SiteKind::TrollCave
223                                | civ::SiteKind::Camp => world_msg::MarkerKind::Town,
224                                civ::SiteKind::Castle => world_msg::MarkerKind::Castle,
225                                civ::SiteKind::Tree | civ::SiteKind::GiantTree => {
226                                    world_msg::MarkerKind::Tree
227                                },
228                                // TODO: Maybe change?
229                                civ::SiteKind::Gnarling => world_msg::MarkerKind::Gnarling,
230                                civ::SiteKind::DwarvenMine => world_msg::MarkerKind::DwarvenMine,
231                                civ::SiteKind::ChapelSite => world_msg::MarkerKind::ChapelSite,
232                                civ::SiteKind::Terracotta => world_msg::MarkerKind::Terracotta,
233                                civ::SiteKind::Citadel => world_msg::MarkerKind::Castle,
234                                civ::SiteKind::Bridge(_, _) => world_msg::MarkerKind::Bridge,
235                                civ::SiteKind::GliderCourse => world_msg::MarkerKind::GliderCourse,
236                                civ::SiteKind::Cultist => world_msg::MarkerKind::Cultist,
237                                civ::SiteKind::Sahagin => world_msg::MarkerKind::Sahagin,
238                                civ::SiteKind::Myrmidon => world_msg::MarkerKind::Myrmidon,
239                                civ::SiteKind::Adlet => world_msg::MarkerKind::Adlet,
240                                civ::SiteKind::Haniwa => world_msg::MarkerKind::Haniwa,
241                                civ::SiteKind::VampireCastle => {
242                                    world_msg::MarkerKind::VampireCastle
243                                },
244                            },
245                            wpos: site.center * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
246                        }
247                    })
248                    .chain(
249                        layer::cave::surface_entrances(&Land::from_sim(self.sim())).map(|wpos| {
250                            world_msg::Marker {
251                                id: None,
252                                name: None,
253                                kind: world_msg::MarkerKind::Cave,
254                                wpos,
255                            }
256                        }),
257                    )
258                    .collect(),
259                possible_starting_sites: {
260                    const STARTING_SITE_COUNT: usize = 5;
261
262                    let mut candidates = self
263                        .civs()
264                        .sites
265                        .iter()
266                        .filter_map(|(_, civ_site)| Some((civ_site, civ_site.site_tmp?)))
267                        .map(|(civ_site, site_id)| {
268                            // Score the site according to how suitable it is to be a starting site
269
270                            let (site2, mut score) = match &index.sites[site_id].kind {
271                                SiteKind::Refactor(site2) => (site2, 2.0),
272                                // Non-town sites should not be chosen as starting sites and get a
273                                // score of 0
274                                _ => return (site_id.id(), 0.0),
275                            };
276
277                            /// Optimal number of plots in a starter town
278                            const OPTIMAL_STARTER_TOWN_SIZE: f32 = 30.0;
279
280                            // Prefer sites of a medium size
281                            let plots = site2.plots().len() as f32;
282                            let size_score = if plots > OPTIMAL_STARTER_TOWN_SIZE {
283                                1.0 + (1.0
284                                    / (1.0 + ((plots - OPTIMAL_STARTER_TOWN_SIZE) / 15.0).powi(3)))
285                            } else {
286                                (2.05
287                                    / (1.0 + ((OPTIMAL_STARTER_TOWN_SIZE - plots) / 15.0).powi(5)))
288                                    - 0.05
289                            }
290                            .max(0.01);
291
292                            score *= size_score;
293
294                            // Prefer sites that are close to the centre of the world
295                            let pos_score = (10.0
296                                / (1.0
297                                    + (civ_site
298                                        .center
299                                        .map2(self.sim().get_size(), |e, sz| {
300                                            (e as f32 / sz as f32 - 0.5).abs() * 2.0
301                                        })
302                                        .reduce_partial_max())
303                                    .powi(6)
304                                        * 25.0))
305                                .max(0.02);
306                            score *= pos_score;
307
308                            // Check if neighboring biomes are beginner friendly
309                            let mut chunk_scores = 2.0;
310                            for (chunk, distance) in
311                                Spiral2d::with_radius(10).filter_map(|rel_pos| {
312                                    let chunk_pos = civ_site.center + rel_pos * 2;
313                                    self.sim()
314                                        .get(chunk_pos)
315                                        .zip(Some(rel_pos.as_::<f32>().magnitude()))
316                                })
317                            {
318                                let weight = 1.0 / (distance * std::f32::consts::TAU + 1.0);
319                                let chunk_difficulty = 20.0
320                                    / (20.0 + chunk.get_biome().difficulty().pow(4) as f32 / 5.0);
321                                // let chunk_difficulty = 1.0 / chunk.get_biome().difficulty() as
322                                // f32;
323
324                                chunk_scores *= 1.0 - weight + chunk_difficulty * weight;
325                            }
326
327                            score *= chunk_scores;
328
329                            (site_id.id(), score)
330                        })
331                        .collect::<Vec<_>>();
332                    candidates.sort_by_key(|(_, score)| -(*score * 1000.0) as i32);
333                    candidates
334                        .into_iter()
335                        .map(|(site_id, _)| site_id)
336                        .take(STARTING_SITE_COUNT)
337                        .collect()
338                },
339                ..self.sim.get_map(index, self.sim().calendar.as_ref())
340            }
341        })
342    }
343
344    pub fn sample_columns(
345        &self,
346    ) -> impl Sampler<
347        Index = (Vec2<i32>, IndexRef, Option<&'_ Calendar>),
348        Sample = Option<ColumnSample>,
349    > + '_ {
350        ColumnGen::new(&self.sim)
351    }
352
353    pub fn sample_blocks(&self) -> BlockGen { BlockGen::new(ColumnGen::new(&self.sim)) }
354
355    /// Find a position that's accessible to a player at the given world
356    /// position by searching blocks vertically.
357    ///
358    /// If `ascending` is `true`, we try to find the highest accessible position
359    /// instead of the lowest.
360    pub fn find_accessible_pos(
361        &self,
362        index: IndexRef,
363        spawn_wpos: Vec2<i32>,
364        ascending: bool,
365    ) -> Vec3<f32> {
366        let chunk_pos = TerrainGrid::chunk_key(spawn_wpos);
367
368        // Unwrapping because generate_chunk only returns err when should_continue evals
369        // to true
370        let (tc, _cs) = self
371            .generate_chunk(index, chunk_pos, None, || false, None)
372            .unwrap();
373
374        tc.find_accessible_pos(spawn_wpos, ascending)
375    }
376
377    #[expect(clippy::result_unit_err)]
378    pub fn generate_chunk(
379        &self,
380        index: IndexRef,
381        chunk_pos: Vec2<i32>,
382        rtsim_resources: Option<EnumMap<ChunkResource, f32>>,
383        // TODO: misleading name
384        mut should_continue: impl FnMut() -> bool,
385        time: Option<(TimeOfDay, Calendar)>,
386    ) -> Result<(TerrainChunk, ChunkSupplement), ()> {
387        let calendar = time.as_ref().map(|(_, cal)| cal);
388
389        let mut sampler = self.sample_blocks();
390
391        let chunk_wpos2d = chunk_pos * TerrainChunkSize::RECT_SIZE.map(|e| e as i32);
392        let chunk_center_wpos2d = chunk_wpos2d + TerrainChunkSize::RECT_SIZE.map(|e| e as i32 / 2);
393        let grid_border = 4;
394        let zcache_grid = Grid::populate_from(
395            TerrainChunkSize::RECT_SIZE.map(|e| e as i32) + grid_border * 2,
396            |offs| sampler.get_z_cache(chunk_wpos2d - grid_border + offs, index, calendar),
397        );
398
399        let air = Block::air(SpriteKind::Empty);
400        let stone = Block::new(
401            BlockKind::Rock,
402            zcache_grid
403                .get(grid_border + TerrainChunkSize::RECT_SIZE.map(|e| e as i32) / 2)
404                .and_then(|zcache| zcache.as_ref())
405                .map(|zcache| zcache.sample.stone_col)
406                .unwrap_or_else(|| index.colors.deep_stone_color.into()),
407        );
408
409        let (base_z, sim_chunk) = match self
410            .sim
411            /*.get_interpolated(
412                chunk_pos.map2(chunk_size2d, |e, sz: u32| e * sz as i32 + sz as i32 / 2),
413                |chunk| chunk.get_base_z(),
414            )
415            .and_then(|base_z| self.sim.get(chunk_pos).map(|sim_chunk| (base_z, sim_chunk))) */
416            .get_base_z(chunk_pos)
417        {
418            Some(base_z) => (base_z as i32, self.sim.get(chunk_pos).unwrap()),
419            // Some((base_z, sim_chunk)) => (base_z as i32, sim_chunk),
420            None => {
421                // NOTE: This is necessary in order to generate a handful of chunks at the edges
422                // of the map.
423                return Ok((self.sim().generate_oob_chunk(), ChunkSupplement::default()));
424            },
425        };
426        let meta = TerrainChunkMeta::new(
427            sim_chunk.get_location_name(&index.sites, &self.civs.pois, chunk_center_wpos2d),
428            sim_chunk.get_biome(),
429            sim_chunk.alt,
430            sim_chunk.tree_density,
431            sim_chunk.river.is_river(),
432            sim_chunk.river.near_water(),
433            sim_chunk.river.velocity,
434            sim_chunk.temp,
435            sim_chunk.humidity,
436            sim_chunk
437                .sites
438                .iter()
439                .filter(|id| {
440                    index.sites[**id]
441                        .get_origin()
442                        .distance_squared(chunk_center_wpos2d) as f32
443                        <= index.sites[**id].radius().powi(2)
444                })
445                .min_by_key(|id| {
446                    index.sites[**id]
447                        .get_origin()
448                        .distance_squared(chunk_center_wpos2d)
449                })
450                .map(|id| index.sites[*id].kind.convert_to_meta().unwrap_or_default()),
451            self.sim.approx_chunk_terrain_normal(chunk_pos),
452            sim_chunk.rockiness,
453            sim_chunk.cliff_height,
454        );
455
456        let mut chunk = TerrainChunk::new(base_z, stone, air, meta);
457
458        for y in 0..TerrainChunkSize::RECT_SIZE.y as i32 {
459            for x in 0..TerrainChunkSize::RECT_SIZE.x as i32 {
460                if should_continue() {
461                    return Err(());
462                };
463
464                let offs = Vec2::new(x, y);
465
466                let z_cache = match zcache_grid.get(grid_border + offs) {
467                    Some(Some(z_cache)) => z_cache,
468                    _ => continue,
469                };
470
471                let (min_z, max_z) = z_cache.get_z_limits();
472
473                (base_z..min_z as i32).for_each(|z| {
474                    let _ = chunk.set(Vec3::new(x, y, z), stone);
475                });
476
477                (min_z as i32..max_z as i32).for_each(|z| {
478                    let lpos = Vec3::new(x, y, z);
479                    let wpos = Vec3::from(chunk_wpos2d) + lpos;
480
481                    if let Some(block) = sampler.get_with_z_cache(wpos, Some(z_cache)) {
482                        let _ = chunk.set(lpos, block);
483                    }
484                });
485            }
486        }
487
488        let sample_get = |offs| {
489            zcache_grid
490                .get(grid_border + offs)
491                .and_then(Option::as_ref)
492                .map(|zc| &zc.sample)
493        };
494
495        // Only use for rng affecting dynamic elements like chests and entities!
496        let mut dynamic_rng = ChaCha8Rng::from_seed(thread_rng().gen());
497
498        // Apply layers (paths, caves, etc.)
499        let mut canvas = Canvas {
500            info: CanvasInfo {
501                chunk_pos,
502                wpos: chunk_pos * TerrainChunkSize::RECT_SIZE.map(|e| e as i32),
503                column_grid: &zcache_grid,
504                column_grid_border: grid_border,
505                chunks: &self.sim,
506                index,
507                chunk: sim_chunk,
508                calendar,
509            },
510            chunk: &mut chunk,
511            entities: Vec::new(),
512            rtsim_resource_blocks: Vec::new(),
513        };
514
515        if index.features.train_tracks {
516            layer::apply_trains_to(&mut canvas, &self.sim, sim_chunk, chunk_center_wpos2d);
517        }
518
519        if index.features.caverns {
520            layer::apply_caverns_to(&mut canvas, &mut dynamic_rng);
521        }
522        if index.features.caves {
523            layer::apply_caves_to(&mut canvas, &mut dynamic_rng);
524        }
525        if index.features.rocks {
526            layer::apply_rocks_to(&mut canvas, &mut dynamic_rng);
527        }
528        if index.features.shrubs {
529            layer::apply_shrubs_to(&mut canvas, &mut dynamic_rng);
530        }
531        if index.features.trees {
532            layer::apply_trees_to(&mut canvas, &mut dynamic_rng, calendar);
533        }
534        if index.features.scatter {
535            layer::apply_scatter_to(&mut canvas, &mut dynamic_rng, calendar);
536        }
537        if index.features.paths {
538            layer::apply_paths_to(&mut canvas);
539        }
540        if index.features.spots {
541            layer::apply_spots_to(&mut canvas, &mut dynamic_rng);
542        }
543        // layer::apply_coral_to(&mut canvas);
544
545        // Apply site generation
546        sim_chunk
547            .sites
548            .iter()
549            .for_each(|site| index.sites[*site].apply_to(&mut canvas, &mut dynamic_rng));
550
551        let mut rtsim_resource_blocks = std::mem::take(&mut canvas.rtsim_resource_blocks);
552        let mut supplement = ChunkSupplement {
553            entities: std::mem::take(&mut canvas.entities),
554            rtsim_max_resources: Default::default(),
555        };
556        drop(canvas);
557
558        let gen_entity_pos = |dynamic_rng: &mut ChaCha8Rng| {
559            let lpos2d = TerrainChunkSize::RECT_SIZE
560                .map(|sz| dynamic_rng.gen::<u32>().rem_euclid(sz) as i32);
561            let mut lpos = Vec3::new(
562                lpos2d.x,
563                lpos2d.y,
564                sample_get(lpos2d).map(|s| s.alt as i32 - 32).unwrap_or(0),
565            );
566
567            while let Some(block) = chunk.get(lpos).ok().copied().filter(Block::is_solid) {
568                lpos.z += block.solid_height().ceil() as i32;
569            }
570
571            (Vec3::from(chunk_wpos2d) + lpos).map(|e: i32| e as f32) + 0.5
572        };
573
574        if sim_chunk.contains_waypoint {
575            let waypoint_pos = gen_entity_pos(&mut dynamic_rng);
576            if sim_chunk
577                .sites
578                .iter()
579                .map(|site| index.sites[*site].spawn_rules(waypoint_pos.xy().as_()))
580                .fold(SpawnRules::default(), |a, b| a.combine(b))
581                .waypoints
582            {
583                supplement
584                    .add_entity(EntityInfo::at(waypoint_pos).into_special(SpecialEntity::Waypoint));
585            }
586        }
587
588        // Apply layer supplement
589        layer::wildlife::apply_wildlife_supplement(
590            &mut dynamic_rng,
591            chunk_wpos2d,
592            sample_get,
593            &chunk,
594            index,
595            sim_chunk,
596            &mut supplement,
597            time.as_ref(),
598        );
599
600        // Apply site supplementary information
601        sim_chunk.sites.iter().for_each(|site| {
602            index.sites[*site].apply_supplement(
603                &mut dynamic_rng,
604                chunk_wpos2d,
605                sample_get,
606                &mut supplement,
607                site.id(),
608                time.as_ref(),
609            )
610        });
611
612        // Finally, defragment to minimize space consumption.
613        chunk.defragment();
614
615        // Before we finish, we check candidate rtsim resource blocks, deduplicating
616        // positions and only keeping those that actually do have resources.
617        // Although this looks potentially very expensive, only blocks that are rtsim
618        // resources (i.e: a relatively small number of sprites) are processed here.
619        if let Some(rtsim_resources) = rtsim_resources {
620            rtsim_resource_blocks.sort_unstable_by_key(|pos| pos.into_array());
621            rtsim_resource_blocks.dedup();
622            for wpos in rtsim_resource_blocks {
623                let _ = chunk.map(wpos - chunk_wpos2d.with_z(0), |block| {
624                    if let Some(res) = block.get_rtsim_resource() {
625                        // Note: this represents the upper limit, not the actual number spanwed, so
626                        // we increment this before deciding whether we're going to spawn the
627                        // resource.
628                        supplement.rtsim_max_resources[res] += 1;
629                        // Throw a dice to determine whether this resource should actually spawn
630                        // TODO: Don't throw a dice, try to generate the *exact* correct number
631                        if dynamic_rng.gen_bool(rtsim_resources[res] as f64) {
632                            block
633                        } else {
634                            block.into_vacant()
635                        }
636                    } else {
637                        block
638                    }
639                });
640            }
641        }
642
643        Ok((chunk, supplement))
644    }
645
646    // Zone coordinates
647    pub fn get_lod_zone(&self, pos: Vec2<i32>, index: IndexRef) -> lod::Zone {
648        let min_wpos = pos.map(lod::to_wpos);
649        let max_wpos = (pos + 1).map(lod::to_wpos);
650
651        let mut objects = Vec::new();
652
653        // Add trees
654        prof_span!(guard, "add trees");
655        objects.extend(
656            &mut self
657                .sim()
658                .get_area_trees(min_wpos, max_wpos)
659                .filter_map(|attr| {
660                    ColumnGen::new(self.sim())
661                        .get((attr.pos, index, self.sim().calendar.as_ref()))
662                        .filter(|col| layer::tree::tree_valid_at(attr.pos, col, None, attr.seed))
663                        .zip(Some(attr))
664                })
665                .filter_map(|(col, tree)| {
666                    Some(lod::Object {
667                        kind: match tree.forest_kind {
668                            all::ForestKind::Dead => lod::ObjectKind::Dead,
669                            all::ForestKind::Pine => lod::ObjectKind::Pine,
670                            all::ForestKind::Mangrove => lod::ObjectKind::Mangrove,
671                            all::ForestKind::Acacia => lod::ObjectKind::Acacia,
672                            all::ForestKind::Birch => lod::ObjectKind::Birch,
673                            all::ForestKind::Redwood => lod::ObjectKind::Redwood,
674                            all::ForestKind::Baobab => lod::ObjectKind::Baobab,
675                            all::ForestKind::Frostpine => lod::ObjectKind::Frostpine,
676                            all::ForestKind::Palm => lod::ObjectKind::Palm,
677                            _ => lod::ObjectKind::GenericTree,
678                        },
679                        pos: {
680                            let rpos = tree.pos - min_wpos;
681                            if rpos.is_any_negative() {
682                                return None;
683                            } else {
684                                rpos.map(|e| e as i16).with_z(col.alt as i16)
685                            }
686                        },
687                        flags: lod::InstFlags::empty()
688                            | if col.snow_cover {
689                                lod::InstFlags::SNOW_COVERED
690                            } else {
691                                lod::InstFlags::empty()
692                            }
693                            // Apply random rotation
694                            | lod::InstFlags::from_bits(((tree.seed % 4) as u8) << 2).expect("This shouldn't set unknown bits"),
695                        color: {
696                            let field = crate::util::RandomField::new(tree.seed);
697                            let lerp = field.get_f32(Vec3::from(tree.pos)) * 0.8 + 0.1;
698                            let sblock = tree.forest_kind.leaf_block();
699
700                            crate::all::leaf_color(index, tree.seed, lerp, &sblock)
701                                .unwrap_or(Rgb::black())
702                        },
703                    })
704                }),
705        );
706        drop(guard);
707
708        // Add structures
709        objects.extend(
710            index
711                .sites
712                .iter()
713                .filter(|(_, site)| {
714                    site.get_origin()
715                        .map2(min_wpos.zip(max_wpos), |e, (min, max)| e >= min && e < max)
716                        .reduce_and()
717                })
718                .filter_map(|(_, site)| {
719                    site.site2().map(|site| {
720                        site.plots().filter_map(|plot| match &plot.kind {
721                            site2::plot::PlotKind::House(h) => Some((
722                                site.tile_wpos(plot.root_tile),
723                                h.roof_color(),
724                                lod::ObjectKind::House,
725                            )),
726                            site2::plot::PlotKind::GiantTree(t) => Some((
727                                site.tile_wpos(plot.root_tile),
728                                t.leaf_color(),
729                                lod::ObjectKind::GiantTree,
730                            )),
731                            site2::plot::PlotKind::Haniwa(_) => Some((
732                                site.tile_wpos(plot.root_tile),
733                                Rgb::black(),
734                                lod::ObjectKind::Haniwa,
735                            )),
736                            site2::plot::PlotKind::DesertCityMultiPlot(_) => Some((
737                                site.tile_wpos(plot.root_tile),
738                                Rgb::black(),
739                                lod::ObjectKind::Desert,
740                            )),
741                            site2::plot::PlotKind::DesertCityArena(_) => Some((
742                                site.tile_wpos(plot.root_tile),
743                                Rgb::black(),
744                                lod::ObjectKind::Arena,
745                            )),
746                            site2::plot::PlotKind::SavannahHut(_)
747                            | site2::plot::PlotKind::SavannahWorkshop(_) => Some((
748                                site.tile_wpos(plot.root_tile),
749                                Rgb::black(),
750                                lod::ObjectKind::SavannahHut,
751                            )),
752                            site2::plot::PlotKind::SavannahAirshipDock(_) => Some((
753                                site.tile_wpos(plot.root_tile),
754                                Rgb::black(),
755                                lod::ObjectKind::SavannahAirshipDock,
756                            )),
757                            site2::plot::PlotKind::TerracottaPalace(_) => Some((
758                                site.tile_wpos(plot.root_tile),
759                                Rgb::black(),
760                                lod::ObjectKind::TerracottaPalace,
761                            )),
762                            site2::plot::PlotKind::TerracottaHouse(_) => Some((
763                                site.tile_wpos(plot.root_tile),
764                                Rgb::black(),
765                                lod::ObjectKind::TerracottaHouse,
766                            )),
767                            site2::plot::PlotKind::TerracottaYard(_) => Some((
768                                site.tile_wpos(plot.root_tile),
769                                Rgb::black(),
770                                lod::ObjectKind::TerracottaYard,
771                            )),
772                            site2::plot::PlotKind::AirshipDock(_) => Some((
773                                site.tile_wpos(plot.root_tile),
774                                Rgb::black(),
775                                lod::ObjectKind::AirshipDock,
776                            )),
777                            site2::plot::PlotKind::CoastalHouse(_) => Some((
778                                site.tile_wpos(plot.root_tile),
779                                Rgb::black(),
780                                lod::ObjectKind::CoastalHouse,
781                            )),
782                            site2::plot::PlotKind::CoastalWorkshop(_) => Some((
783                                site.tile_wpos(plot.root_tile),
784                                Rgb::black(),
785                                lod::ObjectKind::CoastalWorkshop,
786                            )),
787                            _ => None,
788                        })
789                    })
790                })
791                .flatten()
792                .filter_map(|(wpos2d, color, model)| {
793                    ColumnGen::new(self.sim())
794                        .get((wpos2d, index, self.sim().calendar.as_ref()))
795                        .zip(Some((wpos2d, color, model)))
796                })
797                .map(|(column, (wpos2d, color, model))| lod::Object {
798                    kind: model,
799                    pos: (wpos2d - min_wpos)
800                        .map(|e| e as i16)
801                        .with_z(self.sim().get_alt_approx(wpos2d).unwrap_or(0.0) as i16),
802                    flags: if column.snow_cover {
803                        lod::InstFlags::SNOW_COVERED
804                    } else {
805                        lod::InstFlags::empty()
806                    },
807                    color,
808                }),
809        );
810
811        lod::Zone { objects }
812    }
813
814    // determine waypoint name
815    pub fn get_location_name(&self, index: IndexRef, wpos2d: Vec2<i32>) -> Option<String> {
816        let chunk_pos = wpos2d.wpos_to_cpos();
817        let sim_chunk = self.sim.get(chunk_pos)?;
818        sim_chunk.get_location_name(&index.sites, &self.civs.pois, wpos2d)
819    }
820}