generate entities on biome

This commit is contained in:
2026-05-19 09:47:42 +02:00
parent fcab02469a
commit ee8d6458ed
16 changed files with 278 additions and 37 deletions

View File

@@ -2,6 +2,7 @@ extends CharacterBody3D
class_name AIBase
@export_group("Movement")
@export var speed: float = 4.0
var _enable_state_machine: bool = true
@export var enable_state_machine: bool:
@@ -11,11 +12,17 @@ var _enable_state_machine: bool = true
get:
return _enable_state_machine
@onready var patrol_radius_shape: CollisionShape3D = $%PatrolRadiusShape
@onready var nav_agent: NavigationAgent3D = $%NavigationAgent3D
@onready var state_machine: StateMachine = $%StateMachine
@export_group("Entities")
enum EntityType { HUMANOID, ANIMAL }
@export var entity_type: EntityType = EntityType.HUMANOID
@export var entity_name: String = ""
@export var allowed_biomes: Array[String] = []
@export_range(0.0, 100.0, 0.1) var spawn_uniqueness: float = 1.0
func _ready() -> void:
randomize()

View File

@@ -14,6 +14,7 @@ radius = 20.0
[node name="AiBase" type="CharacterBody3D" unique_id=1228675528]
script = ExtResource("1_4d1nn")
entity_name = "Humanoid"
[node name="MeshInstance3D" type="MeshInstance3D" parent="." unique_id=214482161]
mesh = SubResource("CapsuleMesh_mh3lg")

View File

