merge: integrate remote player quest slices

This commit is contained in:
Rijad Zuzo
2026-08-16 16:53:30 +02:00
55 changed files with 3640 additions and 54 deletions
+172 -34
View File
@@ -5,6 +5,7 @@ extends Node
# intentionally keeps its orchestration readable in one authoritative file.
const SimulationEventLogScript := preload("res://simulation/events/SimulationEventLog.gd")
const SimulationEventRecorderScript := preload("res://simulation/events/SimulationEventRecorder.gd")
const VillageEconomyScript := preload("res://simulation/economy/VillageEconomy.gd")
const AnimalCareSystemScript := preload("res://simulation/animals/animal_care_system.gd")
const NpcTickDebugLog := preload("res://simulation/debug/npc_tick_debug_log.gd")
@@ -41,6 +42,14 @@ signal raid_started(raider_ids: Array[StringName])
signal war_resolved(outcome: StringName)
signal war_aborted
signal player_downed
signal player_quest_opened(quest: PlayerQuestRecord)
signal player_quest_completed(quest: PlayerQuestRecord)
signal player_quest_expired(quest: PlayerQuestRecord)
signal player_standing_changed(standing: PlayerStandingRecord)
signal player_tier_advanced(tier: int, tier_name: String)
signal player_needs_changed(state: PlayerStateRecord)
signal player_inventory_changed(state: PlayerStateRecord)
signal player_died(state: PlayerStateRecord)
var village := SimVillage.new()
var player_system := PlayerCitizenSystem.new()
@@ -59,6 +68,7 @@ var tick_count := 0
var wander_random_sources := {}
var resource_states: Dictionary = {}
var event_log := SimulationEventLogScript.new()
var event_recorder := SimulationEventRecorderScript.new()
var economy := VillageEconomyScript.new()
var animal_care := AnimalCareSystemScript.new()
var relationship_system := RelationshipSystemScript.new()
@@ -71,6 +81,10 @@ var commitment_lifecycle := CommitmentLifecycleService.new()
var conversation_service := ConversationService.new()
var conversation_history: Array[ConversationActStateRecord] = []
var conflict_system := ConflictSystemScript.new()
var player_quest_system := PlayerQuestSystem.new()
var player_needs := PlayerNeedsSystem.new()
var player_negotiation := PlayerNegotiationSystem.new()
var _last_player_tier := PlayerStandingRecord.TIER_STRANGER
var storage_states: Dictionary:
get:
return economy.storage_states
@@ -114,6 +128,19 @@ const NPC_NAMES := ["Amina", "Tarik", "Jasmin", "Elma", "Mirza", "Lejla"]
func _ready() -> void:
add_to_group("simulation_manager")
event_log.event_recorded.connect(_on_economic_event_recorded)
event_recorder.configure(event_log, Callable(self, "get_tick_count_for_recording"))
event_recorder.set_npcs(npcs)
player_needs.configure(economy, event_recorder)
player_needs.set_resource_states(resource_states)
player_negotiation.configure(
player_quest_system,
Callable(self, "_find_npc_by_id"),
Callable(self, "get_active_opportunity"),
Callable(self, "get_active_opportunity_player_response"),
player_quest_opened,
player_quest_expired,
player_standing_changed
)
economy.inventory_changed.connect(_on_economy_inventory_changed)
economy.economic_event_requested.connect(_record_economic_event)
economy.narrative_event_requested.connect(record_narrative_event)
@@ -225,6 +252,10 @@ func simulate_tick() -> void:
if debug_logs:
print("--- Tick ", tick_count, " ---")
animal_care.advance(tick_count)
for quest in player_quest_system.consider_animal_care_quests(
animal_care, npcs, get_pantry(), tick_count
):
player_quest_opened.emit(quest)
advance_player_needs()
_advance_resource_regrowth()
var village_was_changed := false
@@ -240,6 +271,10 @@ func simulate_tick() -> void:
if invalidated != null:
opportunity_invalidated.emit(invalidated)
_maintain_emergent_world()
if invalidated != null:
var expired_quest := player_quest_system.on_opportunity_invalidated(invalidated, tick_count)
if expired_quest != null:
player_quest_expired.emit(expired_quest)
if tick_count % get_knowledge_review_interval() == 0:
_maintain_event_knowledge(true)
if debug_logs:
@@ -314,7 +349,7 @@ func _select_action_if_idle(npc: SimNPC, previous_state: StringName) -> void:
var display_name := (
definition.display_name if definition != null else String(selection.action_id)
)
record_narrative_event(SimulationIds.EVENT_TASK_STARTED, npc.id, &"", display_name)
event_recorder.record_narrative(SimulationIds.EVENT_TASK_STARTED, npc.id, &"", display_name)
func _is_weak_villager_state(npc: SimNPC) -> bool:
@@ -391,7 +426,7 @@ func _handle_npc_death(npc: SimNPC, previous_task: StringName, previous_target:
release_npc_reservation(npc.id)
npc_died.emit(npc)
npc_task_changed.emit(npc, previous_task, npc.current_task)
record_narrative_event(SimulationIds.EVENT_NPC_DIED, npc.id)
event_recorder.record_narrative(SimulationIds.EVENT_NPC_DIED, npc.id)
_notify_mourning(npc)
if debug_logs:
print("[SimulationManager] NPC died: ", npc.npc_name)
@@ -480,7 +515,7 @@ func _complete_resource_gather(npc: SimNPC, completed_task: StringName) -> void:
var resource_id := resource_state.get_resource_id()
npc.add_inventory(resource_id, extracted)
npc_inventory_changed.emit(npc, resource_id, npc.get_inventory_amount(resource_id))
_record_economic_event(
event_recorder.record_economic(
SimulationIds.EVENT_RESOURCE_EXTRACTED,
npc.id,
resource_state.get_node_id(),
@@ -489,7 +524,7 @@ func _complete_resource_gather(npc: SimNPC, completed_task: StringName) -> void:
extracted
)
if resource_state.get_amount_remaining() <= 0.0:
record_narrative_event(
event_recorder.record_narrative(
SimulationIds.EVENT_RESOURCE_DEPLETED, npc.id, resource_state.get_node_id()
)
if debug_logs:
@@ -1393,6 +1428,10 @@ func _get_event_world_position(
return Vector3.ZERO
func get_tick_count_for_recording() -> int:
return tick_count
func get_npc_events(npc_id: int, max_count: int = 8) -> Array[EconomicEventRecord]:
return event_log.get_for_actor(npc_id, max_count)
@@ -1407,22 +1446,42 @@ func _on_economic_event_recorded(event: EconomicEventRecord) -> void:
)
for learned_record in learned_records:
_apply_new_event_knowledge(learned_record, event)
if StringName(event.data["event_type"]) == SimulationIds.EVENT_ANIMAL_FED:
_finish_quest_resolution(
player_quest_system.on_animal_fed(
animal_care.get_state(StringName(event.data["destination_id"])), event, tick_count
)
)
_update_opportunity_from_event(event)
_update_situations_from_event(event)
economic_event_recorded.emit(event)
func _finish_quest_resolution(resolution: Dictionary) -> void:
if not resolution.has("quest"):
return
var quest: PlayerQuestRecord = resolution["quest"]
if resolution["completed"]:
player_quest_completed.emit(quest)
var standing := player_quest_system.standing
player_standing_changed.emit(standing)
if standing.get_tier() > _last_player_tier:
_last_player_tier = standing.get_tier()
player_tier_advanced.emit(standing.get_tier(), standing.get_tier_name())
return
player_quest_expired.emit(quest)
func try_communicate_at_shared_activity(speaker_id: int, listener_id: int) -> bool:
var speaker := _find_npc_by_id(speaker_id)
var listener := _find_npc_by_id(listener_id)
if not _can_communicate_at_shared_activity(speaker, listener):
return false
var known_event_ids := event_knowledge_system.get_communicable_event_ids(
for event_id in event_knowledge_system.get_communicable_event_ids(
speaker.id,
_get_lasting_event_ids(speaker.id),
opportunity_system.get_open_trigger_event_id()
)
for event_id in known_event_ids:
):
var event := event_log.get_by_id(event_id)
if event == null:
continue
@@ -1439,31 +1498,8 @@ func try_communicate_at_shared_activity(speaker_id: int, listener_id: int) -> bo
func _can_communicate_at_shared_activity(speaker: SimNPC, listener: SimNPC) -> bool:
if speaker == null or listener == null or speaker.id == listener.id:
return false
if speaker.is_dead or listener.is_dead:
return false
if (
speaker.task_state != SimNPC.TASK_STATE_WORKING
or listener.task_state != SimNPC.TASK_STATE_WORKING
):
return false
if speaker.target_id.is_empty() or speaker.target_id != listener.target_id:
return false
if storage_states.has(speaker.target_id):
return false
var speaker_action := SimulationDefinitions.get_action(speaker.current_task)
var listener_action := SimulationDefinitions.get_action(listener.current_task)
if (
speaker_action == null
or listener_action == null
or speaker_action.target_type != SimulationIds.TARGET_ACTIVITY
or listener_action.target_type != SimulationIds.TARGET_ACTIVITY
):
return false
return (
speaker.position.distance_squared_to(listener.position)
<= KNOWLEDGE_COMMUNICATION_RADIUS * KNOWLEDGE_COMMUNICATION_RADIUS
return EventKnowledgeSystem.can_communicate_at_shared_activity(
speaker, listener, storage_states, KNOWLEDGE_COMMUNICATION_RADIUS
)
@@ -1494,8 +1530,19 @@ func _update_opportunity_from_event(event: EconomicEventRecord) -> void:
return
if changed.get_status() == OpportunityStateRecord.STATUS_OPEN:
opportunity_opened.emit(changed)
var quest := player_quest_system.consider_opportunity_opened(
changed,
get_active_opportunity_player_response(),
tick_count,
player_quest_system.can_request_personally(changed)
)
if quest != null:
player_quest_opened.emit(quest)
return
opportunity_resolved.emit(changed, event)
_finish_quest_resolution(
player_quest_system.on_opportunity_resolved(changed, event, tick_count)
)
_maintain_event_knowledge(false)
@@ -1652,6 +1699,73 @@ func get_active_opportunity() -> OpportunityStateRecord:
return opportunity_system.get_open_opportunity()
func get_active_player_quest() -> PlayerQuestRecord:
return player_quest_system.get_active_quest()
func _advance_player_needs() -> void:
advance_player_needs()
player_needs_changed.emit(player_system.player_state)
func respawn_player() -> bool:
var state := player_system.player_state
if state == null or not state.is_dead():
return false
state.respawn()
_sync_player_combatant()
player_needs_changed.emit(state)
player_inventory_changed.emit(state)
return true
func player_eat(amount: float) -> float:
var state := player_system.player_state
var eaten := state.eat(amount) if state != null else 0.0
if eaten > 0.0:
player_needs_changed.emit(state)
return eaten
func player_gather(node: ResourceNode) -> float:
var gathered := harvest_resource_node(node)
if gathered > 0.0:
player_inventory_changed.emit(player_system.player_state)
return gathered
func player_deposit(resource_id: StringName) -> float:
var deposited := deposit_player_inventory(resource_id)
if deposited > 0.0:
village_changed.emit(village)
player_inventory_changed.emit(player_system.player_state)
return deposited
func get_player_quests() -> Array[PlayerQuestRecord]:
return player_quest_system.get_all_sorted()
func get_villager_talk(npc_id: int) -> PlayerTalkResult:
return player_negotiation.get_talk(npc_id)
func accept_villager_request(npc_id: int) -> PlayerQuestRecord:
return player_negotiation.accept_request(npc_id, tick_count)
func decline_villager_request(npc_id: int) -> PlayerQuestRecord:
return player_negotiation.decline_request(npc_id, tick_count)
func get_latest_player_quest_for_requester(requester_npc_id: int) -> PlayerQuestRecord:
return player_quest_system.get_latest_for_requester(requester_npc_id)
func get_player_standing() -> PlayerStandingRecord:
return player_quest_system.standing
func get_active_opportunity_helper() -> OpportunityHelperResult:
var active := get_active_opportunity()
if active == null:
@@ -2005,6 +2119,11 @@ func get_pantry() -> StorageStateRecord:
return economy.get_pantry()
func get_animal_display_name(animal_id: StringName) -> String:
var animal_state := animal_care.get_state(animal_id)
return animal_state.get_display_name() if animal_state != null else ""
func get_woodpile() -> StorageStateRecord:
return economy.get_woodpile()
@@ -2139,7 +2258,7 @@ func harvest_resource_node(node: ResourceNode) -> float:
if node.interaction_point != null
else node.global_position
)
_record_economic_event_at(
event_recorder.record_economic_at(
SimulationIds.EVENT_RESOURCE_EXTRACTED,
SimulationIds.PLAYER_ACTOR_ID,
resource_state.get_node_id(),
@@ -2149,7 +2268,7 @@ func harvest_resource_node(node: ResourceNode) -> float:
event_position
)
if resource_state.get_amount_remaining() <= 0.0:
_record_narrative_event_at(
event_recorder.record_narrative_at(
SimulationIds.EVENT_RESOURCE_DEPLETED,
SimulationIds.PLAYER_ACTOR_ID,
resource_state.get_node_id(),
@@ -2172,8 +2291,16 @@ func harvest_resource_node(node: ResourceNode) -> float:
func advance_player_needs() -> void:
var was_dead := player_system.player_state.is_dead()
player_system.advance_needs(village.food_modifier)
player_system.player_state.advance_health()
if not was_dead and player_system.player_state.is_dead():
player_died.emit(player_system.player_state)
player_quest_system.standing.data["standing"] = (
player_quest_system.standing.get_standing() * PlayerStateRecord.DEATH_STANDING_PENALTY
)
_last_player_tier = player_quest_system.standing.get_tier()
player_standing_changed.emit(player_quest_system.standing)
_sync_player_combatant()
@@ -2311,6 +2438,7 @@ func create_state_record() -> SimulationStateRecord:
"next_conversation_act_id": _next_conversation_act_id,
"world_id": String(event_scope["world_id"]),
"location_id": String(event_scope["location_id"]),
"next_quest_id": player_quest_system.next_quest_id,
"cycle_duration_seconds": clock.cycle_duration_seconds
}
record.village = VillageStateRecord.capture(village)
@@ -2345,6 +2473,10 @@ func create_state_record() -> SimulationStateRecord:
record.conversation_history.append(conversation_act)
record.player = player_system.player_state
conflict_system.append_state_records(record)
record.player_standing = player_quest_system.standing
for quest in player_quest_system.get_all_sorted():
record.player_quests.append(quest)
record.player_state = player_system.player_state
return record
@@ -2421,6 +2553,12 @@ func restore_state(record: SimulationStateRecord) -> bool:
_active_player_conversation = &""
_conversation_context_by_id.clear()
_dialogue_speed_index = -1
player_quest_system.restore(
record.player_quests, int(record.simulation.get("next_quest_id", 0)), record.player_standing
)
_last_player_tier = player_quest_system.standing.get_tier()
if record.player_state != null:
player_system.player_state = record.player_state
_maintain_event_knowledge(tick_count % get_knowledge_review_interval() == 0)
wander_random_sources.clear()
var wander_streams: Array = record.simulation["wander_random_streams"]
+14
View File
@@ -121,6 +121,20 @@ func get_state(animal_id: StringName) -> AnimalStateRecord:
return states.get(animal_id) as AnimalStateRecord
func get_all_states() -> Array[AnimalStateRecord]:
var all_states: Array[AnimalStateRecord] = []
for animal_id in states.keys():
var animal_state := states[animal_id] as AnimalStateRecord
if animal_state != null:
all_states.append(animal_state)
all_states.sort_custom(_sort_states_by_id)
return all_states
static func _sort_states_by_id(first: AnimalStateRecord, second: AnimalStateRecord) -> bool:
return String(first.get_animal_id()) < String(second.get_animal_id())
func reserve(animal_id: StringName, agent_id: int) -> bool:
var animal_state := get_state(animal_id)
return animal_state != null and animal_state.can_npc_feed() and animal_state.reserve(agent_id)
+1
View File
@@ -85,6 +85,7 @@ const OPPORTUNITY_RESTOCK_EMPTY_PANTRY := &"restock_empty_pantry"
const OPPORTUNITY_SUPPLY_MISSING_WOOD := &"supply_missing_wood"
const OPPORTUNITY_FEED_WEAK_VILLAGER := &"feed_weak_villager"
const OPPORTUNITY_REPAIR_HOME_ROOF := &"repair_home_roof"
const OPPORTUNITY_FEED_HUNGRY_ANIMAL := &"feed_hungry_animal"
const OPPORTUNITY_STATUS_OPEN := &"open"
const OPPORTUNITY_STATUS_RESOLVED := &"resolved"
const OPPORTUNITY_STATUS_INVALIDATED := &"invalidated"
@@ -0,0 +1,113 @@
class_name SimulationEventRecorder
extends RefCounted
const SimulationEventLogScript := preload("res://simulation/events/SimulationEventLog.gd")
var event_log: RefCounted
var npcs: Array[SimNPC] = []
var tick_provider: Callable
func configure(log: RefCounted, tick_source: Callable) -> void:
event_log = log
tick_provider = tick_source
func set_npcs(npc_list: Array[SimNPC]) -> void:
npcs = npc_list
func record_economic(
event_type: StringName,
actor_id: int,
source_id: StringName,
destination_id: StringName,
item_id: StringName,
amount: float
) -> void:
record_economic_at(
event_type,
actor_id,
source_id,
destination_id,
item_id,
amount,
get_event_world_position(actor_id, source_id, destination_id)
)
func record_economic_at(
event_type: StringName,
actor_id: int,
source_id: StringName,
destination_id: StringName,
item_id: StringName,
amount: float,
world_position: Vector3
) -> void:
event_log.record_economic(
tick_provider.call(),
event_type,
actor_id,
source_id,
destination_id,
item_id,
amount,
world_position
)
func record_narrative(
event_type: StringName,
actor_id: int,
source_id: StringName = &"",
action_display: String = "",
action_id: StringName = &"",
item_id: StringName = &"",
required_amount: float = 0.0
) -> void:
record_narrative_at(
event_type,
actor_id,
source_id,
action_display,
get_event_world_position(actor_id, source_id, &""),
action_id,
item_id,
required_amount
)
func record_narrative_at(
event_type: StringName,
actor_id: int,
source_id: StringName,
action_display: String,
world_position: Vector3,
action_id: StringName = &"",
item_id: StringName = &"",
required_amount: float = 0.0
) -> void:
event_log.record_narrative(
tick_provider.call(),
event_type,
actor_id,
source_id,
action_display,
world_position,
action_id,
item_id,
required_amount
)
func get_event_world_position(
actor_id: int, source_id: StringName, destination_id: StringName
) -> Vector3:
for npc in npcs:
if npc.id != actor_id:
continue
if not npc.target_id.is_empty() and npc.target_id in [source_id, destination_id]:
return npc.travel_target_position
return npc.position
return Vector3.ZERO
@@ -0,0 +1 @@
uid://yl07qwlrpxjs
@@ -267,6 +267,65 @@ func restore(records: Array[KnownEventStateRecord]) -> void:
known_events[_key(record.get_knower_id(), record.get_event_id())] = record
static func can_communicate_at_shared_activity(
speaker: SimNPC, listener: SimNPC, storage_states: Dictionary, radius: float
) -> bool:
if speaker == null or listener == null or speaker.id == listener.id:
return false
if speaker.is_dead or listener.is_dead:
return false
if (
speaker.task_state != SimNPC.TASK_STATE_WORKING
or listener.task_state != SimNPC.TASK_STATE_WORKING
):
return false
if speaker.target_id.is_empty() or speaker.target_id != listener.target_id:
return false
if storage_states.has(speaker.target_id):
return false
var speaker_action := SimulationDefinitions.get_action(speaker.current_task)
var listener_action := SimulationDefinitions.get_action(listener.current_task)
if (
speaker_action == null
or listener_action == null
or speaker_action.target_type != SimulationIds.TARGET_ACTIVITY
or listener_action.target_type != SimulationIds.TARGET_ACTIVITY
):
return false
return speaker.position.distance_squared_to(listener.position) <= radius * radius
func collect_lasting_records(
relationships: Array[RelationshipStateRecord], open_opportunity: OpportunityStateRecord
) -> Array[KnownEventStateRecord]:
var lasting: Array[KnownEventStateRecord] = []
var seen := {}
for relationship in relationships:
var event_id := relationship.get_last_trust_cause_event_id()
if event_id == RelationshipStateRecord.NO_CAUSE_EVENT:
continue
var record := get_record(relationship.get_observer_id(), event_id)
if record == null:
continue
var key := "%d:%d" % [record.get_knower_id(), record.get_event_id()]
if seen.has(key):
continue
seen[key] = true
lasting.append(record)
if open_opportunity != null:
var opportunity_record := get_record(
open_opportunity.get_interested_npc_id(), open_opportunity.get_trigger_event_id()
)
if opportunity_record != null:
var opportunity_key := (
"%d:%d" % [opportunity_record.get_knower_id(), opportunity_record.get_event_id()]
)
if not seen.has(opportunity_key):
seen[opportunity_key] = true
lasting.append(opportunity_record)
return lasting
func _remember(
knower_id: int,
event_id: int,
@@ -661,7 +661,10 @@ static func _is_valid_supply(
var actor_id := int(event.data["actor_id"])
if event_type == SimulationIds.EVENT_STORAGE_DEPOSITED:
if actor_id == SimulationIds.PLAYER_ACTOR_ID:
return StringName(event.data["source_id"]) == SimulationIds.PLAYER_INVENTORY_ID
return (
StringName(event.data["source_id"])
in [SimulationIds.PLAYER_INVENTORY_ID, &"player_carry"]
)
return (
_find_npc(actor_id, npcs) != null
and StringName(event.data["source_id"]) == SimulationIds.npc_inventory_id(actor_id)
@@ -14,6 +14,10 @@ func configure(economy_state: RefCounted, record_event: Callable) -> void:
func advance_needs(food_modifier: float) -> void:
player_state.set_hunger(player_state.get_hunger() + 0.125 * food_modifier)
player_state.set_energy(maxf(player_state.get_energy() - 0.0625, 0.0))
# Starvation is an authoritative state transition, not a UI-only warning.
# Reuse the record's bounded compatibility transition so save/load and the
# legacy embodied-needs slice observe the same death counter and fact state.
player_state.advance(0.0, 0.0)
func add_carried(item_id: StringName, amount: float) -> void:
+117
View File
@@ -0,0 +1,117 @@
class_name PlayerNeedsSystem
extends RefCounted
var state := PlayerStateRecord.create()
var economy: RefCounted
var event_recorder: RefCounted
var resource_states: Dictionary = {}
func configure(economy_service: RefCounted, recorder: RefCounted) -> void:
economy = economy_service
event_recorder = recorder
func set_resource_states(states: Dictionary) -> void:
resource_states = states
func advance(village: SimVillage) -> bool:
if state.is_dead():
return false
var hunger_rate := 0.125 * village.food_modifier
if state.advance(hunger_rate, 0.5):
state.die()
return true
return false
func eat(amount: float) -> float:
return state.eat(amount)
func gather_node(node: ResourceNode) -> float:
if node == null:
return 0.0
var resource_state := resource_states.get(node.node_id) as ResourceStateRecord
if resource_state == null or not resource_state.can_player_use_resource():
return 0.0
var available := state.get_available_carry()
if available <= 0.0:
return 0.0
var extracted := resource_state.extract(minf(resource_state.get_yield_per_action(), available))
if extracted <= 0.0:
return 0.0
var carried := state.add_inventory(resource_state.get_resource_id(), extracted)
if carried <= 0.0:
resource_state.data["amount_remaining"] = (
resource_state.get_amount_remaining() + extracted
)
return 0.0
var event_position := (
node.interaction_point.global_position
if node.interaction_point != null
else node.global_position
)
event_recorder.record_economic_at(
SimulationIds.EVENT_RESOURCE_EXTRACTED,
-1,
resource_state.get_node_id(),
&"player_carry",
resource_state.get_resource_id(),
carried,
event_position
)
if resource_state.get_amount_remaining() <= 0.0:
event_recorder.record_narrative_at(
SimulationIds.EVENT_RESOURCE_DEPLETED,
-1,
resource_state.get_node_id(),
"",
event_position
)
return carried
func deposit_resource(resource_id: StringName) -> float:
if resource_id.is_empty():
return 0.0
var carried := state.get_inventory_amount(resource_id)
if carried <= 0.0:
return 0.0
if economy == null or not economy.has_method("get_storage_for_resource"):
return 0.0
var storage: StorageStateRecord = economy.get_storage_for_resource(resource_id)
if storage == null:
return 0.0
var deposited: float = economy.deposit_resource(resource_id, carried)
if deposited <= 0.0:
return 0.0
state.remove_inventory(resource_id, deposited)
event_recorder.record_economic(
SimulationIds.EVENT_STORAGE_DEPOSITED,
-1,
&"player_carry",
storage.get_storage_id(),
resource_id,
deposited
)
return deposited
func get_carried_amount(item_id: StringName) -> float:
return state.get_inventory_amount(item_id)
func respawn() -> void:
if state.is_dead():
state.respawn()
func apply_death_consequence(standing: PlayerStandingRecord) -> void:
var reduced := standing.get_standing() * PlayerStateRecord.DEATH_STANDING_PENALTY
standing.data["standing"] = reduced
func restore(record: PlayerStateRecord) -> void:
state = record if record != null else PlayerStateRecord.create()
@@ -0,0 +1 @@
uid://brf3a7drbfs7
@@ -0,0 +1,67 @@
class_name PlayerNegotiationSystem
extends RefCounted
var quest_system: PlayerQuestSystem
var npc_lookup: Callable
var opportunity_provider: Callable
var player_response_provider: Callable
var quest_opened_signal: Signal
var quest_expired_signal: Signal
var standing_changed_signal: Signal
func configure(
quests: PlayerQuestSystem,
lookup: Callable,
opportunity_source: Callable,
response_source: Callable,
opened: Signal,
expired: Signal,
standing: Signal
) -> void:
quest_system = quests
npc_lookup = lookup
opportunity_provider = opportunity_source
player_response_provider = response_source
quest_opened_signal = opened
quest_expired_signal = expired
standing_changed_signal = standing
func get_talk(npc_id: int) -> PlayerTalkResult:
var npc := npc_lookup.call(npc_id) as SimNPC
if npc == null or npc.is_dead:
return null
return quest_system.get_talk_for_requester(npc.id, npc.npc_name, opportunity_provider.call())
func accept_request(npc_id: int, current_tick: int) -> PlayerQuestRecord:
var npc := npc_lookup.call(npc_id) as SimNPC
if npc == null:
return null
var opportunity: OpportunityStateRecord = opportunity_provider.call()
if opportunity == null or opportunity.get_interested_npc_id() != npc.id:
return null
var result: Dictionary = quest_system.accept_opportunity_quest(
opportunity, player_response_provider.call(), current_tick
)
var quest := result.get("quest") as PlayerQuestRecord
if quest != null and result.get("created", false) and not quest_opened_signal.is_null():
quest_opened_signal.emit(quest)
return quest
func decline_request(npc_id: int, current_tick: int) -> PlayerQuestRecord:
var npc := npc_lookup.call(npc_id) as SimNPC
if npc == null:
return null
var opportunity: OpportunityStateRecord = opportunity_provider.call()
if opportunity == null or opportunity.get_interested_npc_id() != npc.id:
return null
var quest := quest_system.decline_opportunity_quest(opportunity, current_tick)
if quest != null:
if not quest_expired_signal.is_null():
quest_expired_signal.emit(quest)
if not standing_changed_signal.is_null():
standing_changed_signal.emit(quest_system.standing)
return quest
@@ -0,0 +1 @@
uid://7oayv5ga327o
+283
View File
@@ -0,0 +1,283 @@
class_name PlayerQuestSystem
extends RefCounted
const PANTRY_STANDING_REWARD := 8.0
const WOOD_STANDING_REWARD := 8.0
const ANIMAL_CARE_STANDING_REWARD := 6.0
const PERSONAL_TRUST_THRESHOLD := 0.5
const MIN_PERSONAL_REQUEST_TIER := PlayerStandingRecord.TIER_KNOWN_HAND
var quests: Array[PlayerQuestRecord] = []
var next_quest_id := 0
var standing := PlayerStandingRecord.create()
func consider_animal_care(
animal_state: AnimalStateRecord,
requester_npc_id: int,
current_tick: int,
pantry: StorageStateRecord
) -> PlayerQuestRecord:
if (
animal_state == null
or requester_npc_id < 0
or current_tick < 0
or pantry == null
or not animal_state.needs_feed()
or not animal_state.can_player_feed_animal()
):
return null
var definition := SimulationDefinitions.get_action(SimulationIds.ACTION_FEED_ANIMAL)
if (
definition == null
or not definition.has_completion_cost()
or (
pantry.get_amount(definition.completion_cost_resource_id)
< definition.completion_cost_amount
)
):
return null
if _find_open_quest_for_animal(animal_state.get_animal_id()) != null:
return null
var quest := PlayerQuestRecord.create(
next_quest_id,
PlayerQuestRecord.NO_OPPORTUNITY,
requester_npc_id,
SimulationIds.OPPORTUNITY_FEED_HUNGRY_ANIMAL,
definition.completion_cost_resource_id,
animal_state.get_animal_id(),
definition.completion_cost_amount,
current_tick,
ANIMAL_CARE_STANDING_REWARD,
animal_state.get_animal_id()
)
next_quest_id += 1
quests.append(quest)
return quest
func on_animal_fed(
animal_state: AnimalStateRecord, resolution_event: EconomicEventRecord, current_tick: int
) -> Dictionary:
if animal_state == null or resolution_event == null:
return {}
var quest := _find_open_quest_for_animal(animal_state.get_animal_id())
if quest == null:
return {}
var event_id := int(resolution_event.data["event_id"])
var actor_id := int(resolution_event.data["actor_id"])
if actor_id < 0:
if not quest.complete(event_id, current_tick):
return {}
standing.grant_standing(quest.get_standing_reward(), quest.get_requester_npc_id())
return {"quest": quest, "completed": true}
if quest.expire(current_tick):
return {"quest": quest, "completed": false}
return {}
func consider_opportunity_opened(
opportunity: OpportunityStateRecord,
player_response: OpportunityPlayerResponseResult,
current_tick: int,
personal_request_eligible := false
) -> PlayerQuestRecord:
if opportunity == null or not opportunity.is_open() or current_tick < 0:
return null
if player_response == null and not personal_request_eligible:
return null
if _find_open_quest_for_opportunity(opportunity.get_opportunity_id()) != null:
return null
var reward := _standing_reward_for(opportunity)
if reward <= 0.0:
return null
var quest := PlayerQuestRecord.create(
next_quest_id,
opportunity.get_opportunity_id(),
opportunity.get_interested_npc_id(),
opportunity.get_opportunity_type(),
opportunity.get_resource_id(),
opportunity.get_target_id(),
opportunity.get_target_amount(),
current_tick,
reward
)
next_quest_id += 1
quests.append(quest)
return quest
func can_request_personally(opportunity: OpportunityStateRecord) -> bool:
if (
opportunity == null
or not opportunity.is_open()
or standing.get_tier() < MIN_PERSONAL_REQUEST_TIER
):
return false
return standing.get_gratitude(opportunity.get_interested_npc_id()) >= PERSONAL_TRUST_THRESHOLD
func on_opportunity_resolved(
opportunity: OpportunityStateRecord, resolution_event: EconomicEventRecord, current_tick: int
) -> Dictionary:
var quest := _find_open_quest_for_opportunity(opportunity.get_opportunity_id())
if quest == null or resolution_event == null:
return {}
var event_id := int(resolution_event.data["event_id"])
var actor_id := int(resolution_event.data["actor_id"])
if actor_id < 0:
if not quest.complete(event_id, current_tick):
return {}
standing.grant_standing(quest.get_standing_reward(), quest.get_requester_npc_id())
return {"quest": quest, "completed": true}
if quest.expire(current_tick):
return {"quest": quest, "completed": false}
return {}
func get_talk_for_requester(
requester_id: int, requester_name: String, opportunity: OpportunityStateRecord
) -> PlayerTalkResult:
var has_need := opportunity != null and opportunity.is_open()
var need_text := ""
if has_need:
need_text = "I'm worried about the %s." % String(opportunity.get_resource_id()).capitalize()
var quest := get_latest_for_requester(requester_id)
var quest_available := quest != null and quest.is_open()
var reward := quest.get_standing_reward() if quest_available else 0.0
var can_accept := has_need and (quest_available or can_request_personally(opportunity))
return PlayerTalkResult.new(
requester_id,
requester_name,
"%s greets you." % requester_name,
has_need,
need_text,
quest_available,
reward,
can_accept,
has_need
)
func accept_opportunity_quest(
opportunity: OpportunityStateRecord,
player_response: OpportunityPlayerResponseResult,
current_tick: int
) -> Dictionary:
var existing := _find_open_quest_for_opportunity(opportunity.get_opportunity_id())
if existing != null:
return {"quest": existing, "created": false}
var created := consider_opportunity_opened(
opportunity, player_response, current_tick, can_request_personally(opportunity)
)
return {"quest": created, "created": created != null}
func decline_opportunity_quest(
opportunity: OpportunityStateRecord, current_tick: int
) -> PlayerQuestRecord:
var quest := _find_open_quest_for_opportunity(opportunity.get_opportunity_id())
if quest == null:
return null
if not quest.expire(current_tick):
return null
var requester_id := quest.get_requester_npc_id()
var gratitude := standing.get_gratitude(requester_id)
standing.data["gratitude"][requester_id] = maxf(gratitude - 0.1, 0.0)
return quest
func on_opportunity_invalidated(
opportunity: OpportunityStateRecord, current_tick: int
) -> PlayerQuestRecord:
var quest := _find_open_quest_for_opportunity(opportunity.get_opportunity_id())
if quest == null:
return null
if quest.expire(current_tick):
return quest
return null
func consider_animal_care_quests(
animal_care: AnimalCareSystem,
npcs: Array[SimNPC],
pantry: StorageStateRecord,
current_tick: int
) -> Array[PlayerQuestRecord]:
var opened: Array[PlayerQuestRecord] = []
for animal_state in animal_care.get_all_states():
var requester := _nearest_npc_id(animal_state.get_position(), npcs)
var quest := consider_animal_care(animal_state, requester, current_tick, pantry)
if quest != null:
opened.append(quest)
return opened
static func _nearest_npc_id(from_position: Vector3, npcs: Array[SimNPC]) -> int:
var nearest_id := -1
var nearest_distance := INF
for npc in npcs:
if npc.is_dead:
continue
var distance := npc.position.distance_squared_to(from_position)
if distance < nearest_distance:
nearest_distance = distance
nearest_id = npc.id
return nearest_id
func get_active_quest() -> PlayerQuestRecord:
for quest in quests:
if quest.is_open():
return quest
return null
func get_all_sorted() -> Array[PlayerQuestRecord]:
var sorted := quests.duplicate()
sorted.sort_custom(_sort_by_id)
return sorted
func get_latest_for_requester(requester_npc_id: int) -> PlayerQuestRecord:
for index in range(quests.size() - 1, -1, -1):
var quest := quests[index]
if quest.get_requester_npc_id() == requester_npc_id:
return quest
return null
func restore(
records: Array[PlayerQuestRecord], restored_next_id: int, standing_record: PlayerStandingRecord
) -> void:
quests = records.duplicate()
quests.sort_custom(_sort_by_id)
next_quest_id = maxi(restored_next_id, 0)
standing = standing_record if standing_record != null else PlayerStandingRecord.create()
func _find_open_quest_for_opportunity(opportunity_id: int) -> PlayerQuestRecord:
for quest in quests:
if quest.is_open() and quest.get_opportunity_id() == opportunity_id:
return quest
return null
func _find_open_quest_for_animal(animal_id: StringName) -> PlayerQuestRecord:
for quest in quests:
if quest.is_open() and quest.has_animal_target() and quest.get_animal_id() == animal_id:
return quest
return null
func _standing_reward_for(opportunity: OpportunityStateRecord) -> float:
match opportunity.get_opportunity_type():
SimulationIds.OPPORTUNITY_RESTOCK_EMPTY_PANTRY:
return PANTRY_STANDING_REWARD
SimulationIds.OPPORTUNITY_SUPPLY_MISSING_WOOD:
return WOOD_STANDING_REWARD
return 0.0
static func _sort_by_id(first: PlayerQuestRecord, second: PlayerQuestRecord) -> bool:
return first.get_quest_id() < second.get_quest_id()
@@ -0,0 +1 @@
uid://cojertujqx8ts
+224
View File
@@ -0,0 +1,224 @@
class_name PlayerQuestRecord
extends RefCounted
const SCHEMA_VERSION := 2
const LEGACY_SCHEMA_VERSION := 1
const STATUS_OPEN := &"open"
const STATUS_COMPLETED := &"completed"
const STATUS_EXPIRED := &"expired"
const NO_OPPORTUNITY := -1
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func create(
quest_id: int,
opportunity_id: int,
requester_npc_id: int,
quest_type: StringName,
resource_id: StringName,
target_id: StringName,
target_amount: float,
created_tick: int,
standing_reward: float,
animal_id: StringName = &""
) -> PlayerQuestRecord:
return (
PlayerQuestRecord
. new(
{
"schema_version": SCHEMA_VERSION,
"quest_id": quest_id,
"opportunity_id": opportunity_id,
"requester_npc_id": requester_npc_id,
"quest_type": String(quest_type),
"resource_id": String(resource_id),
"target_id": String(target_id),
"target_amount": target_amount,
"status": String(STATUS_OPEN),
"created_tick": created_tick,
"standing_reward": standing_reward,
"resolution_event_id": -1,
"resolved_tick": -1,
"animal_id": String(animal_id),
}
)
)
static func from_dictionary(record_data: Dictionary) -> PlayerQuestRecord:
var version := int(record_data.get("schema_version", -1))
if version not in [LEGACY_SCHEMA_VERSION, SCHEMA_VERSION]:
return null
var normalized := record_data.duplicate(true)
if version == LEGACY_SCHEMA_VERSION:
normalized["schema_version"] = SCHEMA_VERSION
normalized["animal_id"] = ""
if not (
normalized
. has_all(
[
"quest_id",
"opportunity_id",
"requester_npc_id",
"quest_type",
"resource_id",
"target_id",
"target_amount",
"status",
"created_tick",
"standing_reward",
"resolution_event_id",
"resolved_tick",
"animal_id",
]
)
):
return null
var quest_id := int(normalized["quest_id"])
var opportunity_id := int(normalized["opportunity_id"])
var requester_npc_id := int(normalized["requester_npc_id"])
var quest_type := StringName(normalized["quest_type"])
var resource_id := StringName(normalized["resource_id"])
var target_id := StringName(normalized["target_id"])
var target_amount := float(normalized["target_amount"])
var status := StringName(normalized["status"])
var created_tick := int(normalized["created_tick"])
var standing_reward := float(normalized["standing_reward"])
var resolution_event_id := int(normalized["resolution_event_id"])
var resolved_tick := int(normalized["resolved_tick"])
var animal_id := StringName(normalized["animal_id"])
if (
quest_id < 0
or requester_npc_id < 0
or quest_type.is_empty()
or resource_id.is_empty()
or target_id.is_empty()
or not is_finite(target_amount)
or target_amount <= 0.0
or created_tick < 0
or not is_finite(standing_reward)
or standing_reward <= 0.0
or resolution_event_id < -1
or (opportunity_id < 0 and animal_id.is_empty())
or (not animal_id.is_empty() and opportunity_id != NO_OPPORTUNITY)
):
return null
match status:
STATUS_OPEN:
if resolution_event_id != -1 or resolved_tick != -1:
return null
STATUS_COMPLETED:
if resolution_event_id < 0 or resolved_tick < created_tick:
return null
STATUS_EXPIRED:
if resolution_event_id != -1 or resolved_tick < created_tick:
return null
_:
return null
return (
PlayerQuestRecord
. new(
{
"schema_version": SCHEMA_VERSION,
"quest_id": quest_id,
"opportunity_id": opportunity_id,
"requester_npc_id": requester_npc_id,
"quest_type": String(quest_type),
"resource_id": String(resource_id),
"target_id": String(target_id),
"target_amount": target_amount,
"status": String(status),
"created_tick": created_tick,
"standing_reward": standing_reward,
"resolution_event_id": resolution_event_id,
"resolved_tick": resolved_tick,
"animal_id": String(animal_id),
}
)
)
func get_quest_id() -> int:
return int(data["quest_id"])
func get_opportunity_id() -> int:
return int(data["opportunity_id"])
func get_requester_npc_id() -> int:
return int(data["requester_npc_id"])
func get_quest_type() -> StringName:
return StringName(data["quest_type"])
func get_resource_id() -> StringName:
return StringName(data["resource_id"])
func get_target_id() -> StringName:
return StringName(data["target_id"])
func get_target_amount() -> float:
return float(data["target_amount"])
func get_status() -> StringName:
return StringName(data["status"])
func get_created_tick() -> int:
return int(data["created_tick"])
func get_standing_reward() -> float:
return float(data["standing_reward"])
func get_resolution_event_id() -> int:
return int(data["resolution_event_id"])
func get_resolved_tick() -> int:
return int(data["resolved_tick"])
func get_animal_id() -> StringName:
return StringName(data["animal_id"])
func has_animal_target() -> bool:
return not get_animal_id().is_empty()
func is_open() -> bool:
return get_status() == STATUS_OPEN
func complete(resolution_event_id: int, resolved_tick: int) -> bool:
if not is_open() or resolution_event_id < 0 or resolved_tick < get_created_tick():
return false
data["status"] = String(STATUS_COMPLETED)
data["resolution_event_id"] = resolution_event_id
data["resolved_tick"] = resolved_tick
return true
func expire(resolved_tick: int) -> bool:
if not is_open() or resolved_tick < get_created_tick():
return false
data["status"] = String(STATUS_EXPIRED)
data["resolved_tick"] = resolved_tick
return true
func to_dictionary() -> Dictionary:
return data.duplicate(true)
@@ -0,0 +1 @@
uid://rix0e3rygdoo
+120
View File
@@ -0,0 +1,120 @@
class_name PlayerStandingRecord
extends RefCounted
const SCHEMA_VERSION := 1
const MAX_STANDING := 100.0
const TIER_STRANGER := 0
const TIER_KNOWN_HAND := 1
const TIER_TRUSTED := 2
const TIER_VILLAGE_STEWARD := 3
const TIER_VOICE_OF_JAJCE := 4
const TIER_THRESHOLDS := {
TIER_STRANGER: 0.0,
TIER_KNOWN_HAND: 15.0,
TIER_TRUSTED: 35.0,
TIER_VILLAGE_STEWARD: 60.0,
TIER_VOICE_OF_JAJCE: 85.0,
}
const TIER_NAMES := {
TIER_STRANGER: "Stranger",
TIER_KNOWN_HAND: "Known Hand",
TIER_TRUSTED: "Trusted",
TIER_VILLAGE_STEWARD: "Village Steward",
TIER_VOICE_OF_JAJCE: "Voice of Jajce",
}
var data: Dictionary
func _init(record_data: Dictionary = {}) -> void:
data = record_data.duplicate(true)
static func create() -> PlayerStandingRecord:
return (
PlayerStandingRecord
. new(
{
"schema_version": SCHEMA_VERSION,
"standing": 0.0,
"resolved_needs": 0,
"gratitude": {},
}
)
)
static func from_dictionary(record_data: Dictionary) -> PlayerStandingRecord:
if int(record_data.get("schema_version", -1)) != SCHEMA_VERSION:
return null
if not record_data.has_all(["standing", "resolved_needs", "gratitude"]):
return null
var standing := float(record_data["standing"])
var resolved_needs := int(record_data["resolved_needs"])
var gratitude = record_data["gratitude"]
if (
not is_finite(standing)
or standing < 0.0
or standing > MAX_STANDING
or resolved_needs < 0
or not gratitude is Dictionary
):
return null
var normalized_gratitude := {}
for raw_npc_id in gratitude:
var npc_id := int(raw_npc_id)
var value := float(gratitude[raw_npc_id])
if npc_id < 0 or not is_finite(value) or value < 0.0 or value > 1.0:
return null
normalized_gratitude[npc_id] = value
return (
PlayerStandingRecord
. new(
{
"schema_version": SCHEMA_VERSION,
"standing": standing,
"resolved_needs": resolved_needs,
"gratitude": normalized_gratitude,
}
)
)
func grant_standing(amount: float, requester_npc_id: int) -> void:
if not is_finite(amount) or amount <= 0.0 or requester_npc_id < 0:
return
data["standing"] = minf(get_standing() + amount, MAX_STANDING)
data["resolved_needs"] = int(data["resolved_needs"]) + 1
var gratitude := get_gratitude(requester_npc_id)
data["gratitude"][requester_npc_id] = minf(gratitude + 0.1, 1.0)
func get_standing() -> float:
return float(data["standing"])
func get_resolved_needs() -> int:
return int(data["resolved_needs"])
func get_gratitude(npc_id: int) -> float:
return float(data["gratitude"].get(npc_id, 0.0))
func get_tier() -> int:
var current := TIER_STRANGER
for tier in [TIER_VOICE_OF_JAJCE, TIER_VILLAGE_STEWARD, TIER_TRUSTED, TIER_KNOWN_HAND]:
if get_standing() >= float(TIER_THRESHOLDS[tier]):
current = tier
break
return current
func get_tier_name() -> String:
return String(TIER_NAMES[get_tier()])
func to_dictionary() -> Dictionary:
return data.duplicate(true)
@@ -0,0 +1 @@
uid://v827brnqruus
+97 -2
View File
@@ -19,6 +19,8 @@ const CONFLICT_SCHEMA_VERSION := 13
const PRE_EMERGENT_SCHEMA_VERSION := 14
const EMERGENT_SCHEMA_VERSION := 15
const PREVIOUS_SCHEMA_VERSION := 7
const PLAYER_LEGACY_SCHEMA_VERSION := 11
const PLAYER_STATE_LEGACY_SCHEMA_VERSION := 12
var simulation: Dictionary
var village: VillageStateRecord
@@ -37,6 +39,9 @@ var conversation_history: Array[ConversationActStateRecord] = []
var player: PlayerStateRecord
var combatants: Array[CombatantStateRecord] = []
var factions: Array[FactionStateRecord] = []
var player_standing: PlayerStandingRecord
var player_quests: Array[PlayerQuestRecord] = []
var player_state: PlayerStateRecord
func to_dictionary() -> Dictionary:
@@ -83,6 +88,9 @@ func to_dictionary() -> Dictionary:
var faction_data: Array[Dictionary] = []
for faction_record in factions:
faction_data.append(faction_record.to_dictionary())
var player_quest_data: Array[Dictionary] = []
for player_quest_record in player_quests:
player_quest_data.append(player_quest_record.to_dictionary())
return {
"schema": SCHEMA_NAME,
@@ -103,7 +111,10 @@ func to_dictionary() -> Dictionary:
"conversation_history": conversation_history_data,
"player": player.to_dictionary(),
"combatants": combatant_data,
"factions": faction_data
"factions": faction_data,
"player_standing": player_standing.to_dictionary(),
"player_quests": player_quest_data,
"player_state": player_state.to_dictionary()
}
@@ -140,6 +151,8 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
CONFLICT_SCHEMA_VERSION,
PRE_EMERGENT_SCHEMA_VERSION,
EMERGENT_SCHEMA_VERSION,
PLAYER_LEGACY_SCHEMA_VERSION,
PLAYER_STATE_LEGACY_SCHEMA_VERSION,
]
):
record_data = _migrate_legacy(record_data, version)
@@ -166,6 +179,9 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
"player",
"combatants",
"factions",
"player_standing",
"player_quests",
"player_state",
]
)
):
@@ -551,6 +567,7 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
record.relationships.append(relationship_record)
var opportunity_ids := {}
var opportunity_records_by_id := {}
var trigger_event_ids := {}
var resolution_event_ids := {}
var has_open_opportunity := false
@@ -585,6 +602,7 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
):
return null
opportunity_ids[opportunity_id] = true
opportunity_records_by_id[opportunity_id] = opportunity_record
trigger_event_ids[trigger_event_id] = true
highest_opportunity_id = maxi(highest_opportunity_id, opportunity_id)
record.opportunities.append(opportunity_record)
@@ -620,6 +638,72 @@ static func from_dictionary(record_data: Dictionary) -> SimulationStateRecord:
record.conversation_history.append(conversation_act)
if saved_next_conversation_act_id <= highest_conversation_act_id:
return null
var standing_data = record_data["player_standing"]
if not standing_data is Dictionary:
return null
var standing_record := PlayerStandingRecord.from_dictionary(standing_data)
if standing_record == null:
return null
record.player_standing = standing_record
var player_quest_data = record_data["player_quests"]
if not player_quest_data is Array:
return null
var quest_ids := {}
var quest_opportunity_ids := {}
var highest_quest_id := -1
for item in player_quest_data:
if not item is Dictionary:
return null
var quest_record := PlayerQuestRecord.from_dictionary(item)
if quest_record == null:
return null
var quest_id := quest_record.get_quest_id()
var quest_opportunity_id := quest_record.get_opportunity_id()
var requester_id := quest_record.get_requester_npc_id()
var has_valid_requester := npc_ids.has(requester_id)
var has_valid_opportunity := (
quest_record.has_animal_target() or opportunity_ids.has(quest_opportunity_id)
)
if (
quest_ids.has(quest_id)
or quest_opportunity_ids.has(quest_opportunity_id)
or not has_valid_requester
or not has_valid_opportunity
):
return null
if (
quest_record.get_status() == PlayerQuestRecord.STATUS_OPEN
and (
(not quest_record.has_animal_target())
and not opportunity_records_by_id.has(quest_opportunity_id)
)
):
return null
if (
quest_record.get_resolution_event_id() >= 0
and not event_ids.has(quest_record.get_resolution_event_id())
):
return null
var dedup_key := (
"animal:%s" % String(quest_record.get_animal_id())
if quest_record.has_animal_target()
else "opp:%d" % quest_opportunity_id
)
if quest_ids.has(quest_id) or quest_opportunity_ids.has(dedup_key):
return null
quest_ids[quest_id] = true
quest_opportunity_ids[dedup_key] = true
highest_quest_id = maxi(highest_quest_id, quest_id)
record.player_quests.append(quest_record)
var player_state_data = record_data["player_state"]
if not player_state_data is Dictionary:
return null
var player_state_record := PlayerStateRecord.from_dictionary(player_state_data)
if player_state_record == null:
return null
record.player_state = player_state_record
return record
@@ -940,7 +1024,10 @@ static func _is_valid_supply_resolution(
return false
if event_type == SimulationIds.EVENT_STORAGE_DEPOSITED:
if actor_id == SimulationIds.PLAYER_ACTOR_ID:
return StringName(event.data["source_id"]) == SimulationIds.PLAYER_INVENTORY_ID
return (
StringName(event.data["source_id"])
in [SimulationIds.PLAYER_INVENTORY_ID, &"player_carry"]
)
return (
npc_ids.has(actor_id)
and StringName(event.data["source_id"]) == SimulationIds.npc_inventory_id(actor_id)
@@ -1066,6 +1153,14 @@ static func _migrate_legacy(legacy_data: Dictionary, version: int) -> Dictionary
var opportunity_simulation_data: Dictionary = migrated.get("simulation", {})
opportunity_simulation_data["next_opportunity_id"] = 0
migrated["simulation"] = opportunity_simulation_data
if version <= PLAYER_LEGACY_SCHEMA_VERSION:
migrated["player_standing"] = PlayerStandingRecord.create().to_dictionary()
migrated["player_quests"] = []
var quest_simulation_data: Dictionary = migrated.get("simulation", {})
quest_simulation_data["next_quest_id"] = 0
migrated["simulation"] = quest_simulation_data
if version <= PLAYER_STATE_LEGACY_SCHEMA_VERSION:
migrated["player_state"] = PlayerStateRecord.create().to_dictionary()
return migrated
+106 -5
View File
@@ -4,6 +4,12 @@ extends RefCounted
const SCHEMA_VERSION := 2
const LEGACY_SCHEMA_VERSION := 1
const MAX_HEALTH := 100.0
const RESET_HUNGER := 40.0
const RESET_ENERGY := 100.0
const STACK_THRESHOLD := 80.0
const DEATH_STANDING_PENALTY := 0.85
const DEFAULT_STARVATION_DEATH_THRESHOLD := 1
const DEFAULT_CARRY_CAPACITY := 3.0
var data: Dictionary
@@ -18,18 +24,30 @@ static func create_default() -> PlayerStateRecord:
. new(
{
"schema_version": SCHEMA_VERSION,
"hunger": 40.0,
"energy": 100.0,
"hunger": RESET_HUNGER,
"energy": RESET_ENERGY,
"health": MAX_HEALTH,
"max_health": MAX_HEALTH,
"downed": false,
"downed_ticks": 0,
"dead": false,
"deaths": 0,
"starvation_ticks": 0,
"starvation_death_threshold": DEFAULT_STARVATION_DEATH_THRESHOLD,
"carry_capacity": DEFAULT_CARRY_CAPACITY,
"inventory": {},
}
)
)
# Compatibility constructor for the first embodied-player slice. New code
# should use create_default(), but keeping this alias lets older quest/needs
# resources load without introducing a second player-state schema.
static func create() -> PlayerStateRecord:
return create_default()
static func from_dictionary(record_data: Dictionary) -> PlayerStateRecord:
var version := int(record_data.get("schema_version", -1))
if version == LEGACY_SCHEMA_VERSION:
@@ -76,6 +94,20 @@ static func from_dictionary(record_data: Dictionary) -> PlayerStateRecord:
"max_health": max_health,
"downed": bool(record_data["downed"]),
"downed_ticks": int(record_data["downed_ticks"]),
"dead": bool(record_data.get("dead", false)),
"deaths": maxi(int(record_data.get("deaths", 0)), 0),
"starvation_ticks": maxi(int(record_data.get("starvation_ticks", 0)), 0),
"starvation_death_threshold":
maxi(
int(
record_data.get(
"starvation_death_threshold", DEFAULT_STARVATION_DEATH_THRESHOLD
)
),
1
),
"carry_capacity":
maxf(float(record_data.get("carry_capacity", DEFAULT_CARRY_CAPACITY)), 0.0),
"inventory": normalized_inventory,
}
)
@@ -89,6 +121,11 @@ static func _migrate_v1(legacy_data: Dictionary) -> Dictionary:
migrated["max_health"] = MAX_HEALTH
migrated["downed"] = false
migrated["downed_ticks"] = 0
migrated["dead"] = false
migrated["deaths"] = 0
migrated["starvation_ticks"] = 0
migrated["starvation_death_threshold"] = DEFAULT_STARVATION_DEATH_THRESHOLD
migrated["carry_capacity"] = DEFAULT_CARRY_CAPACITY
return migrated
@@ -112,6 +149,18 @@ func is_downed() -> bool:
return bool(data["downed"])
func is_dead() -> bool:
return bool(data.get("dead", false))
func is_starving() -> bool:
return get_hunger() >= STACK_THRESHOLD and not is_dead()
func get_deaths() -> int:
return maxi(int(data.get("deaths", 0)), 0)
func get_downed_ticks() -> int:
return int(data["downed_ticks"])
@@ -124,6 +173,54 @@ func set_energy(amount: float) -> void:
data["energy"] = clampf(amount, 0.0, 100.0)
func advance(hunger_rate: float, energy_drain: float) -> bool:
if is_dead():
return true
set_hunger(get_hunger() + maxf(hunger_rate, 0.0))
set_energy(get_energy() - maxf(energy_drain, 0.0))
if get_hunger() < STACK_THRESHOLD:
data["starvation_ticks"] = 0
return false
data["starvation_ticks"] = int(data.get("starvation_ticks", 0)) + 1
if int(data["starvation_ticks"]) >= int(data.get("starvation_death_threshold", 1)):
die()
return true
return false
func eat(amount: float) -> float:
if not is_finite(amount) or amount <= 0.0 or is_dead():
return 0.0
var consumed := minf(amount, get_hunger())
set_hunger(get_hunger() - consumed)
set_energy(get_energy() + consumed * 0.5)
data["starvation_ticks"] = 0
return consumed
func die() -> void:
if is_dead():
return
data["dead"] = true
data["deaths"] = get_deaths() + 1
func respawn() -> void:
data["dead"] = false
data["downed"] = false
data["downed_ticks"] = 0
data["hunger"] = RESET_HUNGER
data["energy"] = RESET_ENERGY
data["health"] = get_max_health()
data["starvation_ticks"] = 0
func get_available_carry() -> float:
return maxf(
float(data.get("carry_capacity", DEFAULT_CARRY_CAPACITY)) - get_carried_total(), 0.0
)
func take_damage(amount: float) -> float:
if not is_finite(amount) or amount <= 0.0 or is_downed():
return 0.0
@@ -157,10 +254,14 @@ func get_carried_total() -> float:
return total
func add_inventory(item_id: StringName, amount: float) -> void:
func add_inventory(item_id: StringName, amount: float) -> float:
if item_id.is_empty() or not is_finite(amount) or amount <= 0.0:
return
data["inventory"][String(item_id)] = get_inventory_amount(item_id) + amount
return 0.0
var added := minf(amount, get_available_carry())
if added <= 0.0:
return 0.0
data["inventory"][String(item_id)] = get_inventory_amount(item_id) + added
return added
func remove_inventory(item_id: StringName, requested_amount: float) -> float: