70 Commits

Author SHA1 Message Date
dobbry-vechur 5c21b4c359 Set minus thirty Celsius in NPC cold weather tests
- -30_C negates an absolute temperature and gives -303.15 K, far below minus thirty Celsius
- use units::from_celsius( -30 ) in the behavior tree score test and four preemption sections
2026-10-31 02:09:36 +04:00
dobbry-vechur 5f669eb1e7 The warmth need is named temperature regulation
- need, goal, executor, plan use temperature name
- behavior tree nodes, predicates and test goals use the same name
2026-10-25 10:41:21 +04:00
dobbry-vechur c5d03ec220 NPCs light fires only in a hearth
- fire goes only in a hearth: fireplace, stove, brazier, fire ring or clay oven
- fuel is the NPC's own burnable firewood, or firewood or tinder in the hearth it may use
- a hearth that is a firewood pile, busy, off-limits, unburnable or full is skipped
2026-10-23 23:05:42 +04:00
dobbry-vechur d64b0ea995 Camp resident goal test crosses a real overmap tile boundary 2026-10-18 06:47:19 +04:00
dobbry-vechur e2cbe75164 Followers and guards sleep only where their obligations allow
- sleep search stays inside the reach and skips spots the NPC may not use
- the npc_sleep action asks the same permission as the behavior tree
- an NPC that sleeps past an obligation says so
- a failed sleep search pauses sleep a minute unless something changes
2026-10-13 17:45:17 +04:00
RenechCDDA da2aaffffd Add quick setup option to clear map 2026-06-22 15:07:51 -04:00
dumb-kevin 7ad1c6a114 NPC: wait while player is in a moving vehicle
- added player_moving_vehicle helper in oracle
- gated npc_is_following on moving-vehicle check
- gated npc_should_embark on moving-vehicle check
- paused npc_follow_embarked dispatch when vehicle moves
- added vehicle yield integration test
2026-04-27 00:37:17 +04:00
dumb-kevin 28b79d5c9c NPC: move follow_embarked into BT, drop cascade follow duplicates
- added npc_should_embark predicate and npc_embark_urgency score
- added npc_follow_embarked node under npc_priorities
- routed follow_embarked through BT dispatch and goal commitment
- mapped follow_embarked to decision_category::follow
- removed cascade duplicates for goto_to_this_pos, follow_embarked, follow_player
- gated combat hook on passive actions, is_following, and same-vehicle
2026-04-26 23:54:56 +04:00
dumb-kevin 693c472c54 NPC: split follower state from spacing rule, suppress duty under follow
- replace should_follow_close with can_follow_player_now and desired_follow_radius
- gate on_shift, displaced_from_post, duty_urgency on is_walking_with
- drop guard_post early-return from npc_is_following
- pause under hold_position and guarding-idle when address_needs undecided
- update tests for new follower-vs-duty arbitration
2026-04-26 11:15:51 -07:00
dumb-kevin 5c5ac59585 Fix camp NPC oscillation on expansion tiles
- Add npc_within_camp() helper using basecamp::point_within_camp()
- Replace base-OMT checks in all six camp BT predicates/scores
- Fall back to base-OMT match when camp object is gone
- Align return_to_camp_duties() with expansion-aware check
- Add expansion-tile regression tests for free_time and camp_work
2026-04-09 13:39:31 +04:00
dumb-kevin bf9878639c Fix NPC infinite loop with NO_NPC_FOOD mod
- Guard BT oracle predicates (needs_food/water_badly, urgency) on needs_food()
- Guard address_needs() food/water handling on needs_food()
- Make npc_noop consume moves when caller didn't
- Add NO_NPC_FOOD sections to behavior_test and npc loop test
2026-04-07 15:16:25 +04:00
dumb-kevin 0447464732 Add NPC need executor system with BT integration
Executor layer:
- need_plan state machine tracks goal, source, target, result,
  and no-progress counter for sticky multi-turn pursuit
- need_goal_id enum with centralized helpers replacing string-based
  dispatch at 6 sites in npc::move()
- Same-category preemption lets urgent needs interrupt holding/blocked
  executors using BT urgency scores via tree::tick_full()
- Failed-target blacklist prevents immediate reacquisition of bad
  targets, cleared on generation reset
