layers/craters/generation/cell_cache.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /// @file | ||
| 2 | /// @brief `CraterCellCache`, the craters of generated cells kept for reuse. | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "terraingen/layers/craters/generation/population.h" | ||
| 6 | #include "terraingen/util/lru_cache.h" | ||
| 7 | |||
| 8 | #include <cstddef> | ||
| 9 | #include <cstdint> | ||
| 10 | #include <functional> | ||
| 11 | #include <memory> | ||
| 12 | |||
| 13 | namespace terraingen { | ||
| 14 | |||
| 15 | /// The craters drawn in each cell of each band, kept so tiles and point queries generate | ||
| 16 | /// each cell once. | ||
| 17 | /// | ||
| 18 | /// Holds about `maxCraters` craters at most, evicting least recently used cells; thread-safe. | ||
| 19 | /// Cells regenerate identically, so eviction never changes results. | ||
| 20 | class CraterCellCache { | ||
| 21 | public: | ||
| 22 | /// @param maxCraters Most craters held across every cell; positive. | ||
| 23 | /// @throws std::invalid_argument if `maxCraters` is zero. | ||
| 24 | explicit CraterCellCache(std::size_t maxCraters = 4000000); | ||
| 25 | |||
| 26 | /// The craters of `cell` in the band of `exponent`, drawn by `generate` when not held. | ||
| 27 | 2765204 | std::shared_ptr<const CraterList> Get(int exponent, const CellIndex& cell, | |
| 28 | const std::function<CraterList()>& generate) { | ||
| 29 | 2765204 | return cache_.Get({exponent, cell.i, cell.j}, generate); | |
| 30 | } | ||
| 31 | |||
| 32 | /// The number of craters held across every cell. | ||
| 33 | 4 | std::size_t Size() const { | |
| 34 | 4 | return cache_.Size(); | |
| 35 | } | ||
| 36 | |||
| 37 | /// The most craters held. | ||
| 38 | 1 | std::size_t MaxCraters() const { | |
| 39 | 1 | return cache_.Capacity(); | |
| 40 | } | ||
| 41 | |||
| 42 | /// The number of cells evicted since construction. | ||
| 43 | 2 | std::size_t Evictions() const { | |
| 44 | 2 | return cache_.Evictions(); | |
| 45 | } | ||
| 46 | |||
| 47 | private: | ||
| 48 | struct Key { | ||
| 49 | 2659100 | int exponent; | |
| 50 | 2659100 | std::int32_t i; | |
| 51 | 2659100 | std::int32_t j; | |
| 52 | |||
| 53 | 2659100 | bool operator==(const Key&) const = default; | |
| 54 | }; | ||
| 55 | struct KeyHash { | ||
| 56 | std::size_t operator()(const Key& key) const; | ||
| 57 | }; | ||
| 58 | |||
| 59 | LruCache<Key, CraterList, KeyHash> cache_; | ||
| 60 | }; | ||
| 61 | |||
| 62 | /// A source for `CraterGenerationOptions::cellCraters` that draws each cell with | ||
| 63 | /// `GenerateCellCraters` once and keeps it in `cache`; every argument must outlive it. | ||
| 64 | CellCraterSource CachedCellCraters(CraterCellCache& cache, const SurfaceCells& cells, | ||
| 65 | const SizeFrequencyDistribution& density, | ||
| 66 | const CraterAgeModel& ages, std::uint32_t seed); | ||
| 67 | |||
| 68 | } // namespace terraingen | ||
| 69 |