ForestGenerator
A class in Root.Township, Alta.Forests.
Generates the procedural forest from a seed: a path graph inside an outline, reshaped and painted terrain, rivers, and per-chunk content. Most results are cached on disk by seed. A scene component on both sides; All lists them.
- Listed in World generation
- Inherits or implements
NetworkEntityBehaviour,ISavable<ForestGeneratorSaveData>,ISavableSave<ForestGeneratorSaveData>,ISavableSaveBase - Derived types
ForestGeneratorSaveData - Nested types
NearestInfo,TerrainNoise - Attributes
TypeConverter - Documented in Forest, Arguments and results
Constructors
| Member | What it is |
|---|---|
ForestGenerator() | Unity makes components itself; use AddComponent or spawn a prefab instead of new. |
Fields
63 private and internal fields
| Member | What it is |
|---|---|
private static HashSet<ForestGenerator> all | Backing field for All. |
private Action<string> bootupStatus | Progress callback used while Bootup runs. Null otherwise. |
private bool btnNavmesh | Editor button that runs RegenerateNavmesh. |
private string cache | Backing field for Cache. Part of every cache file name for this forest. |
private float currentMaximum | Most distance two points can be apart and still get an edge, for the current pass. |
private float currentMinimum | Least spacing between points, for the current pass. |
private float edgeBuffer | Distance points and edges must keep from the outline. 20 by default. |
private float edgeHeightPullFalloff | Not read in this class. |
private float edgeHeightPullFalloffPower | Not read in this class. |
private float edgeHeightPullStrength | Not read in this class. |
private List<Node> entranceNodes | Backing field for Entrances. Not assigned in this class. |
private float entranceRadius | Radius given to entrance nodes. 5 by default. |
private Transform[] entrances | Transforms marking where paths enter the forest. They become the first nodes. |
private IForestGeneration[] forestGeneration | The IForestGeneration steps under the generator (trees, rocks and more) that make global, static and dynamic content. |
private Task<ForestGeneration> generation | The generation task, started once by GetGenerationAsync. |
private int groupSizeX | Not used. Group sizes come from the heightmap size instead. |
private int groupSizeZ | Not used. Group sizes come from the heightmap size instead. |
private int hardLimit | Most points the graph can have. 2000 by default. |
private int heightInterations | Number of ModifyHeights smoothing passes. 10 by default. |
private float heightRandomPower | Power applied to the random height nudge, so most nudges are small. 2 by default. |
private int initialCount | How many starting points were added after the entrances. Used by gizmos. |
private float initialHeight | Height new nodes start at. 10 by default. |
private float initialMaximumNearbyDistance | Edge distance limit while connecting the entrances. 20 by default. |
private float initialMinimumPointDistance | Point spacing while connecting the entrances. 10 by default. |
private int initialPathIncrement | Points added per pass until every entrance is connected. 1 by default. |
private float initialPointExtraRadiusMaximum | Most extra radius for the starting points. 12 by default. |
private float initialPointExtraRadiusMinimum | Least extra radius for the starting points. 5 by default. |
private int initialRandomPointCount | Random points tried at the start. 100 by default. |
private Dictionary<LocationChunk, InstructionSet> instructions | Static instruction set run for each loaded chunk, undone on ReleaseStatic. |
private bool isDrawingGizmos | Editor: draws the generated graph in play mode. |
private float lastIterationWeightMultiplier | How strong the random nudge is on the last height pass, compared to the first. 0.1 by default. |
private static Logger logger | NLog logger for this class. |
private float maximumHeightPerIteration | Largest random height change per pass. 5 by default. |
private float maximumNearbyDistance | Edge distance limit after the entrances are connected. 20 by default. |
private float maximumRadius | Largest base node radius, picked by noise. 10 by default. |
private float minimumPointDistance | Point spacing after the entrances are connected. 10 by default. |
private float minimumRadius | Smallest base node radius, picked by noise. 2 by default. |
private ConcurrentBag<ForestGenerator.NearestInfo> nearestInfos | Pool of nearest-edge buffers reused across height worker threads. |
private NodeMapModifier[] nodeMapModifiers | Modifiers under the generator that change the finished node map. Those that are also terrain modifiers change heights. |
private float openingMinimumDistance | Point spacing for the very first points. 20 by default. |
private Transform[] outline | Transforms tracing the forest's border. |
private static readonly NNConstraint overworldOnlyAstar | A* constraint limited to the first graph, used for navmesh updates. |
private float radiusNoiseScale | Scale of the noise that picks node radii. 10000 by default. |
private int randomPointCount | Target node count for the second, filling pass. 1000 by default. |
private List<Vector3> randomPointRadius | Working list of points as x, z and radius. The first ones are the entrances. |
private float randomWeighting | Chance (0 to 1) that carving restarts from a random used node instead of the newest. |
private int seed | The forest seed. -1 until set; the server picks a random one. Saved and synced to clients. |
private float selfHeightWeighting | How much a node's own height counts against its neighbours when smoothing. 2 by default. |
private int sizeX | Heightmap resolution on X, from SetupConstants. |
private int sizeZ | Heightmap resolution on Z, from SetupConstants. |
private Texture2D splatMap | Not read in this class. |
private int splatMapResolutionMultiplier | Not read in this class. |
private ISplatPainter[] splatPainters | Splat painters under the generator, found when painting starts. |
private MethodSync syncSeed | Method sync that sends the seed to joining players. |
private TerrainInfo terrain | The terrain the forest reshapes and paints. |
private float terrainEdgeBlurPower | Not read in this class. |
private float terrainEdgeBlurStrength | Not read in this class. |
private float terrainFadeDistance | Distance inside the border over which generated heights blend into the existing terrain. 10 by default. |
private List<ITerrainModifier> terrainModifiers | Node map modifiers that also change terrain heights. |
private ForestGenerator.TerrainNoise[] terrainNoise | Noise layers added to terrain heights, each with scale, magnitude and a fade near paths. |
private Vector3 unit | Heightmap scale: world size of one heightmap cell and the height range. |
private List<Node> usedNodes | Nodes reached by carved paths, used to pick where carving continues. |
private TaskCompletionSource<bool> wipeLock | Set while Wipe runs, so generation and a second wipe wait for it. |
Properties
| Member | What it is |
|---|---|
static IEnumerable<ForestGenerator> All { get; } | Every forest generator in the scene. |
string Cache { get; } | The forest's name in cache file names, such as "The Forest". |
ICollection<Node> Entrances { get; } | The entrance nodes of the path graph. |
int GizmosVersion { get; private set; } | Counter bumped when debug gizmo data changes. |
bool IsDuringCalculate { get; } | True while generation is running. |
RiverGenerator RiverGenerator { get; private set; } | The river, lake and waterfall generator under this forest. |
Events
| Member | What it is |
|---|---|
event Action<LocationChunk> GeneratedDynamic | Raised when a chunk has had its dynamic content (creatures, items) generated. |
Methods
| Member | What it is |
|---|---|
static async Task<ForestGenerator> Get(Vector2 position) | Finds the forest whose outline contains an x/z point. Waits for generation. |
async Task<IEnumerable<ForestGCoreInstruction>> GetAllGCores(ForestGeneration generating) | Collects the generation core instructions of every chunk in a layout. |
ForestGeneration GetGenerated(bool isThrowingError = true) | The layout if generation has finished, else null (logging an error unless told not to). |
Task<ForestGeneration> GetGenerationAsync() | The generated layout. Starts generation the first time and returns the same task after. |
override void Initialize() | Sets up the message that syncs the seed. |
override void InitializeAsServer(SpawnData spawnData) | Server: picks a random seed if none is saved. |
override void OnConnected(Player player) | Server: sends the seed to a joining player. |
async void RegenerateNavmesh() | Rebuilds the A* navmesh inside the forest outline. |
async void Reheight() | Editor tool: recomputes terrain heights inside the forest. |
void ReleaseDynamic(LocationChunk chunk) | Clears a chunk's dynamic content from every generation step. |
void ReleaseStatic(LocationChunk chunk) | Clears a chunk's static content and undoes its instructions. |
async Task RequestDynamic(LocationChunk chunk) | Generates a chunk's dynamic content and raises GeneratedDynamic. |
async Task RequestStatic(LocationChunk chunk, bool isRequiringTerrain, CancellationToken cancellationToken) | Runs a chunk's static instructions (trees, rocks). On the server it can also update the navmesh for the chunk. |
async void Resplat() | Editor tool: repaints terrain textures inside the forest. |
async Task Wipe(int newSeed = -1) | Server: clears the forest's caches and chunk saves, moves players out and regenerates. A seed passed in is ignored; negative picks a random one. TavernLib replaces it with a reset that takes effect at the next restart. |
void ZeroHeights() | Editor tool: flattens the terrain inside the outline to 0. |
28 private and internal methods
| Member | What it is |
|---|---|
private void AddRandomInTriangle(ForestGeneration result, Random random, int startIndex, float additionalRadius) | Picks a random point in one outline triangle and keeps it if it is far enough from the border and other points. |
private void AddRandomPoint(ForestGeneration result, Random random, float additionalRadius) | Tries to add one random point, picking an outline triangle weighted by area. |
private float AreaStartingAt(ForestGeneration result, int index) | Area of the outline triangle starting at an index, on the x/z plane. |
private void Awake() | Finds the river generator, node map modifiers and generation steps under it, and adds itself to All. |
private async Task Bootup(Action<string> progressNotification) | Generates the forest while reporting progress. No callers in this build. |
private Node Carve(ForestGeneration result, Random random, Node current) | Extends a path from a node to a random unused neighbour, marking the edge as a normal path. Returns the new node or null. |
private async Task Connection(Connection connection, Action<string> progressNotification) | Makes sure a connecting client has the node and terrain caches for this seed. No callers in this build. |
private void CreateRandomPoints(ForestGeneration result, Random random, int count, bool isClearing, float additionalRadiusMinimum = 0, float additionalRadiusMaximum = -1) | Adds up to count random points (each may fail), optionally clearing first and re-adding the entrances. |
private async Task EvaluateHeights(ForestGeneration result, Random random, float[,] heights, TerrainAccess access, int minX, int minY, int maxX, int maxY) | Worker for a block of heightmap rows: sets heights inside the outline from nearby paths and noise, fading into the existing terrain at the border. |
private async Task EvaluateSplatData(ForestGeneration result, Random random, SplatData[,] data, TerrainAccess access, int minX, int minY, int maxX, int maxY) | Worker for a block of splat rows: runs every splat painter on cells inside the outline. |
private float EvaluateTargetHeight(ForestGeneration generation, ForestGenerator.NearestInfo info, Vector2 position, out float distanceToPath) | Works out a terrain height from the nearest path edges' node heights, then applies the terrain modifiers. |
private async Task<ForestGeneration> GenerateAsync() | Waits for a wipe and a seed, then loads the forest layout from cache or generates nodes, terrain and chunk instructions. |
private async Task<bool> GenerateInternalAsync(ForestGeneration result) | Builds the path graph on a worker thread: random points, Delaunay edges, carved paths, heights, spaces and node modifiers. |
private async Task GenerateTerrain(ForestGeneration forest) | Gets the forest's heights and splat (from cache or by generating, with rivers), applies them and spawns river visuals and global content. |
private Task<InstructionSet> GetChunkInstructionsAsync(LocationChunk chunk, ForestGeneration forest) | Gets a chunk's static instruction set from cache, or builds it by running every generation step's GenerateStatic. |
private Node GetNext(Random random) | Picks the next node to carve from: usually the newest used node, or a random one by randomWeighting. |
private void ModifyHeights(ForestGeneration result, Random random, float weight) | One smoothing pass over node heights: blends each with its path neighbours and adds a random nudge. Entrances keep their height. |
private void OnDestroy() | Removes itself from All. |
private async void OnDrawGizmos() | Editor: draws the outline, or after generation (if isDrawingGizmos) the biome spheres, outline, paths and spaces. |
private void OutlineGizmo(ForestGeneration result) | Editor: draws the outline triangles. |
private void PathGizmos(ForestGeneration result) | Editor: draws the starting points, node radii and edges coloured by type. |
private void Reproduce(ForestGeneration result, Dictionary<Node, List<Node>> toReproduce) | Rebuilds paths from the last pass by pathfinding between previously linked nodes in the new graph. |
private void SetupConstants() | Reads heightmap size and scale from the terrain data. |
private void SpaceGizmos(ForestGeneration result) | Editor: draws a sphere at each space's centre, coloured by space type. |
private void SyncSeed(IPlayer player, Stream stream) | Method sync handler that sends or reads the seed. |
private void Traverse(ForestGeneration result, Random random) | Carves paths from used nodes until none can grow further. |
private void WeightToEdge(ForestGeneration result, float fade) | Pulls each node's height towards the height of the nearest outline edge. A fade of 0 sets it fully. |
private async Task WipeChunk(LocationChunk chunk) | Unloads a chunk, saves and clears its save, and deletes its static instruction cache. Used by Wipe. |
Used in
Members of other types that take, return or hold a ForestGenerator:
WorldCommandModule.ForestCommandModule.Info, WorldCommandModule.ForestCommandModule.Reset, WorldCommandModule.ForestCommandModule.Teleport, ForestDefinedAtmosphere.forest, ForestGeneration.Generator, ForestPopulationArea.forest, RiverCollision.forest, RiverGenerator.forest, RiverGenerator.Forest, RiverMeshTest.forest, ForestChunk.Forests, ForestChunk.inBounds.