- clear_committed_goal() helper unifies external clear sites

Executors:
- execute_eat_food: camp food, inventory, ground items, harvestable
  terrain with food-only filter and sticky target
- execute_drink_water: camp water, inventory drinks, ground drinks,
  water terrain sources with sticky target
- execute_seek_warmth: inventory wear, ground clothing, shelter
  movement with indoor hold and timeout
- execute_go_to_sleep: candidate scoring, sticky target, danger gate,
  effect_lying_down management
- Fold start_fire into seek_warmth as fire_spot source kind with
  shared is_usable_npc_firestarter helper

Shared candidate query layer:
- need_candidate struct with find_food/water/warmth/sleep_candidates()
  wrapping scored helpers into unified scans
- BT predicates and executor target acquisition share the same scan
- Camp food/water as predicate-only sources in candidate layer

BT changes:
- Collapse warmth goals into single seek_warmth node
- Restructure npc_thirst with obtain/seek fallback
- needs_food_badly triggers on caloric deficit, not just hunger
- can_obtain_food/water predicates cover all source types
- Commitment completion uses executor result

Engine fixes:
- NPCs skip query_yn in examine actions so forage/harvest start
- Activities return npc_player_activity, self_activity() restores
  attitude/mission for self-initiated activities
- In-progress forage/harvest finish before BT re-runs
- Forage/harvest yield to danger instead of blindly continuing
- Harvest auto-eat restricted to self-care committed goals
- Protect wielded weapon from fire fuel searches
- Fix idle dispatch intercepting non-guard NPCs with stale guard_pos
- Fix lying_down persistence on sleep interruption
- Delegate firestarter validation to firestarter_actor::can_use()
- consume_food/find_nearby_food with food_only/drink_only filter via
  consume_filter enum
- move_to_and_verify no-bash parameter for routine need-seeking

Tests:
- Executor contract tests for food-seeking (sticky target, retarget,
  no-progress timeout, follow non-regression)
- Water executor contract and predicate tests
- Sleep and warmth executor characterization
- Guard warmth routing, danger interruption, camp food tests
2026-04-05 04:24:41 +04:00
dumb-kevin 2dcf858eeb Split camp residents from guard state, add free_time BT goal
assign_camp() and assign_guard() both set NPC_MISSION_GUARD_ALLY, so
the BT treats camp workers as guards. This causes oscillation between
hold_position and worker_downtime after returning from camp activities.

New NPC_MISSION_CAMP_RESIDENT for camp workers. CAMP_RESIDENT never
has guard_pos, so duty predicates naturally fail. Three new BT goals:
camp_work (job scanning), return_to_camp (overmap travel home), and
free_time (worker_downtime between jobs).

Camp residents can be temporarily ordered to guard (switches to
GUARD_ALLY, keeps assigned_camp). stop_guard preserves assigned_camp
so the player can send them back via "Go back to your camp" in
follower dialogue. New return_to_camp_duties talk effect for the
reverse transition.

On-load migration converts legacy GUARD_ALLY + assigned_camp NPCs,
including previous_mission for those saved mid-activity.
2026-03-31 22:01:14 +04:00
dumb-kevin aad7ed9771 BT evaluates for all NPCs, add npc_follow and goto_ordered_position
Remove the mission gate so the BT runs every turn for all NPCs, not
just guards and shopkeepers. Duty predicates now key off persistent
guard_pos only, ignoring temp sound-investigation anchors.

New BT goals under npc_priorities (utility scoring):
- npc_follow: fires for followers with follow_close, urgency 0.3-0.6
  based on distance. NPCATT_LEAD excluded so leaders keep their own
  pause/goto/keep-up behavior.
- goto_ordered_position: player-directed goto, urgency 0.65. Beats
  follow but loses to life-threatening needs.

Idle dispatch: guard_pos holds post, temp anchor returns to origin,
no anchor falls through to the cascade.
2026-03-31 04:45:57 +04:00
dumb-kevin f09a113ea6 NPC duty/sleep shift scheduling, Hub intercom overhaul, persistent guard_pos
Persistent guard_pos as authority for NPC duty posts. BT-driven
needs-vs-duty arbitration with goal commitment. JSON work_hours on
npc_class for day/night shifts. Schedule reconciliation wakes/sleeps
NPCs at shift boundaries.