@@ -1,8 +1,14 @@
extends Node3D
#constants about biome, pieces and entity spawn
const CHUNK_TYPE_BIOME: int = 0
const CHUNK_TYPE_STRAIGHT_TRACK: int = 1
const CHUNK_TYPE_CURVED_TRACK: int = 2
const ENTITY_TYPE_HUMANOID: int = 0
const ENTITY_TYPE_ANIMAL: int = 1
const ENTITY_SPAWN_ANY: int = 0
const ENTITY_SPAWN_HUMANOID_ONLY: int = 1
const ENTITY_SPAWN_ANIMAL_ONLY: int = 2
const CHUNK_GENERATION_FRAME_BUDGET_USEC: int = 2000 #2 ms/frame to generate chunks
const CHUNK_CLEANUP_FRAME_BUDGET_USEC: int = 1000 #1 ms/frame per cleanup
@@ -18,7 +24,6 @@ const LAMPPOST_WIRE_FRAME_BUDGET_USEC: int = 1000 #1 ms/frame per i fili dei lam
#abbassare cleanup a 500
const MAX_CHUNK_UNIQUENESS: int = 5
const RAILWAY_SCENE_DIRECTORY: String = "res://tgcc/chunk/railway/scene"
const RIVER_SIDE_ORDER: Array[String] = ["north", "est", "south", "west"]
const RIVER_DIRECTIONS: Dictionary = {
"north": Vector2(0.0, -1.0),
@@ -35,10 +40,16 @@ const RIVER_NEIGHBOUR_OFFSETS: Dictionary = {
@export_group("Rails")
@export var rail_path: Path3D #rail path
@export var railway_pool: Resource
@export_group("Biomes")
@export var biome_list: Array[Biome] #list of scenes for the biome
@export_group("Entities")
@export var entity_pool: Resource
@export_range(0.0, 1.0, 0.01) var entity_spawn_probability: float = 0.6
@export_range(0, 20, 1) var max_entities_per_chunk: int = 3
@export_group("Grid and Area")
@export var chunk_size: float = 20.0 #size of a cell; default 20 (global position is defined dividing x and z for this value)
@export var eye_line: int = 3 #cells to be considerated around the train (e.g. 3 => a square of cells from -3 to 3 around train cell)
@@ -56,6 +67,7 @@ var altitude_generator: FastNoiseLite
var wire_connections: Dictionary = {}
var chunk_candidate_cache: Dictionary = {} #node cache (metadata)
var prop_candidate_cache: Dictionary = {}
var entity_candidate_cache: Dictionary = {}
var pending_generation_cells: Array[Vector2i] = []
var pending_cleanup_cells: Array[Vector2i] = []
var pending_wire_cells: Array[Vector2i] = []
@@ -86,6 +98,7 @@ func _ready() -> void:
#fill cache with available chunk
_warm_chunk_candidate_cache()
_warm_entity_candidate_cache()
_warm_rail_chunk_catalogue()
#set unique pieces
_update_set_pieces()
@@ -120,6 +133,7 @@ func _update_set_pieces() -> void:
func _destroy_and_regenrate_world() -> void:
_warm_chunk_candidate_cache()
_warm_entity_candidate_cache()
_clear_pending_world_work()
#Turn off old temples
@@ -179,6 +193,24 @@ func collect_all_propinfo(root: Node, list: Array[Node]) -> void:
for child in root.get_children():
collect_all_propinfo(child, list)
func collect_all_entityinfo(root: Node, list: Array[Node]) -> void:
if root == null: return
if "entity_type" in root:
list.append(root)
for child in root.get_children():
collect_all_entityinfo(child, list)
func collect_all_entity_spawn_points(root: Node, list: Array[Node]) -> void:
if root == null: return
if "allowed_type" in root or root.is_in_group("entity_spawn_point"):
list.append(root)
for child in root.get_children():
collect_all_entity_spawn_points(child, list)
func _warm_chunk_candidate_cache() -> void:
var unique_scenes: Dictionary = {}
@@ -199,27 +231,30 @@ func _warm_chunk_candidate_cache() -> void:
for scene in unique_scenes.values():
_get_chunk_scene_metadata(scene)
func _warm_rail_chunk_catalogue() -> void:
rail_chunk_catalogue.clear()
var directory := DirAccess.open(RAILWAY_SCENE_DIRECTORY)
if directory == null:
func _warm_entity_candidate_cache() -> void:
entity_candidate_cache.clear()
if entity_pool == null or not "available_entities" in entity_pool:
return
directory.list_dir_begin()
var file_name := directory.get_next()
while file_name != "":
if not directory.current_is_dir() and file_name.ends_with(".tscn"):
var scene_path := "%s/%s" % [RAILWAY_SCENE_DIRECTORY, file_name]
var scene := load(scene_path) as PackedScene
if scene != null:
var chunk_type = _get_chunk_type_from_scene(scene)
if chunk_type == CHUNK_TYPE_STRAIGHT_TRACK or chunk_type == CHUNK_TYPE_CURVED_TRACK:
if not rail_chunk_catalogue.has(chunk_type):
rail_chunk_catalogue[chunk_type] = []
rail_chunk_catalogue[chunk_type].append(scene)
file_name = directory.get_next()
directory.list_dir_end()
for scene in entity_pool.available_entities:
if scene == null:
continue
_get_entity_scene_metadata(scene)
func _warm_rail_chunk_catalogue() -> void:
rail_chunk_catalogue.clear()
if railway_pool == null or not "available_railways" in railway_pool:
return
for scene in railway_pool.available_railways:
if scene == null:
continue
var chunk_type = _get_chunk_type_from_scene(scene)
if chunk_type == CHUNK_TYPE_STRAIGHT_TRACK or chunk_type == CHUNK_TYPE_CURVED_TRACK:
if not rail_chunk_catalogue.has(chunk_type):
rail_chunk_catalogue[chunk_type] = []
rail_chunk_catalogue[chunk_type].append(scene)
func _get_chunk_scene_cache_key(scene: PackedScene) -> String:
if scene == null:
@@ -306,7 +341,7 @@ func _collect_replaceable_rail_chunks(root: Node, result: Array[Node3D]) -> void
if root is Node3D:
var node_3d := root as Node3D
if node_3d.scene_file_path.begins_with(RAILWAY_SCENE_DIRECTORY):
if _is_railway_scene_registered(node_3d.scene_file_path):
var info_list: Array[Node] = []
collect_all_chunkinfo(node_3d, info_list)
var info_node = info_list[0] if info_list.size() > 0 else null
@@ -319,6 +354,17 @@ func _collect_replaceable_rail_chunks(root: Node, result: Array[Node3D]) -> void
for child in root.get_children():
_collect_replaceable_rail_chunks(child, result)
func _is_railway_scene_registered(scene_path: String) -> bool:
if scene_path == "":
return false
for candidates in rail_chunk_catalogue.values():
for candidate in candidates:
var scene := candidate as PackedScene
if scene != null and scene.resource_path == scene_path:
return true
return false
func _pick_replacement_rail_scene(chunk_type: int, current_scene_path: String) -> PackedScene:
var candidates: Array = rail_chunk_catalogue.get(chunk_type, [])
if candidates.is_empty():
@@ -365,7 +411,7 @@ func _replace_rail_chunk_instance(chunk_root: Node3D) -> bool:
chunk_root.queue_free()
return true
#rebuild the scene catalogue from res://tgcc/chunk/railway/scene,
#rebuild the scene catalogue from railway_pool,
#than serach on the current scene which chunks can be changed and for each one chose a new scene (the same kind)
func _refresh_rail_chunks() -> void:
print("update rail chunks")
@@ -521,6 +567,13 @@ func _choose_catalogue_by_cell(grid_pos: Vector2i) -> Array[PackedScene]:
var indice = clamp(int(normalized_value * biome_list.size()), 0, biome_list.size() - 1)
return biome_list[indice].available_chunks
func _choose_biome_name_by_cell(grid_pos: Vector2i) -> String:
if manual_biome != null:
return manual_biome.name
var value = noise_generator.get_noise_2d(grid_pos.x, grid_pos.y)
return _get_procedural_biome_name(value)
func _get_procedural_biome_name(value: float) -> String:
if manual_biome != null:
return manual_biome.name
@@ -592,6 +645,41 @@ func _get_prop_scene_cache_key(scene: PackedScene) -> String:
return scene.resource_path
return "prop_scene_%s" % scene.get_instance_id()
func _get_entity_scene_cache_key(scene: PackedScene) -> String:
if scene == null:
return ""
if scene.resource_path != "":
return scene.resource_path
return "entity_scene_%s" % scene.get_instance_id()
func _get_entity_scene_metadata(scene: PackedScene) -> Dictionary:
if scene == null:
return {}
var key = _get_entity_scene_cache_key(scene)
if entity_candidate_cache.has(key):
return entity_candidate_cache[key]
var preview_entity = scene.instantiate()
var entity_info_list: Array[Node] = []
collect_all_entityinfo(preview_entity, entity_info_list)
var info_node = entity_info_list[0] if entity_info_list.size() > 0 else null
if info_node == null:
preview_entity.queue_free()
entity_candidate_cache[key] = {}
return {}
var metadata = {
"type": info_node.entity_type,
"name": info_node.entity_name if "entity_name" in info_node else "",
"allowed_biomes": info_node.allowed_biomes.duplicate() if "allowed_biomes" in info_node else [],
"weight": maxf(info_node.spawn_uniqueness if "spawn_uniqueness" in info_node else 1.0, 0.0001)
}
preview_entity.queue_free()
entity_candidate_cache[key] = metadata
return metadata
func _get_prop_scene_uniqueness(scene: PackedScene) -> int:
if scene == null:
return -1
@@ -664,6 +752,90 @@ func _spawn_prop_for_marker(marker: Node) -> void:
marker.add_child(prop_node)
prop_node.transform = Transform3D.IDENTITY
func _spawn_entities_for_chunk(root: Node, biome_name: String) -> void:
if entity_pool == null or not "available_entities" in entity_pool:
return
if entity_pool.available_entities.is_empty():
return
if entity_spawn_probability <= 0.0 or max_entities_per_chunk <= 0:
return
if entity_candidate_cache.is_empty():
_warm_entity_candidate_cache()
var spawn_points: Array[Node] = []
collect_all_entity_spawn_points(root, spawn_points)
if spawn_points.is_empty():
return
spawn_points.shuffle()
var spawned_count: int = 0
for spawn_point in spawn_points:
if spawned_count >= max_entities_per_chunk:
break
var point_node = spawn_point as Node3D
if point_node == null:
continue
var spawn_chance = entity_spawn_probability
if "spawn_chance" in spawn_point:
spawn_chance *= spawn_point.spawn_chance
if randf() > spawn_chance:
continue
var entity_scene = _pick_compatible_entity(biome_name, _get_spawn_point_type_filter(spawn_point))
if entity_scene == null:
continue
var entity_instance = entity_scene.instantiate()
var entity_node = entity_instance as Node3D
if entity_node == null:
entity_instance.queue_free()
continue
root.add_child(entity_node)
entity_node.global_transform = point_node.global_transform
if "random_y_rotation" in spawn_point and spawn_point.random_y_rotation:
entity_node.rotate_y(randf() * TAU)
spawned_count += 1
func _get_spawn_point_type_filter(spawn_point: Node) -> int:
if "allowed_type" in spawn_point:
match spawn_point.allowed_type:
ENTITY_SPAWN_HUMANOID_ONLY:
return ENTITY_TYPE_HUMANOID
ENTITY_SPAWN_ANIMAL_ONLY:
return ENTITY_TYPE_ANIMAL
return -1
func _pick_compatible_entity(biome_name: String, type_filter: int) -> PackedScene:
if entity_pool == null or not "available_entities" in entity_pool:
return null
var candidates = []
for entity_scene in entity_pool.available_entities:
if entity_scene == null:
continue
var metadata = _get_entity_scene_metadata(entity_scene)
if metadata.is_empty():
continue
if type_filter != -1 and int(metadata["type"]) != type_filter:
continue
var allowed_biomes: Array = metadata.get("allowed_biomes", [])
if not allowed_biomes.is_empty() and not allowed_biomes.has(biome_name):
continue
candidates.append({
"scene": entity_scene,
"weight": float(metadata.get("weight", 1.0))
})
if candidates.is_empty():
return null
return _pick_weighted_candidate(candidates).scene
#Using a vertical raycast from the top to the bottom at the center of the cell
#If there is a collision search for a new chunk node
func _register_cell_with_ray(grid_pos: Vector2i) -> bool:
@@ -772,6 +944,7 @@ func _add_compatible_biome(grid_pos: Vector2i) -> void:
var height_target = clamp(roundi((height_noise + 1.0) / 2.0), 0, 1)
var zone_catalogue = _choose_catalogue_by_cell(grid_pos)
var biome_name = _choose_biome_name_by_cell(grid_pos)
var valid_candidates = []
for scene in zone_catalogue:
@@ -840,6 +1013,7 @@ func _add_compatible_biome(grid_pos: Vector2i) -> void:
new_chunk.rotation.y = choise.rotation * (-PI / 2.0)
add_child(new_chunk)
_spawn_props_for_chunk(new_chunk)
_spawn_entities_for_chunk(new_chunk, biome_name)
var info_new = _get_cached_chunk_info(new_chunk, choise.scene)
@@ -871,6 +1045,7 @@ func _add_compatible_biome(grid_pos: Vector2i) -> void:
backup.position = Vector3(grid_pos.x * chunk_size, 0, grid_pos.y * chunk_size)
add_child(backup)
_spawn_props_for_chunk(backup)
_spawn_entities_for_chunk(backup, biome_name)
var info_backup = _get_cached_chunk_info(backup, backup_scene)
var backup_uniqueness = _get_chunk_uniqueness_from_info(info_backup)

View File

@@ -2,7 +2,9 @@
[ext_resource type="Script" uid="uid://ct2k25kslaxe5" path="res://core/biome_generator/biome_generator.gd" id="1_c7ilo"]
[ext_resource type="Material" uid="uid://b8p1sjxisi522" path="res://core/biome_generator/wires.tres" id="2_w42pm"]
[ext_resource type="Resource" path="res://core/biome_generator/railway_pool.tres" id="3_railway_pool"]
[node name="biome_generator" type="Node3D" unique_id=1861369341]
script = ExtResource("1_c7ilo")
railway_pool = ExtResource("3_railway_pool")
lamppost_wire_material = ExtResource("2_w42pm")

View File

@@ -0,0 +1,9 @@
[gd_resource type="Resource" script_class="EntityPool" format=3 uid="uid://cmd6s6thq4f7r"]
[ext_resource type="PackedScene" uid="uid://clx701xdwelgx" path="res://core/ai/agents/base/ai_base.tscn" id="1_0kfj8"]
[ext_resource type="Script" uid="uid://53ryr0fsqiq7" path="res://core/biome_generator/entity_pool.gd" id="1_vccp2"]
[resource]
script = ExtResource("1_vccp2")
name = "Entity Pool"
available_entities = Array[PackedScene]([ExtResource("1_0kfj8")])

View File

@@ -0,0 +1,5 @@
extends Resource
class_name EntityPool
@export var name: String = "New Entity Pool"
@export var available_entities: Array[PackedScene] = []

View File

@@ -0,0 +1 @@
uid://53ryr0fsqiq7

View File

@@ -0,0 +1,8 @@
extends Marker3D
class_name EntitySpawnPoint
enum AllowedType { ANY, HUMANOID_ONLY, ANIMAL_ONLY }
@export var allowed_type: AllowedType = AllowedType.ANY
@export_range(0.0, 1.0, 0.01) var spawn_chance: float = 1.0
@export var random_y_rotation: bool = true

View File

@@ -0,0 +1 @@
uid://c5ercbqy7srx3

View File

@@ -0,0 +1,5 @@
extends Resource
class_name RailwayPool
@export var name: String = "New Railway Pool"
@export var available_railways: Array[PackedScene] = []

View File

@@ -0,0 +1 @@
uid://c374rv220mvh1

View File

@@ -0,0 +1,16 @@
[gd_resource type="Resource" script_class="RailwayPool" format=3 uid="uid://nrm040srfjwo"]
[ext_resource type="PackedScene" uid="uid://cl2ast2tk7ifw" path="res://tgcc/chunk/railway/scene/chunk_railway_curve.tscn" id="1_86h1y"]
[ext_resource type="PackedScene" uid="uid://85l80b6jcdhr" path="res://tgcc/chunk/railway/scene/chunk_railway_curve_2.tscn" id="2_r0882"]
[ext_resource type="PackedScene" uid="uid://cewdxvcpqb53f" path="res://tgcc/chunk/railway/scene/chunk_railway_station_doubleside.tscn" id="3_3auto"]
[ext_resource type="PackedScene" uid="uid://d3pcshw2bioic" path="res://tgcc/chunk/railway/scene/chunk_railway_station_oneside.tscn" id="4_i1umq"]
[ext_resource type="PackedScene" uid="uid://bqxpqhla2kogq" path="res://tgcc/chunk/railway/scene/chunk_railway_straight.tscn" id="5_x44at"]
[ext_resource type="PackedScene" uid="uid://c3ub6rj0tlt6q" path="res://tgcc/chunk/railway/scene/chunk_railway_straight_2.tscn" id="6_vrrkw"]
[ext_resource type="PackedScene" uid="uid://cqevecsd1cm1v" path="res://tgcc/chunk/railway/scene/chunk_railway_straight_3.tscn" id="7_l17bw"]
[ext_resource type="PackedScene" uid="uid://f53hfrjaxkwa" path="res://tgcc/chunk/railway/scene/chunk_railway_straight_bridge.tscn" id="8_qcl5o"]
[ext_resource type="Script" uid="uid://c374rv220mvh1" path="res://core/biome_generator/railway_pool.gd" id="9_8tdc7"]
[resource]
script = ExtResource("9_8tdc7")
name = "Railway Pool"
available_railways = Array[PackedScene]([ExtResource("1_86h1y"), ExtResource("2_r0882"), ExtResource("3_3auto"), ExtResource("4_i1umq"), ExtResource("5_x44at"), ExtResource("6_vrrkw"), ExtResource("7_l17bw"), ExtResource("8_qcl5o")])