Hub intercom: shift-rotating operators, remote dialogue mode, shared
trade backend via supply clerk. NPC_STASIS trait for inert NPCs.

Pathfinder: skip opening shutters over impassable glass.
2026-03-29 07:59:24 +04:00
dumb-kevin 1f24dccc8d Add top-level NPC decision BT convergence diagnostic
npc_decision tree: fallback(combat, investigate, utility(needs, duty)).
Evaluates each NPC turn alongside the legacy cascade, logs symmetric
category comparison under DF_NPC_NEEDS. No behavior changes.

Needs and duty compete via utility scoring with child scores bubbling
up (no parent score override). Predicates mirror live cascade gates
for sound investigation and guard displacement.
2026-03-24 21:01:57 +04:00
dumb-kevin 9d498b1a17 Stabilize NPC needs: shelter radius, cargo, quench floor, foraging
Extend shelter search from radius 1 to 6 with LOS and creature checks.
Oracle delegates to the same helper so BT matches action scope.

Add vehicle cargo to find_nearby_food/warm_clothing, respecting locked
cargo and cargo-locking features.

Floor rate_food() quench penalty so calorie-positive food survives.
Drop the thirst-dominant hard filter -- rate_food scoring handles it.

Add harvest scavenging as last-resort food fallback in both extreme
and normal hunger paths. Adjacent harvestable terrain triggers examine,
distant terrain uses move_to_and_verify.
2026-03-24 13:52:58 +04:00
dumb-kevin be760d4735 Add sleepiness need, implement can_take_shelter, fix can_make_fire
Sleepiness: new needs_sleep_badly predicate (fires at DEAD_TIRED/383)
and sleepiness_urgency score (0-1 against MASSIVE_SLEEPINESS/1000).
The can_sleep feasibility gate fires at EXHAUSTED (575) -- between
DEAD_TIRED and EXHAUSTED the need exists but the NPC pushes through.
Meth effect and positive stim also block sleep, matching the
deterministic checks from Character::can_sleep().

Shelter: can_take_shelter is now an action predicate. Returns running
when the NPC is outdoors with an adjacent passable INDOORS tile.
Returns failure when already indoors (action not applicable), when no
indoor tiles are nearby, or when the indoor tile is impassable.

Fix can_make_fire: was returning success instead of failure when no
fire supplies existed. process_predicates breaks on non-running results,
so success propagated through the fallback as warmth handled, hiding
the shelter check.
2026-03-22 09:12:09 +04:00
dumb-kevin 402dccc35d Switch NPC behavior tree to utility strategy
The npc_needs root node now uses the utility strategy instead of
sequential_until_done. Competing survival needs are prioritized by
urgency score rather than fixed tree order.

Score predicates on the three branch nodes:
- npc_homeostasis: npc_warmth_urgency
- npc_thirst: npc_thirst_urgency
- npc_hunger: npc_hunger_urgency

No gameplay change -- the behavior tree only drives the debug
diagnostic. But the diagnostic now shows dynamic priority shifts
(e.g., near-starvation beats moderate thirst).
2026-03-21 23:40:32 +04:00
dumb-kevin 59fe738dda Add urgency score predicates to character oracle
Three new float-returning methods on character_oracle_t return 0-1
urgency values for use with the behavior tree utility strategy:

- thirst_urgency: thirst / 1200 (dehydration death threshold)
- hunger_urgency: 1 - stored_kcal / healthy_kcal (starvation proximity)
- warmth_urgency: coldest bodypart distance from BODYTEMP_NORM toward
  BODYTEMP_FREEZING

Registered in score_predicate_map via make_score_function helper so
npc_behavior.json can reference them by name.
2026-03-21 23:40:32 +04:00
dumb-kevin 6f8d40e951 Add utility strategy to behavior tree framework
New strategy type that evaluates all children and selects the running
one with the highest score. This is the foundational piece for
kevingranade's NPC needs architecture (#28681) where competing survival
needs are prioritized by urgency (e.g. time_to_die estimates).

- behavior_return gains a score field (default 0.0, no impact on
  existing strategies)
- node_t gains set_score_function() for attaching numeric scoring to
  both leaf and branch nodes
- Score propagation works on branch nodes: a branch evaluates its
  children via its own strategy, then attaches its score to the result.
  This lets a utility parent pick between scored subtrees.
- JSON loading: nodes can specify "score" field referencing a named
  score predicate from score_predicate_map. Unknown IDs are fatal
  (matching strategy/predicate error handling).
- score_predicate_map starts empty, populated by future PRs adding
  time_to_die oracle methods
- "utility" registered in strategy_map for JSON use
2026-03-21 09:39:13 +04:00
dumb-kevin f00541e73b Add NPC behavior tree diagnostic and fix stale needs comments
Add DF_NPC_NEEDS debug filter that evaluates the npc_behavior.json
behavior tree each NPC turn and logs the goal. Purely diagnostic,
no behavior change. Toggle it in the debug menu to see what the BT
would recommend for each NPC (idle, eat_food, drink_water, etc.).

Fix stale comments claiming NPCs can't starve -- they can and do
when needs_food() returns true. Mark the old enum npc_need system
and decide_needs() as legacy with pointers to the behavior tree
replacement path.

Add test coverage for thirst+hunger BT precedence and an integration
test verifying the diagnostic fires (and doesn't fire) based on the
debug filter.
2026-03-18 16:20:57 +04:00
Andrew Krieger 0215b26cce Rewrite all tests to clear map without touching character map memory, for performance. 2026-02-08 23:05:55 -08:00
marilynias 1271c8b08a Refactor and consolidate wield (#79719)
* refactor wield

* refactor wield

* rename wield_new, replace tests

* return early

* fix test and .h var name

* add unwield from game.wield
add_msg_if_player

* remove references to u.

* small fixes

* missing ;

* fix unwield

* fix test

* remove_old for compatibility

* wrong paranthesis

* correct wield_new

* use more wield_new, remove some reminder comments

* fix craft

* fix wielding from reloading

* remove commented out code

* rename weapon -> wielded

* IWYU

* fix wrong move cost
use correct wield for 'one of the bottles is wielded' test

* remove debug msg

* fix tests / clang-tidy

* I hate those tests

* fex 2/3 tests

* please let this be the last test

* clang-tidy

* apply some reviews, remove reminder comments

* re-work; overload item_location from item,

* fix missing item replacement

* fix using item after removing

* revert unecessary changes

* fix missed revert

* move steal check to avatar overload

* this time for real

* extend wield( item_location loc)

* fix

* forgot to do the actual wielding

* fix moves test, apply clang-tidy

* correct obtain cost, doc

* clang-tidy, cleaner conditional

* ordering

* move to std::optional instead of default

* fix optional

* fix 2

---------

Co-authored-by: marilynias <marilynias57+github@gmail.com>
2025-03-01 22:46:14 +01:00
moxian c44d65a8ae Run IWYU again to pick up the changes 2025-02-11 13:02:19 -08:00
moxian 2ee44002fd Mechanically IWYU the tests
python3 ~/github/include-what-you-use/iwyu_tool.py -j5 -p build $( find
src/ tests/ -maxdepth 1 -name '*.cpp' | grep -v -f
tools/iwyu/bad_files.txt )  --  -Xiwyu --comment_style=long -Xiwyu -
-max_line_length=1000 -Xiwyu --cxx17ns -Xiwyu
--mapping_file=../tools/iwyu/cata.imp   | tee out/iwyu/f-a-01.txt >
/dev/null

followed by

cat out/iwyu/f-a-02.txt | python3
~/github/include-what-you-use/fix_includes.py --reorder --nosafe_headers

followed by manual fixups of <stddef.h> -> <cstddef> and similar.

tests/generic_factory_test.cpp gets mangled very badly (IWYU bug) so
it's excluded from the list.

Code size:
includes:
$ cat obj/tiles/*.inc | wc
 288068  576136 17898260
$ cat tests/obj/tiles/*.inc | wc
 167044  334088 10465766

post-processed source (clang -E):
./make_preproc.sh src/
68567896 177775140 2134075721
./make_preproc.sh tests/
39341957 102891720 1243323710
2025-02-10 00:46:57 -08:00
PatrikLundell f14346c5db Rename map:: get_global->get_abs, bub_from_abs->get_bub, omt_from_abs->get_omt (#79167)
* Renamed map:: getglobal->get_abs, bub_from_abs->get_bub, omt_from_abs->get_omt

* astyle
2025-01-16 09:15:04 +01:00
Procyonae 982df19d0f Change /tests remaining uses of raw string item initialisation to use itype_id s
"remaining uses" being somewhat of an understatement -_-
2025-01-10 15:31:15 +00:00
PatrikLundell 8ae88c96d5 typified stuff 2024-12-27 15:17:12 +01:00
Procyonae 0635102b24 "Fix" the check_monster_behavior_tree_locust placing a nonsense plant furniture 2024-12-14 18:41:04 +00:00
PatrikLundell ef6b53acfb typified a little bit of map.h + dependents (#76340)
* typified a little bit of map.h + dependents
2024-09-27 15:10:36 -07:00
PatrikLundell ab062c5e8b typified a bit of map.h/cpp + some dependents (#75125)
* typified a bit of map.h/cpp + some dependents

* Macro crasher found by one compiler!

* demanded changes

* stupid wokaround for demanded changes

* Sort out conflict mess
2024-09-10 09:42:54 -05:00
mqrause bd211963e6 move item_pocket::pocket_type to it's own header 2023-11-27 13:22:35 +01:00
John Bytheway 89171fb202 Convert lots more things to string_view
These are mostly automated changes.  My automation tries to be
conservative, but I did have to do manual fixup of a few things.

I plan to PR the clang-tidy check that automates these changes later,
but I think more changes may be needed before that.

Some of the manual changes:
- Added svto<T> where T is an integer type, which parses integers in
  string_views.  This is our first use of the low-level C++17 int
  conversion functions.
- Added a shortcut to lcmatch for empty queries, to allow for
  refactoring overmapbuffer searches.
- Fixed an apparent bug in overmapbuffer::get_notes and get_extras,
  where it was inverting the match result.  As far as I can tell, these
  functions aren't actually used anywhere, so I guess this bug wasn't
  breaking anything.
- Allow use of string_view in JSON serialization.  Previously these were
  misidentified as sequences and appeared as a list of integers rather
  than a string.
2023-04-20 19:57:23 -04:00
Hirmuolio 5525a3f38a Replace sun_intensity with sun irradiance (#60375)
* irradiance

* is_in_sunlight

* warmth

* firestart

* chloromorph

* glare

* leaves

* troglo

* remove sun_intensity

* remove sun_intensity

* remove sun_intensity

* remove sun_intensity

* adjust sun intensity a bit

* vague comment

* unused

* astyle

* closing comment

* troglo adjustments

* parenthesises
2022-08-31 13:15:47 +02:00
Hirmuolio e547ae781f Make environment temperature to use units::temperature (#58852)
* update get_temperature

* update print_temperature

* tests

* get_local_windchill

* tests run

* make tests pass

* astyle

* cleanup

* weather_generator temperature

* astyle

* cleanup

* get_heat_radiation

* get_convection_temperature

* map temperature mod

* astyle

* weather.temperature

* avoid integer division

* clean get_local_windchill

* unused converts

* get_water_temperature

* unused converts

* windchill tests

* delta F corrected

* wrong unit

* astyle

* dTand wetness morale

* misc cleanup

* astyle

Co-authored-by: Fris0uman <41293484+Fris0uman@users.noreply.github.com>
2022-08-17 12:43:54 +02:00
David Seguin feedfd23ea Re-adopted PR: Persist installed CBMs across revives (#59817)
* Check that reviving items are corpses, not 1 specific corpse type

* Persist installed CBM info across revives

* Astyle

* Remove unused itype_corpse variable

* On first death, spawn CBMs into CORPSE pocket.

* Don't spawn non-cbm dissection items on death

* Revert "Don't spawn non-cbm dissection items on death"

This reverts commit 394309dc61.

* Dissect action now pulls from CORPSE pocket instead of generating from corpse's dissect entries.

* Comment cleanup

* Astyle

* Remove unused success variable

* Update failing tests. CORPSE pocket does not drop contents, but corpse's CONTAINER pocket does.

* Preserve drop type until dissection

Co-authored-by: psuedolet <psuedolet@gmail.com>
2022-08-02 14:27:26 -03:00
John Bytheway b88df12f3d behaviour_test can have its own statics
Previously behaviour_test was using extern declarations that linked to
values inside src/behaviour.cpp for its default behaviours.  But that's
an unclear connection that's somewhat confusing.  It might as well just
have its own static declarations of the same things.
2022-07-11 08:53:00 -04:00
mqrause d688521e7b Character::i_add returns an item_location (#58191)
Co-authored-by: mqrause <martin@qrause.de>
2022-06-18 21:27:30 -04:00
John Bytheway 7385a790be Avoid reserved identifiers
There are three clang-tidy checks which are looking for use of reserved
identifiers.  Enable all of them and fix or suppress the associated
warnings.

The reserved identifiers we had fall into three categories:
- Names containing "__"
- Names starting with "_" followed by a capital letter.
- Names starting with "_" in the global namespace.

Most of those could be automatically fixed by clang-tidy.

One was also affected by the cata-static-string_id-constants check,
which needed to be updated so they wouldn't conflict.

Two cases were erroneous and needed suppression.

The _ macro we use for translation is a reserved identifier, but we're
going to use it anyway.  So that is also suppressed.
2022-06-05 21:02:05 -04:00
KorGgenT 99a62861eb Create wrapper for worn items called outfit 2022-02-27 23:44:51 -05:00
Rob Goodberry 24e295cb98 Rework ABSORBS/ABSORBS_SPLITS behavior (#53741)
Attempt to balance shoggoths a tiny bit

* JSONize absorb rate and split cooldown

Co-authored-by: Kevin Granade <kevin.granade@gmail.com>
2021-12-29 18:21:07 -08:00
John Bytheway e95a4fc9b8 Promote string_id constants to global statics
Our string_id constants were a mixture of temporaries, locals, and
globals.  Pull them all out as globals, for consistency and efficiency.
The efficiency comes from the fact that each string_id instance caches
its respective int_id, and sharing one instance means that value need
not be recomputed.
2021-11-19 19:10:09 -05:00
John Bytheway 8cc6378fc5 clang-tidy modernize-use-emplace (#48661)
* Port code to emplace_back

This is clang-tidy making automated changes to convert push_back into
emplace_back whenever the argument to push_back is either a constructor
call for the type in question of an expression of a type implicitly
convertible to the type in question.

This should eliminate one move-construction of the inserted object for
each call.

* Enable clang-tidy modernize-use-emplace
2021-07-03 07:42:06 -07:00
John Bytheway ebd549b300 Fix StringMaker ODR violations in tests
Catch2 provides a customization point for converting our types to
strings by specializing the StringMaker template.

We have some specializations in stringmaker.h, but this feature was only
working intermittently.  I finally figured out that was due to an ODR
violation.  The test files that didn't include stringmaker.h were
compiling a different specialization than the ones that did.

Re-jig the test includes so that any file including catch.hpp also
includes stringmaker.h, thereby ensuring that the custom
specializations are used everywhere and there is no ODR violation.

I achieved this by adding a new cata_catch.h header and making all
existing headers include catch.hpp via the new header.
2021-07-03 07:42:06 -07:00
Binrui Dong 9fdb7ef59c Run IWYU
* Change _ctype.h and __locale to cctype and clocale

* Change _wctype.h to cwctype in game.cpp

* Change __functional_base to functional

* Remove libcxx internal headers

* Remove UNIX system headers

* Fix clang-tidy error with -nostdinc++
2021-02-06 00:18:41 -05:00
Kevin Granade 675d9ae3a1 clear achievement tracker (#43060)
* clear achievement tracker

* Guard against rounding errors with Approx()

* Add requirements to wield test.

* Manually set margins for comparison

* Just accept minor variation in results

* Verify that behavioral needs are needed

* Fix oracle checks

* Clear temperature cache in behavior test
2020-08-21 10:02:37 +03:00
Kevin Granade c5ccf0c2c7 IWYU for tests (#42806) 2020-08-09 09:46:57 +03:00
Kevin Granade bf2ff19573 Trim some more superflous includes 2020-08-04 06:17:28 +00:00
Kevin Granade 6d1841ac67 Precompiled Catch2 header (#42453)
* Hoist catch.hpp include to the top of files

* Precompile the catch header in tests
2020-07-29 01:28:26 +03:00