Compare commits

...
Author SHA1 Message Date
Hiroku f8ee62386f Some cleanup for brain stuff 2026-10-15 20:25:22 +10:00
Hiroku 52261ea533 Draft for traversal policy as a better control for entity movement preferences + capability 2026-10-04 10:13:31 +10:00
Plastered_Crab 89209f5833 Account for ditto in water egg group check 2026-09-28 19:15:24 -07:00
Plastered_Crab f56a98a3d8 Add basic color tinting to grassy and leafy nests 2026-09-28 16:28:14 -07:00
Plastered_Crab a7798df9cc Stop Incubator from dropping an extra one 2026-09-28 16:26:49 -07:00
Plastered_Crab ee79d1f1a9 Add lost molang fields from prior main merge and add in breeding rules based on QA findings 2026-09-28 16:16:44 -07:00
Plastered_Crab 312bfb2515 Stop incubator from auto hatching eggs 2026-09-28 15:25:12 -07:00
Plastered_Crab 7c9b2f2792 Lower egg placement in incubator 2026-09-28 15:24:36 -07:00
Plastered_Crab a3e12971f8 Better values for wild and pasture breeding cooldowns and breed chance 2026-09-28 15:24:10 -07:00
Plastered_Crab 5bb2a8822c Add helper method for bigger bois so they can have an easier time being considered close enough to the nest 2026-09-28 14:58:49 -07:00
Plastered_Crab 4db7817781 update neighbor shape on egg removal and egg placing for nests (for observers) 2026-09-28 14:32:10 -07:00
Plastered_Crab 76fc434d6d Add mate scan and breeding cooldown configs. Set playtesting values of wild mons breeding 75% less and pastured pokemon having 50% less cooldown 2026-09-28 14:11:16 -07:00
Plastered_Crab 40671c1f56 fix particle reference for hatching eggs 2026-09-28 13:55:15 -07:00
Plastered_Crab 7f73d09ec0 Forgot display section of model jsons 2026-09-28 13:51:50 -07:00
Plastered_Crab c2da10a4f1 Add in final incubator assets and add new READY blockstate 2026-09-28 13:48:54 -07:00
Plastered_Crab 491fd67be1 Fix various species egg textures and jsons 2026-09-28 13:36:59 -07:00
Plastered_Crab 98de0f7163 IdealNestPlacementSense should account for nearby players so afk players stop getting killed lol 2026-09-28 13:15:59 -07:00
Plastered_Crab f1377643e0 Drop wild nests with silk touch and drop hay, incubator, and kelp nests normally 2026-09-28 13:11:37 -07:00
Plastered_Crab 0068ca1a56 mates will chase egg thieves to the ends of the earth if they break the nest and egg (they used to give up) 2026-09-28 13:01:49 -07:00
Plastered_Crab 59d5539b3b Wild eggs break if nest is broken if a player did not place it in the nest (prevent wild egg stealing cheese) 2026-09-28 12:51:08 -07:00
Plastered_Crab 2d5b6eef8c Pasture mons do not build their own nests 2026-09-28 12:25:06 -07:00
Plastered_Crab 3c81ee7432 Pasture mons do not recover their eggs 2026-09-28 12:24:04 -07:00
Plastered_Crab 8da19ade92 Pasture mons do not defend their nest 2026-09-28 12:20:33 -07:00
Plastered_Crab 5b91d87e3e Extra protection checks for eggs in incubators 2026-09-28 11:50:13 -07:00
Plastered_Crab ce4f61d956 trigger hatching pose with timer at or below zero instead (on nest block entity too) 2026-09-28 11:25:15 -07:00
Plastered_Crab 172fd75f4b trigger hatching pose with timer at or below zero instead 2026-09-28 11:24:32 -07:00
Plastered_Crab 59e324737b Remake the brain after tethering to pasture block 2026-09-26 15:32:52 -07:00
Plastered_Crab 76f2918c46 Add missing licenses 2026-09-26 15:15:07 -07:00
Plastered_Crab 2cdde420cc Add temp recipes for Hay Nest and Kelp Nest 2026-09-26 11:32:28 -07:00
Plastered_Crab e698a98ec5 Shuffle the valid nest placements so mates don't always go for west and lower spots first 2026-09-26 00:05:05 -07:00
Plastered_Crab 3e699144a3 Remove debug speed values from breeding brain fixations 2026-09-25 23:33:36 -07:00
JakotensandJakotens 84af5c8c8e Fixed all 87 nest variant blockitem visuals.
Signed-off-by: Jakotens <jjakobdupuyy@gmail.com>
2026-09-25 19:29:43 -06:00
Plastered_Crab e06969c449 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2026-09-25 17:00:55 -07:00
Plastered_Crab b5ee583cd6 Prevent wild eggs being stolen if the parents are in a battle and break egg if nest is broken 2026-09-25 17:00:18 -07:00
JakotensandJakotens 23b185dd19 Fixed the blockitem models for all nest types.
Signed-off-by: Jakotens <jjakobdupuyy@gmail.com>
2026-09-25 17:56:56 -06:00
Plastered_Crab 086db0a295 DefendNest should ignore players in battle and not cry with particles if mon is in battle 2026-09-25 16:20:04 -07:00
Plastered_Crab 8237e69823 Fix wild double battles with parents of a nest 2026-09-25 14:41:45 -07:00
Plastered_Crab dde3b3ea0c Safe check memory of nest to prevent crash for pastured mons and interacted ones 2026-09-25 08:16:56 -07:00
Plastered_Crab 69450121ea Sync the egg hatching animation and sounds 2026-09-24 15:13:24 -07:00
Plastered_Crab 123b1a3c3c give nests proper break particles 2026-09-24 12:18:25 -07:00
Plastered_Crab 823167f121 add leafy nest placements to various bug, bird, and treetop pokemon 2026-09-24 12:06:43 -07:00
Plastered_Crab 380088013b Remove unused grassy variants 2026-09-24 11:58:03 -07:00
Plastered_Crab 2d61c49a7c reposition if statement that was messing up egg recovery 2026-09-24 11:12:40 -07:00
Plastered_Crab f10d828be0 Add in missing egg variation JSON files 2026-09-24 10:24:21 -07:00
Plastered_Crab 5c0dd435b5 Merge with main 2026-09-24 09:35:46 -07:00
Plastered_Crab e38b230102 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/util/codec/internal/PokemonP3.kt
#	common/src/main/resources/data/cobblemon/species/generation9/greavard.json
#	common/src/main/resources/data/cobblemon/species/generation9/houndstone.json
2026-09-24 08:46:24 -07:00
Plastered_Crab 73824094f7 Push ALL egg sprites and block textures 2026-09-23 17:11:19 -07:00
Plastered_Crab 4165ef1866 add eggCycles molang so the hatch time isn't instant from the breeding rule 2026-09-23 16:16:54 -07:00
Plastered_Crab 97bd907563 add orElse(null) to these conditionals now that the uuids are Optional 2026-09-23 15:58:36 -07:00
Plastered_Crab fdf9bc035c change uuids to be Optional<UUID> instead to stop the null codec crash when nests load 2026-09-23 15:55:54 -07:00
Plastered_Crab 1078a83455 remove unused Codec 2026-09-23 15:34:09 -07:00
Plastered_Crab 2d2d6326ce add back molang queries that were lost in main merge 2026-09-23 14:57:24 -07:00
Plastered_Crab 193bea807c whoopsie my main merge kept two busy entries in the packet 2026-09-23 14:22:34 -07:00
Plastered_Crab e69b607a95 Alter breeding behavior priority and add condition to breeding (wild or pastured) 2026-09-23 13:21:58 -07:00
Plastered_Crab 85da0f39b9 Clean up old unused breeding code 2026-09-23 13:16:19 -07:00
Plastered_Crab 2045b2902f Add EggRecovery objective and remove egg related tasks 2026-09-23 12:55:28 -07:00
Plastered_Crab e61e0b55f4 Add Breed objective and remove more old tasks 2026-09-22 16:17:38 -07:00
Plastered_Crab 10275d8a65 Add DefendNest objective and remove 3 old tasks 2026-09-22 11:33:34 -07:00
Plastered_Crab 6785a24bea turn some Sense companion constants into SenseConfig values for in game editing and remove pokemon disturbances 2026-09-21 15:46:01 -07:00
Plastered_Crab 22be65e637 fix variable mistake on EggComponent that would fail isParent check 2026-09-21 14:02:12 -07:00
Plastered_Crab 639835f184 Add BlockPos codec to PATERNAL_NEST_LOCATION so nest locations are remembered 2026-09-21 13:42:11 -07:00
Plastered_Crab 7f4382714d Fix issues from the bigger brain merge 2026-09-18 15:39:42 -07:00
Plastered_Crab 9eb62f4eb0 Merge branch 'bigger-brains' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/biggerbrain/sense/Sense.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/objective/ObjectiveConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/sense/SenseConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/PokemonSpecies.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/auto/pokemon_core.json
2026-09-18 14:55:44 -07:00
Plastered_Crab d6e995f167 Get bigger-brains on parity with main 2026-09-16 15:44:42 -07:00
Plastered_Crab d1246f71dc Merge remote-tracking branch 'origin/bigger-brains' into bigger-brains
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/function/EntityMoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/function/LivingEntityMoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/function/PokemonEntityMoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
#	common/src/main/resources/data/cobblemon/species/generation1/growlithe.json
2026-09-15 16:59:57 -07:00
Plastered_Crab 32049cdffb Merge branch 'main' into bigger-brains
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/ai/OmniPathNavigation.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonServerDelegate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
2026-09-15 16:07:19 -07:00
Plastered_Crab 987fea8cf5 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/function/GeneralMoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/function/SpeciesMoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
2026-09-15 08:09:51 -07:00
Hiroku 3828272511 Merge remote-tracking branch 'origin/bigger-brains' into bigger-brains 2026-09-08 17:34:49 +10:00
Hiroku b3d7736d9f Subscribe system for brain memories 2026-09-08 17:34:35 +10:00
JazzMcNade a36d18d2ed Comments: It's affect not effect... 2026-09-07 20:49:28 -05:00
JazzMcNade 7e2ded7718 Block entity sensing when the Pokemon is sleeping 2026-09-06 21:38:48 -05:00
JazzMcNade 80d5b60dd7 Synced shape and height of AOE effect with the client 2026-09-06 17:41:54 -05:00
Paul a10a90fbbc Merge and resolve conflicts from main 2026-09-06 19:46:51 +10:00
Paul 9921565af7 Merge remote-tracking branch 'origin/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/java/com/cobblemon/mod/common/mixin/client/ItemRendererMixin.java
#	common/src/main/java/com/cobblemon/mod/common/mixin/client/ModelLoaderMixin.java
#	common/src/main/kotlin/com/cobblemon/mod/common/Cobblemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonBlockEntities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonBlocks.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/HabitatPool.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/HabitatPools.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/HabitatSpawn.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/dto/ActivatedHabitatSettingsDTO.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/dto/HabitatPoolSettingsDTO.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/dto/HabitatSettingsDTO.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/dto/NaturalHabitatSettingsDTO.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/spawningstyle/ActivatedHabitatSpawning.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/spawningstyle/HabitatSpawningStyle.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/habitats/spawningstyle/NaturalHabitatSpawning.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/MoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/moves/MoveTemplate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/SpawnLoader.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/influence/detector/SpawningInfluenceDetector.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/BerryBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/habitat/HabitatBlock.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/habitat/HabitatBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/gui/habitat/HabitatEditGUI.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/gui/habitat/HabitatPoolEditorGUI.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/gui/habitat/HabitatSpawnEditorGUI.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/net/habitat/OpenHabitatBlockEditorHandler.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/HabitatBlockRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/CobblemonConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/fishing/PokeRodFishingBobberEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonServerDelegate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/habitat/OpenHabitatBlockEditorPacket.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/server/habitat/SaveHabitatBlockSettingsPacket.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Pokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
#	common/src/main/resources/assets/cobblemon/blockstates/habitat_block.json
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
#	common/src/main/resources/data/cobblemon/species/generation1/blastoise.json
#	common/src/main/resources/data/cobblemon/species/generation1/grimer.json
#	common/src/main/resources/data/cobblemon/species/generation1/growlithe.json
#	common/src/main/resources/data/cobblemon/species/generation1/mrmime.json
#	common/src/main/resources/data/cobblemon/species/generation1/muk.json
#	common/src/main/resources/data/cobblemon/species/generation1/pidgeot.json
#	common/src/main/resources/data/cobblemon/species/generation1/weezing.json
#	common/src/main/resources/data/cobblemon/species/generation2/scizor.json
#	common/src/main/resources/data/cobblemon/species/generation2/steelix.json
#	common/src/main/resources/data/cobblemon/species/generation3/absol.json
#	common/src/main/resources/data/cobblemon/species/generation3/castform.json
#	common/src/main/resources/data/cobblemon/species/generation3/flygon.json
#	common/src/main/resources/data/cobblemon/species/generation3/metagross.json
#	common/src/main/resources/data/cobblemon/species/generation4/garchomp.json
#	common/src/main/resources/data/cobblemon/species/generation4/gastrodon.json
#	common/src/main/resources/data/cobblemon/species/generation4/staraptor.json
#	common/src/main/resources/data/cobblemon/species/generation5/hydreigon.json
#	common/src/main/resources/data/cobblemon/species/generation5/zorua.json
#	common/src/main/resources/data/cobblemon/species/generation6/goodra.json
#	common/src/main/resources/data/cobblemon/species/generation6/inkay.json
#	common/src/main/resources/data/cobblemon/species/generation6/malamar.json
#	common/src/main/resources/data/cobblemon/species/generation6/skiddo.json
#	common/src/main/resources/data/cobblemon/species/generation7/drampa.json
#	common/src/main/resources/data/cobblemon/species/generation8/duraludon.json
#	common/src/main/resources/data/cobblemon/species/generation9/archaludon.json
#	common/src/main/resources/data/cobblemon/species/generation9/orthworm.json
2026-09-06 16:55:26 +10:00
JazzMcNade 1e80c56273 Added AOE realtime attack, refactored damage calculation. 2026-09-05 19:50:30 -05:00
Hiroku 8bc46e26cf Why don't you license deez 2026-07-26 13:55:21 +10:00
Hiroku b925c71884 Remaining resolutions from merge 2026-07-26 13:04:46 +10:00
Hiroku 65e26b558c A few merge resolutions 2026-07-26 12:51:20 +10:00
Hiroku 59d74a8405 Merge remote-tracking branch 'origin/main' into bigger-brains
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonPoiTypes.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/MoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/aspect/AspectParticleMap.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/storage/party/PlayerPartyStore.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/PokemonPastureBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/keybind/keybinds/DebugKeybindings.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/ai/OmniPathNavigation.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonServerDelegate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Pokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/codec/internal/PokemonP3.kt
#	common/src/main/resources/assets/cobblemon/bedrock/pokemon/resolvers/0415_combee/2_combee_nectar.json
#	common/src/main/resources/assets/cobblemon/lang/en_us.json
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/auto/pokemon_non_party.json
#	common/src/main/resources/data/cobblemon/species/generation2/ariados.json
2026-07-26 12:23:33 +10:00
JazzMcNade 1f343e92b9 Move Events, DashMove type, move ticking out of parent/child hierarchy 2026-06-14 16:13:23 -05:00
JazzMcNade 5234c4cfef Fix recovery time for RayCastMoveInstance.kt 2026-05-28 02:29:01 -05:00
Paul 0e82cb7953 Fixed elemental type deserialization in real time moves 2026-05-28 14:17:46 +10:00
JazzMcNade 2ee66d5fb5 Damage Calculation and typed damage multipliers 2026-05-27 22:48:57 -05:00
JazzMcNade bafb524709 Implemented the raycasts in RayCastMoveInstance.kt 2026-05-25 21:48:12 -05:00
JazzMcNade 781b00deb1 Added Piercing effect for ProjectileMove.kt, Licenses 2026-05-25 18:12:29 -05:00
JazzMcNade 71353cf5a7 RealTimeMoves now given subclasses of ProjectileMove.kt and RayCastMove.kt. Dynamic casting of RealTImeMoves when deserialized. 2026-05-25 00:46:48 -05:00
JazzMcNade 4cc1f722a1 Reworked AttackTarget objective into AttackFixation.kt 2026-05-19 00:47:25 -05:00
Paul b635c1516d Migrated real time moves into a registry, implemented move cooldowns inside the Pokemon instead of in the AttackTarget objective 2026-05-18 00:13:27 +10:00
Hiroku 269f7b85e6 Merge branch 'breeding/breeding-rules' into '1.21.1-breeding'
Remade breeding logic, remade egg sprites and model rendering

See merge request cable-mc/cobblemon!2197
2026-05-17 06:56:45 +00:00
JazzMcNade a2a31be107 Added anger on hurt for TerritorialBehaviour.kt 2026-05-16 21:32:42 -05:00
JazzMcNade f646f8ad2e Added TerritorialBehaviour.kt 2026-05-16 21:20:11 -05:00
JazzMcNade 0422f43843 Added NeutralBehaviour.kt, added default ranged/melee attacks, willDefendSelf now adds the NeutralBehaviour Objective 2026-05-15 01:26:50 -05:00
JazzMcNade 0e1f326cf3 Updated FriendlyBehaviour 2026-05-14 21:40:56 -05:00
JazzMcNade 8af4a14944 Improved performance of colliding attack/avoid target objectives 2026-05-14 00:13:47 -05:00
JazzMcNade 2324307abf Wip abstraction of behaviours into EntityResponseObjective.kt, added SkittishBehaviour.kt 2026-05-13 00:55:44 -05:00
JazzMcNade 267a402c09 Allow for nameable objectives for AggressiveBehaviour.kt and FriendlyBehaviour.kt 2026-05-11 01:13:25 -05:00
JazzMcNade dced30f176 Bug fix for molang player entity staleness 2026-05-09 22:31:09 -05:00
JazzMcNade 80e0e78c8a Revert Ariados species changes 2026-05-08 00:47:02 -05:00
JazzMcNade afb3cf1ad3 Pokemon can no longer wander off while attacking 2026-05-08 00:45:41 -05:00
JazzMcNade 3281c82161 WIP Generic real time attack objective 2026-05-06 20:58:26 -05:00
JazzMcNade ce74e87a1e Updated aggressive Objective, added self vs target conditions. Added light_level molang function 2026-04-23 22:54:24 -05:00
JazzMcNade df01d543d2 Update ObjectiveConifg 2026-04-20 21:16:43 -05:00
JazzMcNade 4e3a03efa6 wip aggressive and friendly behaviour 2026-04-20 00:24:12 -05:00
JazzMcNade 235beff45a WIP Defensive Behaviour 2026-04-16 22:24:54 -05:00
jackowes 4ca12aed32 DefendOwner objective and sense 2026-04-12 12:27:25 -05:00
jackowes e564b443f9 Migrate WalkTowardsParentSpeciesTask.kt -> Bigger Brains 2026-04-12 11:25:20 -05:00
jackowes 40a350b8b4 Move over circleAround task to new system. provide debug keybind for the debug ai and highlight the debugged entity. Also comment out some no longer used tasks on old system. 2026-04-11 20:09:40 -05:00
Paul 3a28f4e1ea Conflic deez nuts 2026-04-12 10:48:11 +10:00
Paul 7290addb02 Merge remote-tracking branch 'origin/1.21.1-breeding' into breeding/breeding-rules
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
2026-04-12 10:39:54 +10:00
Plastered_Crab c68a64fc29 Fix Gravel Watery nest kelp animated texture. 2026-04-10 12:47:01 -07:00
Plastered_Crab cc979d5ebc Fix Gravel Watery nest kelp animated texture. Cleanup blockstates. Finalize Nests 2026-04-10 12:46:47 -07:00
Paul bb0bbf1858 Probably fixed egg block crash, inherit various other forms 2026-04-10 22:32:34 +10:00
Plastered_Crab f13274d833 Adjust json formatting and add Saccharine variants based on Honey level 2026-04-08 17:33:48 -07:00
Plastered_Crab 5c14e1a541 Add Watery, Twiggy, and Player nests 2026-04-08 14:20:14 -07:00
Paul 0a1ba92e80 Redid egg texture/sprite handling for addon support, added type & mystery sprite sets and options, removed obsolete breeding logic 2026-04-08 22:06:01 +10:00
Plastered_Crab e6bfc18829 Tweak some rocky nests 2026-04-06 11:25:13 -07:00
Plastered_Crab 812714cc1f Add Rocky Nests 2026-04-06 10:40:46 -07:00
Plastered_Crab 1457424ba8 Swap to packed ice textures 2026-04-06 09:35:46 -07:00
Plastered_Crab 6edec5ab18 Add Icy Nests 2026-04-06 09:18:20 -07:00
Paul a434892af3 Added ability inheritance and fixed some ability slot handling with 500 million file edits 2026-04-04 21:50:36 +10:00
Paul aa6cae6a8b Added pokeball inheritance rules 2026-04-04 15:15:53 +10:00
Paul ea42b584f8 Added shiny logic for eggs, added default hatch time logic, added everstone breeding logic 2026-04-04 13:40:53 +10:00
Paul 03ea67e911 Put the born shorn rule in the pokemon layer, fixed config.struct not being transient oops 2026-04-04 10:35:24 +10:00
Paul 579916b66f Added cobblemon:empty implementations for each breeding rule type to be used for nixing rules from addons 2026-04-03 22:41:39 +10:00
Paul 50faef9496 Filled in the majority of the breeding rule infrastructure and implementation 2026-04-03 22:28:51 +10:00
Plastered_Crab 9e4815bb41 Add Sandy Nests 2026-04-02 15:55:49 -07:00
Plastered_Crab 436c38c8a5 Add Shroomy Nests 2026-04-02 15:30:18 -07:00
Plastered_Crab 0feb2f14e4 Push missing Leafy Nest 2026-04-02 14:54:09 -07:00
Plastered_Crab 16652c5542 Split Grassy into Leafy and Grassy 2026-04-02 14:47:21 -07:00
Plastered_Crab db15f58a69 Final touches on Leafy Nests 2026-04-02 12:01:32 -07:00
Plastered_Crab 808b033285 Push up Leafy (used to be Grassy) nests 2026-04-01 22:00:22 -07:00
Plastered_Crab 31f79bb8c8 Add assets for Fiery Nest and Variants 2026-03-30 11:54:49 -07:00
JazzMcNade 664c0c012c Converted PointToSpawn to BiggerBrains 2026-03-24 01:05:07 -05:00
JazzMcNade ed8c7569f9 Update FocusDuringBattle.kt 2026-03-21 18:55:36 -05:00
JazzMcNade e63a7c474f Migrate kick starting flight for flyers over water 2026-03-21 16:38:40 -05:00
Paul e8e8b31826 Rebuilt Egg data backend to use a storage and only contain a link to it in the egg component 2026-03-14 17:20:21 +10:00
Paul f288dfcbe9 Setting up layer-based breeding rule system 2026-03-14 12:26:20 +10:00
Paul f5580fd83b Merge remote-tracking branch 'origin/bigger-brains' into bigger-brains 2026-03-14 11:40:10 +10:00
Paul a31b533b77 Rhyperior's grooving with better transitioning 2026-03-14 11:39:55 +10:00
JazzMcNade 817ea0bff7 Added "canDance" species configuration option 2026-03-10 23:30:12 -05:00
Paul 35977c0724 Rhyperior's grooving 2026-03-10 21:26:02 +10:00
JazzMcNade 7e08a46f28 Dancing Objective WIP 2026-03-10 01:41:32 -05:00
JazzMcNade cc5d63fd11 Port JumpOutOfWaterTask to BiggerBrains 2026-03-08 01:56:47 -06:00
JazzMcNade 065c5388a0 Fix Combee block jail break, more cleanup 2026-03-02 02:03:04 -06:00
JazzMcNade c20203a8e9 more clean up 2026-03-01 22:57:28 -06:00
JazzMcNade 932ebfa563 Clean up 2026-03-01 22:11:31 -06:00
JazzMcNade 0f57bd35de Comments 2026-03-01 22:05:45 -06:00
JazzMcNade d6974452fb Implemented Bee behavior with biggerbrain tech, allow fliers to wander 2026-03-01 22:02:59 -06:00
Paul aa498450b5 Yet more work on temporary habitat block GUI 2026-02-23 23:12:14 +10:00
Paul e77124369e Some more work on temporary habitat block GUI 2026-02-23 14:13:37 +10:00
Paul 1aaf0d4be6 Some work on temporary habitat block GUI 2026-02-23 13:44:36 +10:00
Paul 1d496bee5b Implemented phase order for habitat blocks 2026-02-23 13:23:34 +10:00
JazzMcNade 937393b93d Remove old tasks 2026-02-22 20:37:45 -06:00
JazzMcNade 59fceeefc3 Smarter usage of looktracker 2026-02-22 16:06:26 -06:00
JazzMcNade ec7e106efb Item pickup for items too close to path to 2026-02-22 13:33:14 -06:00
Paul 244e1c0434 GUI instructions for habitat block editor 2026-02-22 21:13:37 +10:00
Paul 6d0e8dfbe5 Kill unused class 2026-02-22 21:01:06 +10:00
Paul a05380f95b Functional habitat blocks with packets for modifying them 2026-02-22 20:56:28 +10:00
JazzMcNade d95c5687b1 Added eatHeldItem Objective, corrections to PickupItem 2026-02-18 01:35:05 -06:00
Deltric fc5e838172 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding
# Conflicts:
#	common/src/main/resources/mixins.cobblemon-common.json
2026-02-16 08:59:17 -06:00
Deltric 9cb2596ca2 add dynamic model selection for eggs 2026-02-16 08:58:12 -06:00
JazzMcNade 39ef558b9b Pickup item logic 2026-02-15 23:11:03 -06:00
Paul 283ff1ac8f Part one of new habitat blocks, data side 2026-02-14 22:21:40 +10:00
Plastered_Crab bd1628a104 Merge branch 'bigger-brains' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/biggerbrain/sense/Sense.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/objective/ObjectiveConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/sense/SenseConfig.kt
2026-02-11 12:51:20 -08:00
Plastered_Crab 49ba657f1c Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2026-02-11 12:40:03 -08:00
Plastered_Crab e4ccfd4dba Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/resources/data/cobblemon/species/generation1/mrmime.json
2026-02-11 12:36:17 -08:00
JazzMcNade 11452de369 class name typo 2026-02-09 01:35:25 -06:00
JazzMcNade fb4e5002a3 Migrate sweet berry bush harvesting 2026-02-08 21:44:28 -06:00
JazzMcNade 6dd7a7bc9a respect distraction rules 2026-02-08 13:30:52 -06:00
JazzMcNade ba718561aa MoveToRestingPlace Correction 2026-02-08 02:43:35 -06:00
Paul 4ae1b84798 Tiny formatting things 2026-02-08 11:20:51 +10:00
JazzMcNade 21411d26ac More clean up, added moveToRestingPlace Objective 2026-02-03 00:49:14 -06:00
Plastered_Crab 02b45e8b55 Push all the ai changes for the new system 2026-01-30 14:57:56 -08:00
JazzMcNade 3f6c5ebc96 Sleep blocks movement, Added comfort distractions, Removed null check from StayAfloat 2026-01-29 23:25:12 -06:00
Plastered_Crab d217dfee54 Merge remote-tracking branch 'origin/bigger-brains' into 1.21.1-breeding-bigger-brains
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/ai/OmniPathNavigation.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/auto/pokemon_core.json
2026-01-29 14:58:34 -08:00
Plastered_Crab 9702cdebeb Add better placeholder textures and models for testing new Nest Variant system 2026-01-29 08:36:43 -08:00
Plastered_Crab dc6e2fae2e Alter and fix World Gen Nests to work with new ones 2026-01-28 10:32:49 -08:00
Plastered_Crab 2fec360805 Delete old nest models and textures 2026-01-28 10:31:48 -08:00
Plastered_Crab 5627233d3d Cleanup block registries for nests 2026-01-28 10:30:52 -08:00
Plastered_Crab 766328874d Remove old nests and cleanup files 2026-01-28 10:30:20 -08:00
Plastered_Crab 953e7cb7ff Add new Nests and Nest Variants 2026-01-27 16:51:46 -08:00
Plastered_Crab 01ce59c8c4 Alter Cobblemon Sensors and Memories 2026-01-27 16:50:48 -08:00
Plastered_Crab 7468b180e2 Add Lang 2026-01-27 16:50:16 -08:00
Plastered_Crab cad0a9490d Add Nest Types variable to species 2026-01-27 16:50:03 -08:00
Plastered_Crab a6e046e405 Alter Nest Creation Task Configs and old Pokemon Brain 2026-01-27 16:48:47 -08:00
Plastered_Crab fe3a893afc Kill old nest material gathering task configs 2026-01-27 16:47:38 -08:00
Plastered_Crab 5c9530e10e Alter Tasks and Sensors for nest building 2026-01-27 16:45:40 -08:00
Plastered_Crab 5c45cf595c Kill old nesting material sensor 2026-01-27 16:45:11 -08:00
Plastered_Crab 378f5434f7 Kill Old tasks for pokemon gathering nesting materials 2026-01-27 16:44:46 -08:00
Plastered_Crab 64f32bf4b7 Add stupid stinky temporary Nest Art Assets 2026-01-27 16:43:41 -08:00
Plastered_Crab 66ec46dcc6 Add stupid stinky temporary Nest Art Assets 2026-01-27 16:43:16 -08:00
Plastered_Crab 1c3d027877 Add BlockStates files for new Nests and their variants 2026-01-27 16:41:35 -08:00
Plastered_Crab 99cf6b8a65 Add JSON tags for the blocks that change the nest types into specific variants 2026-01-27 16:40:21 -08:00
Plastered_Crab 1025a583d9 Add JSON tag lists for blocks certain types of nests can be created on by pokemon 2026-01-27 16:39:08 -08:00
Plastered_Crab 749303f640 Scrape Nest Types onto all Species of pokemon from Behavior Spreadsheet 2026-01-27 16:37:54 -08:00
Plastered_Crab fa80edf178 Remove Material Gathering tasks from Breeding behavior 2026-01-27 16:27:15 -08:00
Plastered_Crab 80f31a13d8 Alter Behavior Scraper to pull Nest Types for each species 2026-01-27 09:53:43 -08:00
Plastered_Crab 62ae8285e2 Fix SpawnPokemonPacket 2026-01-26 14:17:51 -08:00
Plastered_Crab cba807be81 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/battles/actor/MultiPokemonBattleActor.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/DisplayCaseRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
2026-01-26 10:01:52 -08:00
JazzMcNade 0bbdfd2c5e Added Sleeping 2026-01-26 02:28:20 -06:00
JazzMcNade f43b7d3dd7 Cleanup 2026-01-25 20:35:28 -06:00
JazzMcNade 6291ac0e23 Added MoveIntoWaterObjective 2026-01-25 02:50:46 -06:00
JazzMcNade 4f528c855b Created MoveOutOfWater Objective 2026-01-24 23:08:21 -06:00
Paul 29c291fd7a Minor doc change [skip-ci] 2026-01-18 13:28:13 +10:00
Paul 493f71302e Some brain clarification stuff and some docs for adding to the brains 2026-01-18 13:20:03 +10:00
Paul ab5a54f21e Fixed excessive wander chances 2026-01-17 18:25:59 +10:00
Paul 440e2855c0 Swimmers can tread water when not pathing on new brain 2026-01-17 16:43:44 +10:00
Paul 8ebecc4928 Migrated stay afloat task to new brain 2026-01-17 11:24:13 +10:00
Paul 4f0108c8a2 Replaced busy locks with fixations that implement LockFixation 2026-01-16 22:16:54 +10:00
Paul 32cd79baec Improved wandering so they can look around and (rarely) wander while in a herd, fixed look targeting for wandering 2026-01-15 22:25:19 +10:00
Plastered_Crab 6df0173cbe Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/PokemonPastureBlockEntity.kt
2026-01-14 10:36:52 -08:00
Paul a8ac858918 Migrated herding to bigger brain 2026-01-14 21:48:20 +10:00
Paul d46394cb1d Migrated sheep grass eating to bigger brains 2026-01-09 22:44:45 +10:00
Paul d5cc2de7e5 I want a license to kill this pipeline error 2026-01-03 17:03:01 +10:00
Paul a5088cf264 Migrated objective configs into the objective classes, moved OT type class out of the Pokemon file 2026-01-03 16:18:20 +10:00
Paul 6c5fd6ea1c Added draft of new AI system 2025-12-31 23:00:10 +10:00
plastered_crab 6b05ab19d4 Merge branch 'main' into 1.21.1-breeding 2025-12-28 14:36:34 -08:00
plastered_crab ad995ad33f Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
2025-12-15 10:33:49 -08:00
Paul 1a265fbe9a Compilation error fixes from merge 2025-12-05 16:52:26 +10:00
Paul 11b47e9c77 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonActivities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItemComponents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/nest/NestSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/position/NestSpawnablePosition.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/spawner/GrottoSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/NestBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
2025-12-05 16:49:02 +10:00
Paul bab7a5e011 merge conflict stuff 2025-12-05 16:47:05 +10:00
plastered_crab 0fca9b17ed Bye bye nest spawner 2025-12-02 14:35:13 -08:00
plastered_crab f648aa44a0 Merge main with Breeding branch! Yipeeeee (Hiro I need your help with the grotto spawner tho) 2025-12-02 11:26:01 -08:00
Paul 9b8663cb82 Merge remote-tracking branch 'origin/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonActivities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/keybind/keybinds/DebugKeybindings.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/world/feature/CobblemonPlacedFeatures.kt
2025-11-24 19:40:22 +10:00
plastered_crab 0ff5ef70c5 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonActivities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/keybind/keybinds/DebugKeybindings.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/world/feature/CobblemonPlacedFeatures.kt
2025-11-21 19:54:04 -08:00
plastered_crab b978a4447b Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
2025-11-21 19:50:23 -08:00
Paul 9bd52006c6 Update from main 2025-10-24 22:26:03 +10:00
Paul f66c782e22 Merge remote-tracking branch 'origin/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/CobblemonConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
2025-10-24 22:06:05 +10:00
plastered_crab 3f75e5307f Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
2025-10-06 11:15:11 -07:00
plastered_crab 7c7488910d Fix some conflicts 2025-09-22 11:23:28 -07:00
plastered_crab 6ef1dc29ae Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItemComponents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2025-09-22 11:10:45 -07:00
plastered_crab e8376ed1c9 why do i even have that lever 2025-09-08 22:08:44 -07:00
plastered_crab 538d186488 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/BerryBlockRenderer.kt
#	common/src/main/resources/assets/cobblemon/particles/snowstorm.json
2025-09-08 21:54:01 -07:00
plastered_crab dd70d159fb Get Breeding on track with Main again (we do so much work) 2025-08-25 21:56:00 -07:00
plastered_crab eece4256b8 Get Breeding on track with Main again (we do so much work) 2025-08-25 21:51:49 -07:00
plastered_crab b773110e9f Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
2025-08-25 21:39:42 -07:00
plastered_crab 1eceaa45b2 Get breeding up to date with main 2025-08-16 19:43:34 -07:00
plastered_crab 1ff2f16c61 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonPoiTypes.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2025-08-16 19:36:33 -07:00
plastered_crab a4a1c0a4d5 Get breeding up to date with main 2025-08-10 16:52:48 -07:00
plastered_crab d80f0ed3c4 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
2025-08-10 15:48:38 -07:00
plastered_crab db4f6a04f3 FREE LUIGIA 2025-07-29 17:14:00 -07:00
plastered_crab 19448a18e7 merge main 2025-07-29 07:23:33 -07:00
plastered_crab a0e125fedb Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/bedrock/animation/BedrockAnimation.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/world/feature/CobblemonPlacedFeatures.kt
2025-07-29 07:02:56 -07:00
plastered_crab b3b039677d Finalized Gen 1 egg block textures 2025-07-29 06:56:15 -07:00
plastered_crab 621f539b98 Finalized Gen 1 egg item sprites 2025-07-29 06:50:33 -07:00
plastered_crab 79768a3407 Fix some classes 2025-07-09 06:06:38 -07:00
plastered_crab 117408ac20 Merge branch 'refs/heads/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonPoiTypes.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/influence/detector/SpawningInfluenceDetector.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/auto/pokemon_core.json
2025-07-09 05:23:25 -07:00
plastered_crab 2c0610757f Merge branch 'refs/heads/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
2025-06-29 20:52:12 -07:00
plastered_crab f94e5eb2d3 Merge remote-tracking branch 'refs/remotes/origin/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonActivities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
2025-06-20 06:10:22 -07:00
plastered_crab 075421856e my kid is asleep time to merge main 2025-06-10 21:46:47 -07:00
plastered_crab 97397aae7d Merge branch 'refs/heads/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItemComponents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
2025-06-10 19:01:46 -07:00
Plastered_Crab 0c9b3ede11 Merge branch 'main' into 1.21.1-breeding 2025-05-29 15:13:46 -07:00
Plastered_Crab 78e15b0d8e Merge branch 'main' into 1.21.1-breeding 2025-05-28 10:54:16 -07:00
plastered_crab b31236dbfb merge main to keep this stuff up to date 2025-05-27 19:49:37 -07:00
plastered_crab da1e172164 Merge branch 'refs/heads/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItemComponents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/PokemonPastureBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/item/CobblemonModelPredicateRegistry.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/bedrock/animation/BedrockAnimation.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
2025-05-27 19:27:46 -07:00
Paul ab0f2cbd79 Bug fix for grotto block editor 2025-05-11 10:10:58 +10:00
Paul 62c7882469 Apply grotto structure markers that can be detected by spawn files 2025-04-28 20:09:34 +10:00
Paul b6c2c65a6c Integrated spawning upgrades from the other branch with surprisingly little pain 2025-04-27 21:43:01 +10:00
Paul 01206fb67a Merge branch 'spawning-upgrades' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/riding/RidingManager.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/BestSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/CobblemonSpawningZoneGenerator.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/SpawningZone.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/condition/SpawningCondition.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/fishing/FishingSpawnCause.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/influence/BucketNormalizingInfluence.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/influence/detector/GrottoBlockDetector.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/influence/detector/SpawningInfluenceDetector.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/position/AreaSpawnablePositionResolver.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/spawner/AreaSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/spawner/Spawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/spawner/TriggerSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/command/SpawnPokemonFromPool.kt
#	common/src/test/kotlin/com/cobblemon/mod/common/spawning/SpawnValidator.kt
2025-04-27 21:20:01 +10:00
Paul 07af63db25 Conflicto fixo 2025-04-27 21:15:53 +10:00
Paul 1047648f68 Merge remote-tracking branch 'origin/main' into 1.21.1-breeding 2025-04-27 20:55:53 +10:00
Paul 6523a610ff immediate compile error fix 2025-04-25 12:08:32 +10:00
Paul 6d132e3f39 Merge remote-tracking branch 'origin/smarterer-pokemons' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/Cobblemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItemComponents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonPoiTypes.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/CobblemonSpawningZoneGenerator.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/SpawningZone.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/condition/FishingSpawningCondition.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/context/AreaContextResolver.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/fishing/FishingSpawnCause.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/preset/BestSpawnerConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/selection/FlatContextWeightedSelector.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/spawner/TickingSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/keybind/keybinds/DebugKeybindings.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/resources/cobblemon-common.accesswidener
#	fabric/src/main/kotlin/com/cobblemon/mod/fabric/CobblemonFabric.kt
2025-04-25 12:07:21 +10:00
Paul b311d092de Fixed tests that assume all spawn files are pokemon ones 2025-04-23 21:44:09 +10:00
Paul 6f134a50e0 Touch ups to herd logic with new controls. It works >:] 2025-04-23 20:58:04 +10:00
Paul a0531f2d2f Spawning refactors and herd spawning (untested!!!) 2025-04-22 22:16:15 +10:00
Paul 80f5050ecd Major rename of spawning terms and moved spawn bucket decision later in the process 2025-04-20 20:08:22 +10:00
Landon Wills e32a2da8a4 Fix animation sometimes not playing 2025-04-19 21:05:24 -04:00
Aram e92609b6c7 Fixed Grotto Mimic Particles/Sound 2025-04-19 22:43:16 +02:00
Aram abc0c72707 Small cleanup again 2025-04-19 22:22:48 +02:00
Aram e55f46c990 small cleanup 2025-04-19 21:48:58 +02:00
Aram 6ee5714bf9 Grotto Debug GUI 2025-04-19 21:47:20 +02:00
plastered_crab bb379764f7 Time for pokemon to breed with their brains! Merging in brain branch finally!!! 2025-04-18 09:50:53 -07:00
plastered_crab 3ec78d9d7e Merge branch 'refs/heads/1.21.1-breeding-pokemingle.com' into 1.21.1-breeding 2025-04-18 09:36:56 -07:00
plastered_crab 12973dd66a Grotto Block finally mimics blocks perfectly (with AO) 2025-04-18 09:26:46 -07:00
Aram ed30e4cd6f Almost working Ambient Occlusion, it doesnt check for all surroundings yet 2025-04-18 17:39:35 +02:00
Aram 32c260446e Grotto isnt black anymore!, Occlusion still broken 2025-04-18 17:30:42 +02:00
plastered_crab 41f1eb699f Marging with smarterer and fixing reference issues 2025-04-18 07:56:23 -07:00
plastered_crab e68a593e9e Merge branch 'refs/heads/smarterer-pokemons' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/MoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/riding/RidingManager.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/PosableModel.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonServerDelegate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/net/messages/client/spawn/SpawnPokemonPacket.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Species.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/pokemon_breeding.json
#	common/src/main/resources/data/cobblemon/behaviours/pokemon/pokemon_core.json
2025-04-18 06:51:29 -07:00
plastered_crab 903ffe2143 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-04-18 06:44:22 -07:00
Aram 1d6845d595 When in Creative, the Incubator also doesn't remove the egg from your inventory 2025-04-18 12:41:15 +02:00
Aram f8eb72e437 Finished Incubator Hatching Animations 2025-04-18 11:39:18 +02:00
Plastered_Crab 28a3b8edfe Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-04-17 15:51:39 -07:00
Plastered_Crab 96ee23b7d1 🥚2️⃣ Add ALL Finalized Gen 2 Egg Sprites and Egg Textures 2025-04-17 15:51:23 -07:00
Aram d3ce829e5b Incubator Hatching Animation WIP
Currently Missing the BlockPos so the Pokemon wont spawn

check: EggRenderHelper
2025-04-17 16:35:46 +02:00
Plastered_Crab 4010f138ae Remove some old code and comment out debug lines 2025-04-16 11:32:24 -07:00
Plastered_Crab 5100d6c028 Habitat spawning system now references player party levels to determine the level of things that spawn 2025-04-16 11:25:20 -07:00
plastered_crab 154ff75a9d Comment out debugging lines to check other things 2025-04-16 07:38:07 -07:00
plastered_crab 678c98a5b6 GrottoBlockEntities now grab a set of habitat spawns during each Full Moon or if it is empty 2025-04-16 07:37:26 -07:00
plastered_crab d9143788bf Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-04-16 06:14:17 -07:00
plastered_crab 7e1956f165 Use POI system to detect Grotto Blocks and use them to spawn Pokemon around habitats 2025-04-16 00:08:28 -07:00
plastered_crab 994a41af78 Add structureCenter variable to GrottoBlockEntity to try to use later to center habitat spawns 2025-04-15 21:32:37 -07:00
Plastered_Crab 2d5f15a4db Fix another oopsie 2025-04-15 15:37:05 -07:00
Plastered_Crab 8442000708 Habitats files now work with weighted spawnpools and per-entry weights too 🌳 2025-04-15 15:28:06 -07:00
Plastered_Crab 695ac93f99 Habitats are starting to work now :D 2025-04-15 12:46:58 -07:00
plastered_crab e5e5c29c12 Edits to Dead Wood habitat 2025-04-15 07:45:20 -07:00
plastered_crab 893277fdec Habitats support list of spawn choices per moon cycle instead of only individual spawns 2025-04-15 00:43:38 -07:00
plastered_crab 60dc881e3d Basic system for Grotto Blocks to cycle spawn pool choices each Full Moon cycle 2025-04-14 23:50:15 -07:00
plastered_crab f98acf0bc4 Fix oopsie 2025-04-14 22:04:38 -07:00
plastered_crab 6e104fdb01 Spawn system detects Grotto blocks as POIs and detects the habitat they belong to along with reads the spawn pool of the habitat 2025-04-14 22:00:48 -07:00
plastered_crab 05c559e203 Grotto block now detects and saves the structure they spawn with onto them 2025-04-14 18:49:54 -07:00
plastered_crab 1323caeeec Add test dead tree habitat for testing 2025-04-14 18:15:44 -07:00
Plastered_Crab 6dc5809622 Add test Grotto Block for habitat testing 2025-04-11 15:24:27 -07:00
Plastered_Crab d4416e50b2 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-04-10 16:13:22 -07:00
Plastered_Crab 520bcda956 Adding test files for experimenting with habitats 2025-04-10 16:12:56 -07:00
Sterrezo d10c082e67 Subtitled the egg sounds 2025-04-10 22:33:23 +02:00
Sterrezo 72d608b300 Volume corrections and fixed a missing sound 2025-04-10 22:13:14 +02:00
Sterrezo 2b4dc467ff Egg sounds! 2025-04-10 21:36:14 +02:00
Plastered_Crab b9390838d0 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-04-10 09:59:44 -07:00
plastered_crab e36bbd98f2 No more stuttering hatch animation (Thank you Landon <3) 2025-04-09 22:37:56 -07:00
plastered_crab c4aa925f39 Put hatch animation onto PokemonEntity 2025-04-09 20:57:26 -07:00
plastered_crab ad5e85ad97 Final Hatching animation + particles working more now! 2025-04-09 14:50:09 -07:00
plastered_crab 5279603432 Particle keyframes starting to work on Hatching Animations now :D 2025-04-09 13:02:15 -07:00
plastered_crab 583fba4e77 Sound keyframes starting to work 2025-04-09 08:56:20 -07:00
plastered_crab 9ee983b2a2 Good checkpoint on trying to get the hatching sound to play via keyframe 2025-04-08 21:31:30 -07:00
Plastered_Crab 16ffbbbd9e Some code to try to get Hatching sounds working :D 2025-04-08 16:33:13 -07:00
Plastered_Crab f23495fe99 Fix for hatching multiple eggs on the same nest due to a missing sync 2025-04-08 14:53:35 -07:00
Plastered_Crab f61448c333 Hatching animations work now! REJOICE! 2025-04-08 14:44:58 -07:00
Plastered_Crab 406770eaf1 More work towards getting the hatching animations working 2025-04-08 13:34:16 -07:00
Plastered_Crab 2513fab317 More work towards getting the hatching animations working 2025-04-08 12:11:47 -07:00
Plastered_Crab 3a79e49edb More work towards getting the hatching animations working 2025-04-08 10:44:16 -07:00
plastered_crab 87dad0143b Hatching animation FINALLY starting to work 2025-04-08 00:48:39 -07:00
plastered_crab bdc91fea71 Add in new files to get ready for Hatching animation implementation 2025-04-07 19:04:41 -07:00
Plastered_Crab eb64666229 Merge with main to keep things up to date for less pain later 2025-04-07 13:43:07 -07:00
Plastered_Crab f7ed0c8799 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/NestBlockEntity.kt
2025-04-07 13:25:27 -07:00
Plastered_Crab 9fde7adb7b Merge with main to keep things up to date for less pain later 2025-04-07 13:14:56 -07:00
Plastered_Crab 8b8c07065b Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/molang/MoLangFunctions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/riding/RidingManager.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/PosableModel.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonServerDelegate.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Pokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/EntityExtensions.kt
2025-04-07 12:48:42 -07:00
Plastered_Crab 6d761fef4f Merge in new Brains code and remove Nest Spawner 2025-03-27 16:59:38 -07:00
Plastered_Crab 737ce1314c Remove old unused "Nest" spawner and merge in new code 2025-03-27 16:31:46 -07:00
Plastered_Crab 7b89f82d45 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonActivities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/PokemonSpecies.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/repository/VaryingModelRepository.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/FormData.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/ai/PokemonBrain.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2025-03-27 15:43:17 -07:00
Plastered_Crab 2203d543a1 Merge branch 'smarterer-pokemons' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/permission/CobblemonPermissions.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/PokemonSpecies.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/spawning/BestSpawner.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/Category.kt
2025-03-27 15:32:11 -07:00
Guilherme Pereira c129157687 add foliage color to leaf nests 2025-03-27 03:52:41 -03:00
Guilherme Pereira 276c49ac5c fix lush nest caves configured feature 2025-03-27 03:52:26 -03:00
Plastered_Crab f517a63cc9 Make it so nests naturally generate in the world in their proper biomes 2025-03-18 15:52:31 -07:00
Plastered_Crab 1e2f685ee5 fix for filename for Gastly's egg 2025-03-17 16:33:13 -07:00
Plastered_Crab 5245614804 Add light level to Warm Ocean nest and adjust collision boxes of new nests 2025-03-17 16:29:12 -07:00
Plastered_Crab 8b97c3cb85 Whoopsie these files were missed 2025-03-17 15:51:07 -07:00
Plastered_Crab d607463116 Added the 8 new nest types! 2025-03-17 15:50:42 -07:00
Plastered_Crab 07cc92eb18 Added new underwater Seagrass nest for cold oceans/rivers :D 2025-03-04 16:21:04 -08:00
Plastered_Crab 9665eba7b0 Wild parents will bring their lost eggs back to their nest more consistently now 2025-02-28 12:25:05 -08:00
Plastered_Crab 9f83c7c72c Put that thing back where it came from or so help me 2025-02-26 15:52:10 -08:00
Plastered_Crab 9bb74358f7 Get this thing on track with Main again too 2025-02-26 15:48:06 -08:00
Plastered_Crab e2219730e6 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/NestBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/CobblemonConfig.kt
2025-02-26 15:40:47 -08:00
Plastered_Crab 4daaf50b1a Get this thing on track with Main again 2025-02-26 15:37:01 -08:00
Plastered_Crab b79792ebbf Merge branch 'main' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonNetwork.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/PokemonSpecies.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/models/blockbench/repository/VaryingModelRepository.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/Category.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/CobblemonConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/FormData.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2025-02-21 15:14:44 -08:00
Plastered_Crab 7a0b294d3d Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
2025-02-21 15:04:14 -08:00
Plastered_Crab ad1312d077 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/Category.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/config/CobblemonConfig.kt
2025-02-21 14:36:04 -08:00
Plastered_Crab d65d7b779f Add delay to NestSensor 2025-02-12 15:49:45 -08:00
Plastered_Crab 7ce25d8158 Wild pokemon will claim the nests they build for themselves 2025-02-12 15:20:55 -08:00
Plastered_Crab 178d7293fb Okay they go to nests in single pairs for real this time 2025-02-12 14:29:04 -08:00
Plastered_Crab ba0bba2202 Code change for parity with the pokemingle branch 2025-02-12 13:32:16 -08:00
Plastered_Crab 29d5ce5f0e Pairs of wild pokemon will "claim" a nest before they get there 2025-02-12 12:57:25 -08:00
Plastered_Crab b9ebfc17ed Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-02-12 09:36:10 -08:00
Plastered_Crab 2e28792c92 Add variable to NestBlockEntity to allow wild mons to "claim" them before breeding so hoards don't run to a single nest 2025-02-12 09:02:21 -08:00
plastered_crab 648d15403f Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-02-11 12:09:17 -08:00
plastered_crab 3fe3f521ee Fix regional form predicate registration 2025-02-11 12:08:54 -08:00
plastered_crab 0ff638a0ca Merge remote-tracking branch 'origin/1.21.1-breeding-pokemingle.com' into 1.21.1-breeding-pokemingle.com 2025-02-11 11:25:02 -08:00
plastered_crab 485b5f46f6 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-02-11 11:24:42 -08:00
plastered_crab b7c2063510 Add ALL Gen 1 - Gen 9 Egg predicate files updated YIPPEE 2025-02-11 11:01:46 -08:00
plastered_crab 94d7ae5290 Add ALL Gen 1 - Gen 9 Egg item model predicate files 2025-02-11 08:37:28 -08:00
plastered_crab d75d5da250 Add ALL gen 9 Egg sprites! That is ALL NOW (THANK YOU CUMULO) 2025-02-11 08:27:43 -08:00
plastered_crab d3cd1be24e Add ALL gen 8 Egg sprites! (THANK YOU CUMULO) 2025-02-11 07:44:07 -08:00
Plastered_Crab d1f11316ec Wild pokemon are more mindful of biomes/materials when making their own nests 2025-02-10 16:47:30 -08:00
plastered_crab 1e50bd999b Wild pokemon now gather nesting material dropped on the ground to make tree, water, snow, etc nests! 2025-02-09 22:34:45 -08:00
plastered_crab 0257f6c6a0 Wild pokemon now have a chance to gather materials around them to make nests for themselves if none are around 2025-02-07 22:15:58 -08:00
Plastered_Crab a3bc1cf72b Wild pokemon will try to detect nest materials to build their own nests if there is not one nearby 2025-02-07 17:12:59 -08:00
Plastered_Crab e236632c67 Wild Pokemon Parents will attack the player until they give the egg back >:( 2025-02-06 17:32:25 -08:00
Plastered_Crab 4730d97898 Wild Pokemon Parents will now give up searching for a lost egg after some time 2025-02-06 15:20:30 -08:00
Plastered_Crab 36994a134d Wild Pokemon Parents will now attack players who take their eggs and bring eggs back 2025-02-06 13:09:36 -08:00
Plastered_Crab 97899b3fa9 Wild pokemon parents will look for their lost egg and bring it back to the nest 2025-02-06 11:56:25 -08:00
plastered_crab 713bd6d6ef Tons of code for wild parent pokemon to know when their egg is missing and to go looking for it (not working fully yet) 2025-02-06 08:01:47 -08:00
plastered_crab 48736fad1f Fix aggression once more since refactor 2025-02-03 20:00:02 -08:00
plastered_crab 5a47deb9a7 Ground pokemon will ignore nests in trees and other areas they cannot pathfind to! 2025-02-01 22:59:33 -08:00
plastered_crab 4b01facb4f Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-02-01 21:08:48 -08:00
plastered_crab 158d4d6aed Tweaking generation of wild nests 2025-02-01 21:03:58 -08:00
plastered_crab ab91776d97 Natural generation of all 15 wild nests almost working properly now 2025-02-01 18:08:35 -08:00
plastered_crab 286ffe7219 More work to add new world gen wild nests 2025-02-01 01:39:21 -08:00
plastered_crab 79da4cb8a8 Add new world gen files for nests (thank you Slippy!) 2025-02-01 01:35:02 -08:00
Plastered_Crab 32f3c75d45 Fix to make Snow Nests only spawn where it is cold 2025-01-31 15:46:46 -08:00
Plastered_Crab acc81d60ad Remove test code for spawning pokemon 2025-01-31 15:31:53 -08:00
Plastered_Crab 4b093a0072 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-01-31 14:39:41 -08:00
Plastered_Crab e0c57007db Wild Nests test generation on ground, in trees, and in snow 2025-01-31 14:38:54 -08:00
Plastered_Crab 66b3579a9b Wild Nests test generation on ground, in trees, and in snow 2025-01-31 14:34:41 -08:00
Plastered_Crab 0981bb71ce Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-01-31 09:47:19 -08:00
Plastered_Crab 6b762cd6d3 Add all Gen 6 and Gen 7 Egg Sprites 2025-01-31 09:47:03 -08:00
Plastered_Crab 581c466c0e Add all Gen 6 and Gen 7 Egg Sprites 2025-01-31 09:46:05 -08:00
Plastered_Crab 5622c65fca Add all Gen 6 and Gen 7 Egg Sprites 2025-01-31 09:45:55 -08:00
Plastered_Crab 51c6ea576b Add all Gen 6 and Gen 7 Egg Sprites 2025-01-31 09:42:24 -08:00
plastered_crab b7b8fe1fb9 fix some sillies 2025-01-31 06:29:51 -08:00
plastered_crab 1634a20464 Config for increased hatching rates in the nether for nests and incubators 2025-01-30 23:57:24 -08:00
plastered_crab 7190c33dab Test bounding box data for 9 new nests coming later 2025-01-30 20:38:26 -08:00
Plastered_Crab 8ea20925d3 Mons with only Water 1/2/3 egg groups can breed at underwater nests. Mons with water + other egg groups can breed at both 2025-01-30 16:52:22 -08:00
Plastered_Crab d4c7ce4eb9 Merge branch 'smarterer-pokemons' into 1.21.1-breeding-pokemingle.com 2025-01-30 15:05:15 -08:00
Plastered_Crab 625237457a move initialization of config to be before CobblemonItems 2025-01-30 12:50:23 -08:00
Plastered_Crab 0f21173f5f move initialization of config to be before CobblemonItems 2025-01-30 12:48:18 -08:00
Plastered_Crab 7fda4570c6 More preparations for the other 9 nests 2025-01-30 10:46:30 -08:00
Plastered_Crab e0aae17f37 Prepare for the other 9 types of nests 2025-01-30 10:14:01 -08:00
plastered_crab 32b4459e19 Adjust BreedAtNest brain task to account for Destiny Knot durability via config 2025-01-30 07:38:06 -08:00
plastered_crab 9072a7ac3c Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/breeding/BreedingLogic.kt
2025-01-30 07:31:50 -08:00
plastered_crab 0e39874f9a Added logic for Destiny Knot durability IF the configs are set to true 2025-01-30 06:31:38 -08:00
plastered_crab aa5d116910 Added config for Destiny Knot Durability and if it breaks or not during breeding 2025-01-30 06:22:21 -08:00
plastered_crab 1f49d0d21b Added config Masuda method & config Legend, Genderless, and Ditto breeding 2025-01-29 23:40:43 -08:00
Plastered_Crab 05a612bf79 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-01-29 13:24:06 -08:00
Plastered_Crab ab0d839006 Comment out possibly unused access wideners 2025-01-29 13:22:46 -08:00
Plastered_Crab 56b061c93d Optimize bounding box for Incubators 2025-01-29 11:39:03 -08:00
Plastered_Crab ec97e16609 Fix faulty bounding boxes on Eggs, Nests, and Incubators! 2025-01-29 11:32:55 -08:00
plastered_crab e4ce58414c Changes to the 7 new nest types 🪺🥺 2025-01-29 07:41:45 -08:00
plastered_crab b07856ed58 Add 7 new nest types 🪺🥺 2025-01-28 21:51:17 -08:00
plastered_crab b7d2f38490 More changes to the MateSensor to try to "pair" mates together 2025-01-28 17:56:26 -08:00
plastered_crab 295185c1cf Change to the MateSensor to try to "pair" mates together 2025-01-28 10:15:22 -08:00
plastered_crab f0d8ee21d9 No more pokemon swingers partys (hopefully) 2025-01-28 09:20:43 -08:00
plastered_crab b203020b4d Pokemon now have a cooldown memory for checking for near mates + compat checks 2025-01-28 08:06:52 -08:00
plastered_crab 5962149da8 Cancel path to nest task if an egg is in it 2025-01-28 06:51:25 -08:00
plastered_crab 24101bed08 Fixes to AI pathing to nests 2025-01-27 08:10:38 -08:00
plastered_crab 321736657e AI breeding is broken once more, but some progress trying to fix 2025-01-25 20:04:21 -08:00
plastered_crab e50309871a Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/breeding/BreedingLogic.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/NestBlock.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/NestBlockEntity.kt
2025-01-24 22:51:58 -08:00
plastered_crab 36cd7e426a Fix give pokemon egg command (it is slow for some reason) 2025-01-24 16:47:37 -08:00
plastered_crab 6660747b31 Fix give pokemon egg command (it is slow for some reason) 2025-01-24 14:55:57 -08:00
plastered_crab c021f28dc7 Eggs now animate based on how ready they are to hatch! :D 2025-01-24 14:42:22 -08:00
plastered_crab a7a2eceda6 More work to refactor the pokemon ai breeding tasks 2025-01-24 06:15:28 -08:00
plastered_crab a4cac592e6 Merge branch 'refs/heads/smarterer-pokemons' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/resources/data/cobblemon/brain_presets/pokemon/pokemon_core.json
2025-01-23 18:13:16 -08:00
plastered_crab b29c6e0d9c Merge branch 'refs/heads/1.21.1-breeding-egganims' into 1.21.1-breeding 2025-01-23 18:06:09 -08:00
amo ba9ea5b793 Add eggmodelrepo to posableModelRepositories so anims and groups are registered 2025-01-23 23:30:36 +00:00
Plastered_Crab 47d5ac4108 trying to get these eggs to wiggle 2025-01-23 09:56:02 -08:00
plastered_crab c6df8bbb61 Why won't these damn egg WIGGLE 2025-01-23 07:12:41 -08:00
plastered_crab 97055b7ede so close to getting egg animations working (no more crashing) 2025-01-22 21:45:34 -08:00
plastered_crab df64ac268e change to Bedrock egg structure 2025-01-22 21:12:28 -08:00
plastered_crab 541a3e257b change to Bedrock egg structure 2025-01-22 19:53:22 -08:00
plastered_crab 1a995dfca8 change to Bedrock egg structure 2025-01-22 19:23:43 -08:00
plastered_crab 9aef6b02ad change to Bedrock egg structure 2025-01-22 19:22:00 -08:00
Plastered_Crab f914f20283 Incubator Recipe 2025-01-22 16:28:10 -08:00
Plastered_Crab 03e558efbb Incubator Recipe 2025-01-22 16:27:54 -08:00
Plastered_Crab 925a0551b2 Nests can only be mined with silk touch + break when block underneath is broken 2025-01-22 16:04:32 -08:00
Plastered_Crab 1677f9fe89 Some preparations for Egg animations based on Ready to Hatch State 2025-01-22 15:30:10 -08:00
Plastered_Crab 1db4c90479 Egg incubators now have a little light in them that lights up when it has an egg 💡🥚 2025-01-22 14:22:52 -08:00
Plastered_Crab e3beeff5a8 Egg Incubators send out Comparator values if they are ready to hatch 🧪👨‍🏫 2025-01-22 12:18:03 -08:00
Plastered_Crab 52a6d84041 Protections and Comparator code for Incubators 🧪👨‍🏫 2025-01-22 11:14:27 -08:00
plastered_crab 84f2183f36 Eggs can be hoppered into Incubators :D 2025-01-22 07:57:56 -08:00
plastered_crab 492cd7bc9e Work towards hoppers working on nests :D 2025-01-21 22:09:04 -08:00
Plastered_Crab c21a25610c Add all Gen 5 Egg Sprites 2025-01-21 11:40:47 -08:00
plastered_crab 4eed3c06a7 Work towards Eggs showing patterns for forms 2025-01-21 09:44:05 -08:00
plastered_crab 7f804445c4 You can make a Charizard breed with Blastoise to make Bulbasaur now (forms don't work...) 2025-01-20 22:55:38 -08:00
plastered_crab 89eee30488 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/breeding/BreedingLogic.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/breeding/BreedingLogicManager.kt
2025-01-20 22:36:30 -08:00
plastered_crab b386a20351 You can make a Charizard breed with Blastoise to make Bulbasaur now (forms don't work...) 2025-01-20 22:33:23 -08:00
Plastered_Crab ac06bc6103 Custom Breeding rules are almost fully functional 2025-01-20 16:15:09 -08:00
plastered_crab cda8697dd9 You can now catch a pokemon in wild Doubles battles when there is only 1 mon left 2025-01-19 22:33:11 -08:00
plastered_crab f7f7400163 Parents can no longer move to kill you during a wild Double Battle!✋🛑🥚😡 2025-01-19 21:05:32 -08:00
plastered_crab ea0c4731d8 Merge remote-tracking branch 'origin/1.21.1-breeding-pokemingle.com' into 1.21.1-breeding-pokemingle.com 2025-01-19 19:34:02 -08:00
plastered_crab 204b923289 Merge branch 'refs/heads/smarterer-pokemons' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/ai/config/task/TaskConfig.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/pokemon/PokemonSpecies.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/FormData.kt
#	common/src/main/resources/data/cobblemon/brain_presets/pokemon/pokemon_core.json
2025-01-19 18:54:12 -08:00
Plastered_Crab 6f34b6347d Pokemon no longer want to mate during battle 😳😳 2025-01-18 20:46:31 -08:00
Plastered_Crab a935edbb55 You can now Double Battle with the parents of a nest 2025-01-18 20:22:02 -08:00
Plastered_Crab e58c3b9422 Pokemon will now warn players when they start to get too close to the nest, then will attack if they get closer 2025-01-18 17:20:56 -08:00
Plastered_Crab a5ddc556f3 Merge remote-tracking branch 'origin/1.21.1-breeding-pokemingle.com' into 1.21.1-breeding-pokemingle.com 2025-01-18 15:27:37 -08:00
Plastered_Crab a541cc3e55 Merge branch '1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/resources/data/cobblemon/species/generation1/growlithe.json
#	common/src/main/resources/data/cobblemon/species/generation3/zigzagoon.json
2025-01-18 15:27:10 -08:00
Plastered_Crab e355bdd68a Add ALL gen 4 egg sprites 2025-01-18 15:24:00 -08:00
Plastered_Crab d687d91090 Add ALL gen 4 egg sprites 2025-01-18 15:23:46 -08:00
Plastered_Crab 6b38147c23 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-01-18 15:09:49 -08:00
Plastered_Crab 0241dbcfa1 Merge branch 'main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/tags/CobblemonItemTags.kt
2025-01-18 15:09:35 -08:00
plastered_crab b2e641e269 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-01-17 22:48:38 -08:00
plastered_crab 63f32cb79c Add all gen 3 Egg block textures🥚 2025-01-17 22:48:04 -08:00
plastered_crab 7b05868c5a Add all gen 3 Egg block textures🥚 2025-01-17 22:46:51 -08:00
plastered_crab c4fd0d6fd7 Wild Pokemon attack players close to their nests 🧍🥚😤👊 2025-01-17 21:57:28 -08:00
plastered_crab a4f0eb999c dumb commit to make you not read my horrible sentence in the last commit 2025-01-17 20:22:17 -08:00
plastered_crab 85b7231ff6 Wild pokemon will patrolling the nest will now phyiscally beat up the player that gets too close to the nest 🧍🥚😤👊 2025-01-17 20:20:52 -08:00
plastered_crab 0f3d0008e9 Wild pokemon will now patrol a radius around their nest AND get angry at visible players that get near the nest 2025-01-17 18:40:37 -08:00
plastered_crab 74addf45c3 Pastured Pokemon will only breed in Player-placed nests, wild pokemon only breed in wild nests 2025-01-17 14:43:01 -08:00
Plastered_Crab f97a8a8475 prep work for wild pokemon ignoring player nests and owned pokemon ignoring wild nests 🥚🪺 2025-01-16 16:20:59 -08:00
Plastered_Crab e8cc212968 Pokemon now get tired from mating 😴🫃🏻🥚 2025-01-16 16:05:30 -08:00
plastered_crab 7918924c1c Add test egg cooldown system 2025-01-16 10:59:16 -08:00
plastered_crab 28a41860b9 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com 2025-01-16 09:52:17 -08:00
plastered_crab 20ef700422 Add all gen 3 Egg Sprites 2025-01-16 09:24:20 -08:00
plastered_crab c017863ef8 Add Unown Egg sprite 2025-01-16 08:48:59 -08:00
Plastered_Crab d28ac2facf Pokemon now listen to their brains that it is time to MATE 🫃🏻🥚 2025-01-15 13:49:20 -08:00
Plastered_Crab b391f13b11 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-01-15 09:28:57 -08:00
plastered_crab c2f29a0dc3 Alter Breeding Logic to prepare for more Brain stuff 2025-01-15 07:19:45 -08:00
plastered_crab 0c4a148c52 Merge branch 'refs/heads/1.21.1-breeding' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonCommands.kt
2025-01-15 07:18:49 -08:00
plastered_crab 5c4aa543fa Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-01-15 06:08:18 -08:00
plastered_crab d3a9b50c03 Add gen 2 egg sprites (minus unown) 2025-01-15 06:07:13 -08:00
Plastered_Crab 46962d95fc Pokemon AI is starting to learn how to find a mate and go to a nest to breed 2025-01-13 15:13:23 -08:00
plastered_crab ea50837750 Changes to AI driven Mating tasks 2025-01-13 07:42:13 -08:00
plastered_crab b03fe17e8c Start of AI driven Mating tasks 2025-01-12 20:27:07 -08:00
Guilherme Pereira 16cf5ecbb7 add '/givepokemonegg' and '/giveallpokemonegg' commands 2025-01-12 18:33:09 -03:00
plastered_crab 1b34278ec4 Merge branch 'refs/heads/smarterer-pokemons' into 1.21.1-breeding-pokemingle.com
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonMemories.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonSensors.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/FormData.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Species.kt
#	common/src/main/resources/data/cobblemon/flows/battle_victory/npc_battle_end_scripts.molang
2025-01-12 13:32:38 -08:00
plastered_crab 045d5a8a5e Start to the new Pokemon dating site 2025-01-12 13:26:38 -08:00
plastered_crab 5729c9d5be Egg tweaks 2025-01-12 09:55:32 -08:00
plastered_crab a286584c32 Egg sprites are working now! YIPPEEE 2025-01-12 09:37:09 -08:00
plastered_crab a5895aaa7c Move sprites and egg item model file 2025-01-12 00:46:45 -08:00
plastered_crab 0ab6fef566 Added more predicate files for sprites 2025-01-11 22:51:48 -08:00
plastered_crab a973d21bc0 Added TONS of Egg sprites :D 2025-01-11 22:48:29 -08:00
plastered_crab e149d3f4c8 Add more egg sprite prep 2025-01-11 14:41:44 -08:00
plastered_crab adfde3e236 Add more egg sprite prep 2025-01-11 14:41:23 -08:00
plastered_crab 18cdf705ed Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/item/EggItemRenderer.kt
#	common/src/main/resources/assets/cobblemon/models/item/egg.json
#	common/src/main/resources/assets/cobblemon/textures/egg_patterns/inventory/charmander_egg.png
2025-01-11 00:20:37 -08:00
plastered_crab e5730a5119 Add egg test sprites and get model predicates for sprites working 2025-01-11 00:17:06 -08:00
plastered_crab b295cd7bef Merge branch 'refs/heads/1.21.1-breeding-sprite-test' into 1.21.1-breeding 2025-01-10 23:26:15 -08:00
plastered_crab a168715b3c Merge branch 'refs/heads/main' into 1.21.1-breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
2025-01-10 23:21:42 -08:00
plastered_crab 55f8212451 Holy Schmoly! So many egg files! 2025-01-10 23:09:42 -08:00
plastered_crab c5e7c79c2a Changes to egg sprite renderer 2025-01-10 17:21:04 -08:00
Plastered_Crab d4a44b4977 Merge branch 'main' into 1.21.1-breeding 2025-01-10 14:20:55 -08:00
Plastered_Crab f9f0668f6b Back to basics to start fresh later 2025-01-10 13:59:56 -08:00
Plastered_Crab d01beb3ba8 plz sprites be nice 2025-01-10 13:36:41 -08:00
Plastered_Crab 3cac052772 Bro why won't these sprites render 2025-01-10 13:29:51 -08:00
Plastered_Crab 84bc8bc426 Added New Egg sprites to test with 2025-01-10 10:02:50 -08:00
Plastered_Crab 98a25908c2 More stuff to try to get egg sprites working 2025-01-10 09:02:25 -08:00
plastered_crab 4ed3d41eb1 Progress towards trying to get Egg Items to render separately from the Egg Blocks 2025-01-09 22:04:02 -08:00
Plastered_Crab 672fd7365f OOPS I should have deleted this test Egg Move rule lmao 2025-01-09 15:42:25 -08:00
Plastered_Crab 39a16beb14 Breeding Logic reworked + Moves passed down work now according to games (Egg moves, Tm/Hm, learned moves, etc) + Added new datapackable Egg Move system for custom egg move rules 2025-01-09 15:38:58 -08:00
plastered_crab 32dbd1f8c9 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2025-01-07 01:30:25 -08:00
plastered_crab bcc23ec4fc Merge branch 'refs/heads/main' into 1.21.1-breeding 2025-01-07 01:30:08 -08:00
luke 143fc8256b Added gen 2 non-regional egg textures 2025-01-02 20:23:34 -07:00
luke 70d753d1d3 Incubator hatch handling 2024-12-29 00:33:13 -07:00
luke 00a67b22df Fixed incubator interaction 2024-12-28 11:11:24 -07:00
luke 12811fe504 Implemented most incubator block logic 2024-12-27 18:42:40 -07:00
Plastered_Crab 40ffb99928 Merge branch 'main' into 1.21.1-breeding 2024-12-26 13:49:35 -08:00
Plastered_Crab 78fb8fb834 Merge remote-tracking branch 'origin/1.21.1-breeding' into 1.21.1-breeding 2024-12-26 13:40:45 -08:00
Plastered_Crab 614663a49c Merge branch 'main' into 1.21.1-breeding 2024-12-26 13:27:46 -08:00
plastered_crab ca9955f4cd Some more changes to try to prepare for eggs to render as items properly 2024-12-24 02:14:19 -08:00
Plastered_Crab 2f40c5d71b Pokemon cry when they hatch from eggs now! CUTE >:D 2024-12-20 15:22:01 -08:00
Plastered_Crab 1a84ca4ba0 Eggs in nests can now hatch!! (in a basic sense) they just don't cry when hatching yet though :( 2024-12-20 15:04:24 -08:00
Plastered_Crab 5f29986d41 Fix some persistent renderings of eggs in the incubator and ground and fix some item models 2024-12-20 12:49:02 -08:00
Plastered_Crab bfb63088c1 Increase time for wild nests to have a family 2024-12-20 10:12:33 -08:00
Plastered_Crab 626bd7f4f4 Now created eggs are always the base pre-evolution (yippeee) 2024-12-20 10:10:27 -08:00
Guilherme Pereira bff941264c temporary workaround for nest spawner not working 2024-12-20 12:30:10 -03:00
plastered_crab 10b472e980 More work on trying to get parent Pokemon to spawn at wild nests 2024-12-20 00:05:22 -08:00
Plastered_Crab 7888a8ac31 Added NestSpawner (and friends). Test to have Charizard guarding nest 2024-12-19 21:25:57 -08:00
plastered_crab d79adfc0be Very early prototype system for "Wild Pokemon Nests" 2024-12-19 16:31:38 -08:00
plastered_crab e4baf5fe3e Pastures recalculate breeding pairs after recalling pokemon 2024-12-19 13:38:07 -08:00
plastered_crab 3013c30084 Eggs will have two parents always now (don't ask about before...) 2024-12-19 13:28:29 -08:00
plastered_crab fc10b550cd Fix Egg position in DisplayCaseRenderer 2024-12-19 13:14:43 -08:00
plastered_crab 514787a1c4 Eggs can now be placed in Nests, Incubators, Display Cases, and on the ground! 2024-12-19 12:32:46 -08:00
plastered_crab c32f3c5581 Fix some issues with the Egg Incubator block and renderer 2024-12-19 01:27:39 -08:00
plastered_crab 94b9b7ade3 Add Egg Incubator block and entity/renderer classes 2024-12-19 00:59:54 -08:00
Plastered_Crab ee33b4292c Added more textures for some species eggs (thank you Cumulo) 2024-12-18 15:51:43 -08:00
Plastered_Crab 271e74d6f2 Added more textures for some species eggs (thank you Cumulo) 2024-12-18 15:50:53 -08:00
Plastered_Crab 2ea41c3dae Adding some placeholder starter/legendary egg textures for testing 2024-12-18 14:47:49 -08:00
Plastered_Crab a6d93aba17 EGGS RENDER IN NESTS NOW!!! WOOOO 2024-12-18 13:55:44 -08:00
Plastered_Crab db1711b76f More attempts to render the eggs (I hate these things) 2024-12-18 10:23:34 -08:00
Plastered_Crab ab5b2e8fdf Add EggComponent and try to get Server to sync to Client (I AM SO CLOSE) 2024-12-17 17:02:16 -08:00
Plastered_Crab efa4028948 Change Egg data to prevent cheesing, and try to make them render via texture instead of overlay 2024-12-17 14:13:29 -08:00
Plastered_Crab 65529474cb Merge main into Breeding branch to keep it up to date 2024-12-17 10:19:04 -08:00
Plastered_Crab 7d756249ae Merge branch 'main' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/fishing/FishingBait.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/moves/MoveSet.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/PokemonPastureBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/command/TestCommand.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/fishing/PokeRodFishingBobberEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/item/group/CobblemonItemGroups.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2024-12-17 10:14:54 -08:00
apion 3fcfd2ff6d We can go into worlds pog 2024-08-02 18:06:02 -04:00
apion 98545541e0 Port to 1.21 (it compiles at least) 2024-08-02 05:44:33 -04:00
apion 56820ad626 Merge branch 'refs/heads/sega_bass_pro_fishing_2' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonBlockEntities.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/CobblemonItems.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/api/tags/CobblemonItemTags.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/BerryBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/PokemonPastureBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/atlas/CobblemonAtlases.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/BasicBlockEntityRenderState.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/BerryBlockRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/FossilAnalyzerRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/RestorationTankRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/layer/CobblemonRenderLayers.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/command/TestCommand.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/data/CobblemonDataProvider.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/item/group/CobblemonItemGroups.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/pokemon/Pokemon.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
#	common/src/main/resources/cobblemon-common.accesswidener
#	common/src/main/resources/data/cobblemon/loot_table/blocks/egg.json
#	common/src/main/resources/data/cobblemon/tags/item/defaulting_poke_balls.json
2024-08-02 03:03:41 -04:00
Plastered_Crab 64546b25f2 - Tweaked Breeding Logic for passing IVs 2024-02-28 12:35:22 -08:00
Plastered_Crab d5496fb465 - Adjusted the Heart Breeding particles to look more vanilla 2024-02-28 12:31:57 -08:00
jeffw773 bcd2474d5f - Pokemon emit Heart particles when bred + logic for nests with eggs is tweaked 2024-02-27 22:13:16 -08:00
apion e331b959c8 Fixed IV logic 2024-02-25 07:49:20 -05:00
apion ce159ac742 Allow insertion of eggs to nests 2024-02-14 17:20:09 -05:00
apion 3e4eaf0397 Fixed another persistence issue 2024-02-14 13:12:30 -05:00
apion 2a2308b4a4 Fixed some desync/persistence issues 2024-02-14 12:54:19 -05:00
apion 47511bac89 Made eggs hatchable 2024-02-13 21:54:47 -05:00
apion c6a5e69f91 Merge remote-tracking branch 'origin/main' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/FossilAnalyzerRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/FossilTubeRenderer.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/layer/CobblemonRenderLayers.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
2024-02-13 20:58:48 -05:00
apion 32a9185cc1 Made egg blocks drop their egg 2024-02-13 20:09:25 -05:00
apion ec54aeb1fd Fixed crash if parent pokemon had no hidden ability options, sped up egg sprite rendering a bit 2024-02-13 17:55:27 -05:00
apion 9aab1113fd Fixed inventory lighting 2024-02-13 16:21:51 -05:00
apion 86578cd266 Got 3D sprite model generation working properly, except for lighting in inventory. Also, licenses 2024-02-13 09:43:03 -05:00
apion 566d74a638 Move egg inventory rendering to generate and use BakedModels 2024-02-12 14:21:42 -05:00
apion 23988b55a1 Egg inventory rendering fully working 2024-02-10 01:06:57 -05:00
apion d5418ed5c7 Got egg rendering working in a less sus way 2024-02-09 22:54:06 -05:00
apion 5318b1470d Eggs now kinda work in inventory 2024-01-30 23:29:57 -05:00
apion 0ca91eb071 Merge branch 'main' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/api/events/CobblemonEvents.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/block/entity/BerryBlockEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/client/render/block/BerryBlockRenderer.kt
#	common/src/main/resources/cobblemon-common.accesswidener
2024-01-30 22:58:08 -05:00
apion 7d31719cd1 Update patterns to include inv sprites 2024-01-30 22:51:45 -05:00
apion 25ed3d28f4 Added placeable eggs 2024-01-30 20:22:21 -05:00
apion 5df64d038b Start working on adding egg item, and egg item rendering 2024-01-30 16:40:56 -05:00
apion ec6d838ea6 Fixed render distances for all BERs 2024-01-08 13:27:34 -05:00
apion 6bea8aafe6 Added a bunch of egg patterns 2024-01-08 13:12:13 -05:00
Lily 5bbf5d2d85 Added documentation to BreedingLogic, added Gender and PokeBall functionality 2024-01-02 21:59:59 -05:00
apion 6d09590374 Fixed lighting and tinting issues on eggs 2024-01-02 14:18:18 -05:00
apion 0e0ebc0b48 Pasture blocks now properly update nest entities, fix some rendering bugs, fix block entity sync issues 2024-01-02 12:40:27 -05:00
apion 0c4a4ddda1 Generified berry rendering optimizations and apply them to eggs, added new data class for egg pokemon, added a bunch of nbt serializer stuff 2024-01-02 10:01:11 -05:00
apion 1efeddc875 Merge branch 'berry-rendering' into breeding 2024-01-02 07:56:31 -05:00
apion 82c6e8f42d Merge branch 'main' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/entity/pokemon/PokemonEntity.kt
#	common/src/main/kotlin/com/cobblemon/mod/common/util/DataKeys.kt
2024-01-02 07:56:19 -05:00
apion 5ff522bb85 Added egg rendering, and nest block entity 2024-01-02 06:59:52 -05:00
apion b2b73575d4 Add some API stuff 2024-01-02 04:41:41 -05:00
apion d7bbccab08 Move BerryBlockRenderState to be client specific 2024-01-02 04:26:52 -05:00
apion 21b8fe8474 Fix flower texture 2024-01-02 04:15:55 -05:00
apion 94c210efd4 Big cool rendering stuff 2024-01-02 04:06:46 -05:00
apion d3100be95a Refined breeding logic 2023-12-29 23:17:51 -05:00
apion 3353c15af6 Add nest detection in pasture block 2023-12-20 23:26:35 -05:00
apion 1cced11431 Merge conflicts lul 2023-12-20 22:54:06 -05:00
apion 646ad5606a Merge branch 'archaeology' into breeding
# Conflicts:
#	common/src/main/kotlin/com/cobblemon/mod/common/client/CobblemonClient.kt
2023-12-20 22:50:17 -05:00
apion 8214e848f9 Added nest blocks and oak twig texture + licenses :D 2023-12-20 22:18:26 -05:00
apion ece9c63121 Added breeding events, refactored logic a bit 2023-12-20 20:16:08 -05:00
apion ce81f07aa2 Started work on pasture behavior for breeding 2023-12-19 19:48:47 -05:00
apion 9bcaa6dfad Merge branch 'main' into breeding 2023-12-16 21:19:45 -05:00
apion 295efe8c11 Merge branch 'breeding' of https://gitlab.com/cable-mc/cobblemon into breeding 2023-12-16 21:17:43 -05:00
apion 5cff811aab Merge branch 'main' into breeding 2023-12-16 21:14:57 -05:00
apion 00e721d714 Add nest assets 2023-11-20 07:01:10 -05:00
Nick 0c602027cb Begin work on an API for breeding logic 2023-10-26 22:17:55 -07:00
Lily 7070369cea breeding logic 2023-10-23 22:10:36 -04:00
4292 changed files with 62595 additions and 2273 deletions
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

+11
View File
@@ -0,0 +1,11 @@
### Additions
### Changes
- Replaced the entity AI for Pokémon and NPCs with an entirely custom one. Yeah we changed the entity AI in 1.7 too, you're remembering right.
- Improved performance of entity AI.
### Fixes
### Developer
### Molang & Datapacks
+8
View File
@@ -0,0 +1,8 @@
### Additions
- Added Pokémon breeding for Pokémon left in pasture blocks.
- Added nest blocks that Pokémon can lay eggs in.
### Developer
- Spawning Influences now have the context of what the other buckets are when adjusting bucket weights. This will break existing influences that do bucket weight adjustment.
- Renamed heaps of things in the spawning system to make more sense.
+223
View File
@@ -0,0 +1,223 @@
# Habitat Block GUI Editor - Developer Instructions
These instructions are brought to you by AI slop with Hiroku reviewing it afterwards. It does seem fairly accurate
though.
## Overview
The Habitat Block is a spawning tool that allows creative mode players to configure custom Pokémon spawning behavior. We need a GUI editor so read below to understand what it needs to do.
Phases might need a bit of explanation. The idea is that each habitat block will have a current "phase", which changes every day. The number of different phases is something that can be configured per block, as well as what order the phase will move through when it changes.
In the case of 3 phases, the different phase orders do the following:
SIMPLE: 1-2-3-1-2-3-1-2-3
FIXED_RANDOM: 1-3-2-1-3-2-1-3-2 (or some other repeating pattern, based on the position of the habitat block)
FULL_RANDOM: 1-3-1-2-3-1-3-1-2 (completely random value each day)
The idea is like, if you had set 3 phases for a habitat block, you could make Rattata spawn in phase 1, Patrat in phase 2, and Zigzagoon in phase 3.
## Entry Point
- GUI opens when a creative mode player right-clicks a Habitat Block
- Packet: `OpenHabitatBlockEditorPacket` sends current settings to client
- When you're done you send a `SaveHabitatBlockSettingsPacket` back to the server with the same settings DTO instance (but modified, one would assume)
- Settings are applied via `HabitatBlockEntity.applySettings(HabitatSettingsDTO)`
## Data Structure
### Root: `HabitatSettingsDTO`
All settings are contained in this DTO which is sent between client and server.
#### Common Settings (always present)
```kotlin
numberOfPhases: Int = 1 // Number of spawn phases (TODO: not yet implemented)
phaseOrder: HabitatPhaseOrder // How the passage of phases will work with each day
levelRange: IntRange // Min..Max level for spawned Pokémon
modifiers: String // PokemonProperties string (e.g., "shiny gender=male")
mimicId: ResourceLocation // Block appearance (e.g., "minecraft:stone")
```
#### Spawning Mode Toggle
```kotlin
isActivatedSpawning: Boolean // true = Activated mode, false = Natural mode
```
Based on this boolean, EITHER `activatedSettings` OR `naturalSettings` will be populated (never both).
---
## Spawning Modes
### Mode 1: Activated Spawning (`ActivatedHabitatSettingsDTO`)
Triggered spawning system - spawns occur based on specific triggers.
```kotlin
trigger: Enum // REDSTONE, TICK, or RANDOM_TICK
chance: Float = 1.0 // Probability (0.0-1.0) spawn attempt occurs on trigger
cancelledNaturalSpawningRange: Int // Radius (blocks) where natural spawning is disabled
spawnRange: Int // Radius (blocks) where spawning can occur
maxSpawns: Int = -1 // Max concurrent spawns from this block (-1 = infinite)
maxSpawnsPerActivation: Int = 1 // Max spawns per single trigger event
habitatPool: HabitatPoolSettingsDTO // What Pokémon can spawn (see below)
```
**Trigger Types:**
- `REDSTONE`: Spawns on redstone pulse (rising edge)
- `TICK`: Attempts spawn every game tick (very frequent)
- `RANDOM_TICK`: Attempts spawn on random tick events
### Mode 2: Natural Spawning (`NaturalHabitatSettingsDTO`)
Modifies the natural spawning system in the area.
```kotlin
replaceSpawns: Boolean // true = only this pool spawns, false = adds to natural spawns
rangeOfInfluence: Int // Radius (blocks) where this influences spawning
habitatPool: HabitatPoolSettingsDTO // What Pokémon can spawn (see below)
```
---
## Habitat Pool Settings (`HabitatPoolSettingsDTO`)
Defines what Pokémon can spawn. Can reference existing pools or define custom ones.
```kotlin
id: ResourceLocation // Pool identifier
isReference: Boolean // true = use existing pool, false = custom pool
isActivated: Boolean // Must match parent spawning mode
// Only present when isReference = false:
name: String? // Display name for custom pool
spawns: List<HabitatSpawn>? // List of spawn entries
```
**Pool Types:**
- **Reference Pool**: `isReference = true` - Uses a pre-defined pool by ID (e.g., `cobblemon:forest_day`)
- **Custom Pool**: `isReference = false` - Defines spawns inline with `name` and `spawns` list
**Custom Pool IDs**: Must start with `custom__` prefix (e.g., `cobblemon:custom__my_pool`)
---
## GUI Requirements
### Layout Sections
#### 1. Common Settings Panel
- **Number of Phases**: Integer input greater than zero (default: 1)
- **Phase Order**: Habitat Phase Order dropdown (default: SIMPLE)
- **Level Range**: Two integer inputs (Min/Max) - Default: 1 to config max Pokémon level
- **Modifiers**: Text input for PokemonProperties string
- Examples: `shiny`, `gender=male`, `shiny gender=female level=50`
- **Mimic Block**: Block selector/dropdown
- Default: `minecraft:stone`
- See `HabitatBlockEntity.mimicCycle` for suggested blocks
#### 2. Spawning Mode Selector
Radio buttons or toggle:
- **Activated Spawning** (trigger-based)
- **Natural Spawning** (world spawning influenced)
#### 3. Mode-Specific Settings
**If Activated Spawning:**
- **Trigger**: Dropdown (REDSTONE / TICK / RANDOM_TICK)
- **Chance**: Float slider (0.0 - 1.0, default: 1.0)
- **Cancel Natural Spawning Range**: Integer input (blocks)
- **Spawn Range**: Integer input (blocks)
- **Max Spawns**: Integer input (-1 for infinite, default: -1)
- **Max Spawns Per Activation**: Integer input (default: 1)
- **Habitat Pool**: Pool selector (see below)
**If Natural Spawning:**
- **Replace Spawns**: Checkbox (true = exclusive, false = additive)
- **Range of Influence**: Integer input (blocks)
- **Habitat Pool**: Pool selector (see below)
#### 4. Habitat Pool Selector
Two options:
- **Use Existing Pool**: Dropdown of registered pools
- Set `isReference = true`
- Set `id` to selected pool
- Ensure `isActivated` matches spawning mode
- **Create Custom Pool**: Opens pool editor
- Set `isReference = false`
- Generate ID with `custom__` prefix
- Set `name` and `spawns` list
- User defines spawn entries (implementation depends on `HabitatSpawn` structure)
---
## Validation Rules
1. **Level Range**: Min must be ≥ 1, Max must be ≤ config max, Min ≤ Max
2. **Number of Phases**: Must be greater than zero
3. **Chance**: Must be between 0.0 and 1.0
4. **Ranges**: All range values must be ≥ 0
5. **Pool Validation**:
- If `isActivated = true`, pool must be `ActivatedHabitatPool`
- If `isActivated = false`, pool must be `NaturalHabitatPool`
- If reference pool not found, server logs error and rejects settings
6. **Custom Pool IDs**: Must start with `custom__`
---
## Network Flow
1. **Opening GUI**: Server sends `OpenHabitatBlockEditorPacket` with current `HabitatSettingsDTO`
2. **Saving Changes**: Client sends updated `HabitatSettingsDTO` back to server
3. **Server Processing**:
- `HabitatBlockEntity.applySettings()` validates and applies changes
- Calls `refreshFromSettings()` to regenerate spawn details
- Marks block entity as changed and syncs to clients
---
## Implementation Notes
- **Creative Mode Only**: GUI should only be accessible to creative mode players
---
## Example Configurations
### Example 1: Redstone-Triggered Shiny Spawner
```kotlin
isActivatedSpawning = true
phaseOrder = FIXED_RANDOM
numberOfPhases = 4
levelRange = 50..60
modifiers = "shiny"
mimicId = "minecraft:diamond_block"
activatedSettings:
trigger = REDSTONE
chance = 1.0
spawnRange = 10
maxSpawns = 1
maxSpawnsPerActivation = 1
habitatPool = (reference to existing pool)
```
### Example 2: Natural Spawn Replacement Zone
```kotlin
isActivatedSpawning = false
levelRange = 1..100
phaseOrder = SIMPLE
numberOfPhases = 1
modifiers = ""
mimicId = "minecraft:moss_block"
naturalSettings:
replaceSpawns = true
rangeOfInfluence = 32
habitatPool = (custom pool with specific Pokémon)
```
---
## Related Files
- `HabitatBlockEntity.kt` - Main block entity logic
- `HabitatSettingsDTO.kt` - Root settings container
- `ActivatedHabitatSettingsDTO.kt` - Activated mode settings
- `NaturalHabitatSettingsDTO.kt` - Natural mode settings
- `HabitatPoolSettingsDTO.kt` - Pool configuration
- `ActivatedHabitatSpawning.kt` - Activated spawning implementation
- `NaturalHabitatSpawning.kt` - Natural spawning implementation
+9
View File
@@ -0,0 +1,9 @@
IVs layer
Move layer
Remove nature layer in favour of modification layer
Reconsider form layer. Its timing seems more important than anything else
Remove cosmetic layer
Add shiny layer
Fix the way the client is the one deciding when hatching will happen from that TriggerEggHatchHandler
Clean up duplication in hatchPokemon logic for nest and incubator, should be a common function in EggComponent probably for hatching into a player's party
@@ -67,14 +67,14 @@ public abstract class BeeOccupantMixin {
if (state.is(BlockTags.BEEHIVES)) {
// position in front of the entrance, face away from the block
var facing = state.getValue(HorizontalDirectionalBlock.FACING);
newPos = pos.relative(facing).getCenter();
newPos = pos.relative(facing).getBottomCenter();
newYaw = facing.toYRot();
if (brain.checkMemory(CobblemonMemories.HIVE_LOCATION, MemoryStatus.REGISTERED)) {
brain.setMemory(CobblemonMemories.HIVE_LOCATION, pos); // This needs to be set in the case that the hive was picked up and moved.
}
} else {
// Block has likely been destroyed
var center = pos.getCenter();
var center = pos.getBottomCenter();
newPos = new Vec3(
center.x + level.random.nextFloat() * 0.6 - 0.3,
center.y + level.random.nextFloat() * 0.6 - 0.3,
@@ -0,0 +1,36 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.CobblemonItemComponents;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemModelShaper;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ItemModelShaper.class)
public class ItemModelShaperMixin {
@Inject(method = "getItemModel(Lnet/minecraft/world/item/ItemStack;)Lnet/minecraft/client/resources/model/BakedModel;", at = @At("HEAD"), cancellable = true)
public void getItemModel(ItemStack stack, CallbackInfoReturnable<BakedModel> cir) {
String eggModel = stack.get(CobblemonItemComponents.EGG_MODEL);
if (eggModel == null) return;
ModelResourceLocation modelResourceLocation = ModelResourceLocation.inventory(ResourceLocation.parse("cobblemon:egg/" + eggModel));
BakedModel bakedModel = Minecraft.getInstance().getModelManager().getModel(modelResourceLocation);
cir.setReturnValue(bakedModel);
}
}
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.resources.model.BlockStateModelLoader;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.profiling.ProfilerFiller;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.List;
import java.util.Map;
@Mixin(ModelBakery.class)
public abstract class ModelBakeryMixin {
@Final
@Shadow
private Map<ResourceLocation, BlockModel> modelResources;
@Shadow
protected abstract void loadItemModelAndDependencies(ResourceLocation modelLocation);
@Inject(method = "<init>", at = @At("TAIL"))
private void cobblemon$loadEggModels(
BlockColors blockColors,
ProfilerFiller profilerFiller,
Map<ResourceLocation, BlockModel> modelResources,
Map<ResourceLocation, List<BlockStateModelLoader.LoadedJson>> blockStateResources,
CallbackInfo ci
) {
for (ResourceLocation fileLocation : this.modelResources.keySet()) {
if (!fileLocation.getNamespace().equals("cobblemon")) continue;
String path = fileLocation.getPath();
if (!path.startsWith("models/item/egg/")) continue;
String modelPath = path.replace("models/item/", "").replace(".json", "");
ResourceLocation modelId = new ResourceLocation("cobblemon", modelPath);
this.loadItemModelAndDependencies(modelId);
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin.client;
import com.cobblemon.mod.common.client.CobblemonClient;
import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.Entity;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(Minecraft.class)
public class AIDebugGlowMixin {
@Inject(method = "shouldEntityAppearGlowing", at = @At("HEAD"), cancellable = true)
public void cobblemon$debugEntityGlow(Entity entity, CallbackInfoReturnable<Boolean> cir) {
if (entity.getId() == CobblemonClient.INSTANCE.getDebuggedEntityId()) {
cir.setReturnValue(true);
}
}
}
@@ -12,9 +12,11 @@ import com.cobblemon.mod.common.Cobblemon;
import com.cobblemon.mod.common.CobblemonItemComponents;
import com.cobblemon.mod.common.CobblemonItems;
import com.cobblemon.mod.common.ModAPI;
import com.cobblemon.mod.common.api.breeding.EggTextures;
import com.cobblemon.mod.common.item.PokeBallItem;
import com.cobblemon.mod.common.item.PokedexItem;
import com.cobblemon.mod.common.item.WearableItem;
import com.cobblemon.mod.common.item.components.EggComponent;
import com.cobblemon.mod.common.item.components.TMMoveComponent;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.multiplayer.ClientLevel;
@@ -56,20 +58,29 @@ public abstract class ItemRendererMixin {
at = @At("HEAD"),
cancellable = true
)
private void cobblemon$overrideItemModel(ItemStack stack, ItemDisplayContext renderMode, boolean leftHanded, PoseStack matrices, MultiBufferSource multiBufferSource, int light, int overlay, BakedModel model, CallbackInfo ci) {
boolean shouldBe2d = renderMode == ItemDisplayContext.GUI || renderMode == ItemDisplayContext.FIXED || stack.getItem() == CobblemonItems.TECHNICAL_MACHINE;
private void cobblemon$overrideItemModel(ItemStack stack, ItemDisplayContext renderMode, boolean leftHanded, PoseStack matrices, MultiBufferSource multiBufferSource, int light, int overlay, BakedModel model, CallbackInfo ci) throws Exception {
boolean shouldBe2d = renderMode == ItemDisplayContext.GUI || renderMode == ItemDisplayContext.FIXED || stack.getItem() == CobblemonItems.POKEMON_EGG || stack.getItem() == CobblemonItems.TECHNICAL_MACHINE;
ResourceLocation resourceLocation = null;
if (shouldBe2d) {
if (stack.getItem() instanceof PokeBallItem pokeBallItem) resourceLocation = pokeBallItem.getPokeBall().getModel2d();
else if (stack.getItem() instanceof PokedexItem pokedexItem) resourceLocation = pokedexItem.getType().getItemSpritePath();
else if (stack.getItem() == CobblemonItems.TECHNICAL_MACHINE) {
if (stack.getItem() instanceof PokeBallItem pokeBallItem) {
resourceLocation = pokeBallItem.getPokeBall().getModel2d();
} else if (stack.getItem() instanceof PokedexItem pokedexItem) {
resourceLocation = pokedexItem.getType().getItemSpritePath();
} else if (stack.getItem() == CobblemonItems.POKEMON_EGG) {
EggComponent component = stack.get(CobblemonItemComponents.EGG_DATA);
if (component != null) {
resourceLocation = EggTextures.getEggTexture(component.getIdentifier(), component.getVariant());
}
} else if (stack.getItem() == CobblemonItems.TECHNICAL_MACHINE) {
TMMoveComponent component = stack.get(CobblemonItemComponents.TM_MOVE);
if (component != null) {
resourceLocation = new ResourceLocation(Cobblemon.MODID, "tm/" + component.getMove().getElementalType().showdownId() + "_tm");
}
}
}
if (renderMode != ItemDisplayContext.HEAD && stack.getItem() instanceof WearableItem wearableItem) resourceLocation = wearableItem.getModel2d();
if (renderMode != ItemDisplayContext.HEAD && stack.getItem() instanceof WearableItem wearableItem) {
resourceLocation = wearableItem.getModel2d();
}
if (resourceLocation != null) {
BakedModel replacementModel = this.itemModelShaper.getModelManager().getModel(new ModelResourceLocation(resourceLocation, "inventory"));
@@ -54,6 +54,10 @@ import com.cobblemon.mod.common.api.storage.adapter.database.MongoDBStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.FileStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.JSONStoreAdapter
import com.cobblemon.mod.common.api.storage.adapter.flatfile.NBTStoreAdapter
import com.cobblemon.mod.common.api.storage.egg.EggStoreManager
import com.cobblemon.mod.common.api.storage.egg.JsonEggStoreBackend
import com.cobblemon.mod.common.api.storage.egg.MongoEggStoreBackend
import com.cobblemon.mod.common.api.storage.egg.NbtEggStoreBackend
import com.cobblemon.mod.common.api.storage.factory.FileBackedPokemonStoreFactory
import com.cobblemon.mod.common.api.storage.molang.NbtMoLangDataStoreFactory
import com.cobblemon.mod.common.api.storage.pc.PCStore
@@ -175,6 +179,7 @@ object Cobblemon {
var storage = PokemonStoreManager()
var molangData = NbtMoLangDataStoreFactory
lateinit var playerDataManager: PlayerInstancedDataStoreManager
lateinit var eggStoreManager: EggStoreManager
lateinit var starterConfig: StarterConfig
val dataProvider: DataProvider = CobblemonDataProvider
var permissionValidator: PermissionValidator by Delegates.observable(LaxPermissionValidator().also { it.initialize() }) { _, _, newValue -> newValue.initialize() }
@@ -183,6 +188,8 @@ object Cobblemon {
var wallpapers = mutableMapOf<UUID, Set<ResourceLocation>>()
val serverPlayerStructs = mutableMapOf<UUID, ObjectValue<Player>>()
/** Player UUID to entity UUID that they're brain debuggin' */
val serverPlayerDebuggingPokemonBrainEntities = mutableMapOf<UUID, UUID>()
val statistics: CobblemonStats = CobblemonStats
@@ -205,6 +212,8 @@ object Cobblemon {
this.LOGGER.info(" - Branch: ${CobblemonBuildDetails.BRANCH}")
}
this.loadConfig()
implementation.registerRecipeSerializers()
implementation.registerRecipeTypes()
implementation.registerPermissionValidator()
@@ -233,7 +242,6 @@ object Cobblemon {
ExperienceGroups.registerDefaults()
CaptureCalculators.registerDefaults()
this.loadConfig()
// CobblemonBlockPredicates.touch()
CobblemonOrePlacedFeatures.register()
CobblemonPlacedFeatures.register()
@@ -259,6 +267,7 @@ object Cobblemon {
playerDataManager.onPlayerDisconnect(it.player)
RequestManager.onLogoff(it.player)
serverPlayerStructs.remove(it.player.uuid)
serverPlayerDebuggingPokemonBrainEntities.remove(it.player.uuid)
}
PlatformEvents.PLAYER_DEATH.subscribe {
PCLinkManager.removeLink(it.player.uuid)
@@ -375,6 +384,12 @@ object Cobblemon {
playerDataManager = PlayerInstancedDataStoreManager().also { it.setup(server) }
HabitatPools.onServerLoading(server)
val eggBackend = when (config.storageFormat) {
"nbt" -> NbtEggStoreBackend()
"json" -> JsonEggStoreBackend()
else -> null // MongoDB handled below
}
val mongoClient: MongoClient?
val pokemonStoreRoot = server.getWorldPath(LevelResource.ROOT).resolve("pokemon").toFile()
@@ -426,6 +441,10 @@ object Cobblemon {
playerDataManager.setFactory(generalMongoFactory, PlayerInstancedDataStoreTypes.GENERAL)
playerDataManager.setFactory(pokedexMongoFactory, PlayerInstancedDataStoreTypes.POKEDEX)
playerDataManager.setFactory(tmMovesMongoFactory, PlayerInstancedDataStoreTypes.TM_MOVES)
eggStoreManager = EggStoreManager(MongoEggStoreBackend(mongoClient, config.mongoDBDatabaseName))
eggStoreManager.setup(server)
MongoDBStoreAdapter(mongoClient, config.mongoDBDatabaseName)
} catch (e: ClassNotFoundException) {
LOGGER.error("MongoDB driver not found.")
@@ -439,6 +458,11 @@ object Cobblemon {
}
.with(ReforgedConversion(server.getWorldPath(LevelResource.ROOT))) as FileStoreAdapter<*>
if (eggBackend != null) {
eggStoreManager = EggStoreManager(eggBackend)
eggStoreManager.setup(server)
}
storage.registerFactory(
priority = Priority.LOWEST,
factory = FileBackedPokemonStoreFactory(
@@ -451,6 +475,7 @@ object Cobblemon {
PlatformEvents.SERVER_STOPPED.subscribe {
storage.unregisterAll(it.server.registryAccess())
eggStoreManager.shutdown()
playerDataManager.saveAllStores()
playerDataManager.saveExecutor.shutdown()
playerDataManager.saveExecutor.awaitTermination(30L, TimeUnit.SECONDS)
@@ -12,6 +12,8 @@ import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.ai.CobblemonBehaviour
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.config.task.TaskConfig
import com.cobblemon.mod.common.api.data.JsonDataRegistry
import com.cobblemon.mod.common.api.data.JsonDataRegistry.Companion.JSON_EXTENSION
@@ -26,6 +28,8 @@ import com.cobblemon.mod.common.util.adapters.ExpressionLikeAdapter
import com.cobblemon.mod.common.util.adapters.ExpressionOrEntityVariableAdapter
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.adapters.MemoryModuleTypeAdapter
import com.cobblemon.mod.common.util.adapters.ObjectiveConfigAdapter
import com.cobblemon.mod.common.util.adapters.SenseConfigAdapter
import com.cobblemon.mod.common.util.adapters.SensorTypeAdapter
import com.cobblemon.mod.common.util.adapters.TaskConfigAdapter
import com.cobblemon.mod.common.util.adapters.TranslatedTextAdapter
@@ -55,6 +59,8 @@ object CobblemonBehaviours : JsonDataRegistry<CobblemonBehaviour> {
.registerTypeAdapter(SensorType::class.java, SensorTypeAdapter)
.registerTypeAdapter(BehaviourConfig::class.java, BehaviourConfigAdapter)
.registerTypeAdapter(TaskConfig::class.java, TaskConfigAdapter)
.registerTypeAdapter(ObjectiveConfig::class.java, ObjectiveConfigAdapter)
.registerTypeAdapter(SenseConfig::class.java, SenseConfigAdapter)
.registerTypeAdapter(
TypeToken.getParameterized(Either::class.java, Expression::class.java, MoLangConfigVariable::class.java).type,
ExpressionOrEntityVariableAdapter
@@ -9,6 +9,7 @@
package com.cobblemon.mod.common
import com.cobblemon.mod.common.block.entity.*
import com.cobblemon.mod.common.block.entity.DisplayCaseBlockEntity
import com.cobblemon.mod.common.block.habitat.HabitatBlockEntity
import com.cobblemon.mod.common.block.multiblock.FossilMultiblockBuilder
import com.cobblemon.mod.common.platform.PlatformRegistry
@@ -46,12 +47,10 @@ object CobblemonBlockEntities : PlatformRegistry<Registry<BlockEntityType<*>>, R
val HANGING_SIGN: BlockEntityType<CobblemonHangingSignBlockEntity> = this.create("hanging_sign", BlockEntityType.Builder.of(::CobblemonHangingSignBlockEntity, CobblemonBlocks.APRICORN_HANGING_SIGN, CobblemonBlocks.APRICORN_WALL_HANGING_SIGN, CobblemonBlocks.SACCHARINE_HANGING_SIGN, CobblemonBlocks.SACCHARINE_WALL_HANGING_SIGN).build(null))
@JvmField
val TM_MACHINE: BlockEntityType<TMMachineBlockEntity> = this.create("tm_machine", BlockEntityType.Builder.of(::TMMachineBlockEntity, CobblemonBlocks.TM_MACHINE).build(null))
@JvmField
val HABITAT_BLOCK: BlockEntityType<HabitatBlockEntity> = this.create("habitat_block",
BlockEntityType.Builder.of(::HabitatBlockEntity, CobblemonBlocks.HABITAT_BLOCK).build(null)
)
@JvmField
val GILDED_CHEST: BlockEntityType<GildedChestBlockEntity> = this.create("chest", BlockEntityType.Builder.of(::GildedChestBlockEntity,
CobblemonBlocks.GILDED_CHEST,
@@ -85,6 +84,38 @@ object CobblemonBlockEntities : PlatformRegistry<Registry<BlockEntityType<*>>, R
).build(null)
)
val NEST: BlockEntityType<NestBlockEntity> = this.create("nest",
BlockEntityType.Builder.of(
::NestBlockEntity,
CobblemonBlocks.NEST_FIERY,
CobblemonBlocks.NEST_GRASSY,
CobblemonBlocks.NEST_LEAFY,
CobblemonBlocks.NEST_ICY,
CobblemonBlocks.NEST_ROCKY,
CobblemonBlocks.NEST_SANDY,
CobblemonBlocks.NEST_SHROOMY,
CobblemonBlocks.NEST_TWIGGY,
CobblemonBlocks.NEST_HAY,
CobblemonBlocks.NEST_KELP,
CobblemonBlocks.NEST_WATERY
).build(null))
val EGG: BlockEntityType<EggBlockEntity> = this.create("egg",
BlockEntityType.Builder.of(
::EggBlockEntity,
CobblemonBlocks.EGG
).build(null)
)
@JvmField
val INCUBATOR: BlockEntityType<IncubatorBlockEntity> = this.create("incubator",
BlockEntityType.Builder.of(
::IncubatorBlockEntity,
CobblemonBlocks.INCUBATOR
).build(null)
)
@JvmField
val DISPLAY_CASE: BlockEntityType<DisplayCaseBlockEntity> = this.create("display_case",
BlockEntityType.Builder.of(::DisplayCaseBlockEntity, CobblemonBlocks.DISPLAY_CASE).build(null)
@@ -9,10 +9,52 @@
package com.cobblemon.mod.common
import com.cobblemon.mod.common.api.apricorn.Apricorn
import com.cobblemon.mod.common.api.nest.WildNestType
import com.cobblemon.mod.common.api.nest.WildNestVariant
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.block.*
import com.cobblemon.mod.common.block.ApricornBlock
import com.cobblemon.mod.common.block.ApricornSaplingBlock
import com.cobblemon.mod.common.block.BerryBlock
import com.cobblemon.mod.common.block.BigRootBlock
import com.cobblemon.mod.common.block.CoinPouchBlock
import com.cobblemon.mod.common.block.DamagedMonitorBlock
import com.cobblemon.mod.common.block.DecorativeItemBlock
import com.cobblemon.mod.common.block.DiscShelfBlock
import com.cobblemon.mod.common.block.DisplayCaseBlock
import com.cobblemon.mod.common.block.EggBlock
import com.cobblemon.mod.common.block.EjectButtonBlock
import com.cobblemon.mod.common.block.EnergyRootBlock
import com.cobblemon.mod.common.block.FossilAnalyzerBlock
import com.cobblemon.mod.common.block.GalaricaWreathBlock
import com.cobblemon.mod.common.block.HealingMachineBlock
import com.cobblemon.mod.common.block.HeartyGrainsBlock
import com.cobblemon.mod.common.block.IncubatorBlock
import com.cobblemon.mod.common.block.LecternBlock
import com.cobblemon.mod.common.block.MagnetBlock
import com.cobblemon.mod.common.block.MedicinalLeekBlock
import com.cobblemon.mod.common.block.MintBlock
import com.cobblemon.mod.common.block.MintBlock.MintType
import com.cobblemon.mod.common.block.MonitorBlock
import com.cobblemon.mod.common.block.NestBlock
import com.cobblemon.mod.common.block.NutBushBlock
import com.cobblemon.mod.common.block.OrbBlock
import com.cobblemon.mod.common.block.PCBlock
import com.cobblemon.mod.common.block.PastureBlock
import com.cobblemon.mod.common.block.PlaqueBlock
import com.cobblemon.mod.common.block.PokeSnackBlock
import com.cobblemon.mod.common.block.RestorationTankBlock
import com.cobblemon.mod.common.block.RevivalHerbBlock
import com.cobblemon.mod.common.block.SaccharineLeafBlock
import com.cobblemon.mod.common.block.SaccharineLogBlock
import com.cobblemon.mod.common.block.SaccharineLogSlatheredBlock
import com.cobblemon.mod.common.block.StackableItemBlock
import com.cobblemon.mod.common.block.TumblestoneBlock
import com.cobblemon.mod.common.block.TypeGemClusterBlock
import com.cobblemon.mod.common.block.TypeGemCoreBlock
import com.cobblemon.mod.common.block.VivichokeBlock
import com.cobblemon.mod.common.block.WallAttachedDirectionalShapeBlock
import com.cobblemon.mod.common.block.WallAttachedStackableItemBlock
import com.cobblemon.mod.common.block.WildNestBlock
import com.cobblemon.mod.common.block.campfirepot.CampfireBlock
import com.cobblemon.mod.common.block.campfirepot.CampfirePotBlock
import com.cobblemon.mod.common.block.chest.GildedChestBlock
@@ -630,7 +672,7 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
val GALARICA_WREATH = create("galarica_wreath", GalaricaWreathBlock(BlockBehaviour.Properties.of().sound(SoundType.AZALEA_LEAVES).mapColor(MapColor.NONE).noOcclusion().noCollission()))
@JvmField
val FLAME_ORB = create("flame_orb", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().lightLevel{15}))
val FLAME_ORB = create("flame_orb",OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion().lightLevel { 15 }))
@JvmField
val TOXIC_ORB = create("toxic_orb", OrbBlock(BlockBehaviour.Properties.of().sound(SoundType.GLASS).mapColor(MapColor.NONE).noOcclusion()))
@JvmField
@@ -801,7 +843,16 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
@JvmField
val LECTERN = create("lectern", LecternBlock(BlockBehaviour.Properties.of().mapColor(MapColor.WOOD).instrument(NoteBlockInstrument.BASS).sound(SoundType.WOOD).strength(2.5F).ignitedByLava().lightLevel { if (it.getValue(LecternBlock.EMIT_LIGHT) as Boolean) 13 else 0 }))
val LECTERN = create("lectern", LecternBlock(
BlockBehaviour.Properties
.of()
.mapColor(MapColor.WOOD)
.instrument(NoteBlockInstrument.BASS)
.sound(SoundType.WOOD)
.strength(2.5F)
.ignitedByLava()
.lightLevel { if (it.getValue(LecternBlock.EMIT_LIGHT) as Boolean) 13 else 0 }
))
@JvmField
val DISC_SHELF = create("disc_shelf", DiscShelfBlock(BlockBehaviour.Properties.of().mapColor(MapColor.WOOD).instrument(NoteBlockInstrument.BASS).sound(SoundType.METAL).strength(2.5F)))
@@ -1033,6 +1084,82 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
val YACHE_BERRY = this.berryBlock("yache")
//val BINDING_SOIL = this.create("binding_soil", BindingSoilBlock(BlockBehaviour.Properties.of()))
val NEST_FIERY = this.create(
"nest_fiery",
WildNestBlock.create(
WildNestType.FIERY,
BlockBehaviour.Properties.of()
.noOcclusion()
.pushReaction(PushReaction.DESTROY)
.lightLevel { state ->
val variant = (state.block as? WildNestBlock)?.variantProperty?.let { state.getValue(it) }
when (variant) {
WildNestVariant.FIERY_NETHERRACK -> 15
WildNestVariant.FIERY_SOUL_SAND -> 10
else -> 3
}
}
)
)
val NEST_GRASSY = this.create(
"nest_grassy",
WildNestBlock.create(WildNestType.GRASSY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_LEAFY = this.create(
"nest_leafy",
WildNestBlock.create(WildNestType.LEAFY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_ICY = this.create(
"nest_icy",
WildNestBlock.create(WildNestType.ICY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_HAY = this.create(
"nest_hay",
WildNestBlock.create(WildNestType.PLAYER, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_KELP = this.create(
"nest_kelp",
WildNestBlock.create(WildNestType.KELP, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_ROCKY = this.create(
"nest_rocky",
WildNestBlock.create(WildNestType.ROCKY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_SANDY = this.create(
"nest_sandy",
WildNestBlock.create(WildNestType.SANDY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_SHROOMY = this.create(
"nest_shroomy",
WildNestBlock.create(WildNestType.SHROOMY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_TWIGGY = this.create(
"nest_twiggy",
WildNestBlock.create(WildNestType.TWIGGY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val NEST_WATERY = this.create(
"nest_watery",
WildNestBlock.create(WildNestType.WATERY, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
)
val EGG = this.create("egg", EggBlock(BlockBehaviour.Properties
.ofFullCopy(Blocks.DRAGON_EGG)
.pushReaction(PushReaction.BLOCK)
.sound(SoundType.BONE_BLOCK)
))
@JvmField
val INCUBATOR = this.create("incubator", IncubatorBlock(BlockBehaviour.Properties.of()
.mapColor(MapColor.COLOR_LIGHT_GRAY)
.sound(SoundType.METAL)
.strength(Blocks.COAL_BLOCK.defaultDestroyTime(), Blocks.DIAMOND_ORE.explosionResistance)
.noOcclusion()
.pushReaction(PushReaction.BLOCK)
.lightLevel { state ->
if (state.getValue(IncubatorBlock.HAS_EGG) && !state.getValue(IncubatorBlock.READY)) 8 else 0 // emit light only when warming the egg
}
))
init {
/**
* Makes all blocks in array flammable by adding them to FireBlock's flammableRegistry.
@@ -1073,6 +1200,12 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, ResourceKey<Registry<
return block
}
private fun nestBlock(variant: NestBlock.NestVariant): NestBlock {
val identifier = cobblemonResource(variant.serializedName)
val block = NestBlock(variant, BlockBehaviour.Properties.of().noOcclusion().pushReaction(PushReaction.DESTROY))
return this.create(identifier.path, block)
}
/**
* Calls helper method from Vanilla
*/
@@ -61,6 +61,8 @@ object CobblemonCommands {
ChangeBoxWallpaperCommand.register(dispatcher)
RunMolangCommand.register(dispatcher)
RunMolangScriptCommand.register(dispatcher)
GivePokemonEggCommand.register(dispatcher)
GiveAllPokemonEggCommand.register(dispatcher)
SpectateBattleCommand.register(dispatcher)
CobblemonConfigCommand.register(dispatcher)
UnlockPCBoxWallpaperCommand.register(dispatcher)
@@ -73,9 +75,11 @@ object CobblemonCommands {
PcTakeCommand.register(dispatcher)
GiveTmCommand.register(dispatcher)
TmCommand.register(dispatcher)
BreedPokemonCommand.register(dispatcher)
// Possibly lock down registration if and only if under dev environment or running in an environment
// with a certain system environment variable set
CobblemonInfoCommand.register(dispatcher)
DebugCobblemonAICommand.register(dispatcher)
}
}
@@ -26,6 +26,8 @@ import net.minecraft.world.entity.LivingEntity
import net.minecraft.resources.ResourceKey
import net.minecraft.world.entity.MobCategory
import net.minecraft.world.entity.ai.attributes.AttributeSupplier
import com.cobblemon.mod.common.entity.RealtimeMoveProjectile
import com.example.mod.entity.RealtimeMoveAreaEffect
object CobblemonEntities : PlatformRegistry<Registry<EntityType<*>>, ResourceKey<Registry<EntityType<*>>>, EntityType<*>>() {
@@ -87,6 +89,25 @@ object CobblemonEntities : PlatformRegistry<Registry<EntityType<*>>, ResourceKey
.build(GENERIC_BEDROCK_ENTITY_KEY.toString())
)
@JvmField
val REALTIME_MOVE_PROJECTILE_ENTITY_KEY = cobblemonResource("realtime_move_projectile")
@JvmField
val REALTIME_MOVE_PROJECTILE_ENTITY: EntityType<RealtimeMoveProjectile> = this.create(
REALTIME_MOVE_PROJECTILE_ENTITY_KEY.path,
EntityType.Builder.of({ _, world -> RealtimeMoveProjectile(world) }, MobCategory.MISC)
.build(REALTIME_MOVE_PROJECTILE_ENTITY_KEY.toString())
)
@JvmField
val REALTIME_MOVE_PROJECTILE_AOE_KEY = cobblemonResource("realtime_move_aoe")
@JvmField
val REALTIME_MOVE_PROJECTILE_AOE: EntityType<RealtimeMoveAreaEffect> = this.create(
REALTIME_MOVE_PROJECTILE_AOE_KEY.path,
EntityType.Builder.of({ _, world -> RealtimeMoveAreaEffect(world) }, MobCategory.MISC)
.build(REALTIME_MOVE_PROJECTILE_AOE_KEY.toString())
)
@JvmField
val NPC_KEY = cobblemonResource("npc")
@JvmField
@@ -18,6 +18,7 @@ import net.minecraft.core.registries.Registries
import net.minecraft.network.codec.ByteBufCodecs
import net.minecraft.resources.ResourceKey
import net.minecraft.resources.ResourceLocation
import net.minecraft.util.ExtraCodecs
object CobblemonItemComponents : PlatformRegistry<Registry<DataComponentType<*>>, ResourceKey<Registry<DataComponentType<*>>>, DataComponentType<*>>() {
@@ -68,6 +69,16 @@ object CobblemonItemComponents : PlatformRegistry<Registry<DataComponentType<*>>
.persistent(FoodColourComponent.CODEC)
.networkSynchronized(FoodColourComponent.PACKET_CODEC)
.build())
@JvmField
val EGG_DATA: DataComponentType<EggComponent> = create("egg", DataComponentType.builder<EggComponent>()
.persistent(EggComponent.CODEC) // For saving/loading
.networkSynchronized(EggComponent.PACKET_CODEC) // For network synchronization
.build())
@JvmField
val EGG_MODEL: DataComponentType<String> = create("egg_model", DataComponentType.builder<String>()
.persistent(ExtraCodecs.NON_EMPTY_STRING)
.networkSynchronized(ByteBufCodecs.STRING_UTF8)
.build())
@JvmField
val TM_MOVE: DataComponentType<TMMoveComponent> = create("tm_move", DataComponentType.builder<TMMoveComponent>()
@@ -111,6 +122,8 @@ object CobblemonItemComponents : PlatformRegistry<Registry<DataComponentType<*>>
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:ingredient"), INGREDIENT)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:food"), FOOD)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:mob_effects"), MOB_EFFECTS)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:egg_data"), EGG_DATA)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:egg_model"), EGG_MODEL)
Registry.register(BuiltInRegistries.DATA_COMPONENT_TYPE, ResourceLocation.parse("cobblemon:held_item_effect"), HELD_ITEM_EFFECT)
}
@@ -602,6 +602,22 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
@JvmField val BERRY_JUICE = this.create("berry_juice", BerryJuiceItem())
val NEST_GRASSY = blockItem("nest_grassy", CobblemonBlocks.NEST_GRASSY)
val NEST_LEAFY = blockItem("nest_leafy", CobblemonBlocks.NEST_LEAFY)
val NEST_FIERY = blockItem("nest_fiery", CobblemonBlocks.NEST_FIERY)
val NEST_ICY = blockItem("nest_icy", CobblemonBlocks.NEST_ICY)
val NEST_HAY = blockItem("nest_hay", CobblemonBlocks.NEST_HAY)
val NEST_KELP = blockItem("nest_kelp", CobblemonBlocks.NEST_KELP)
val NEST_ROCKY = blockItem("nest_rocky", CobblemonBlocks.NEST_ROCKY)
val NEST_SANDY = blockItem("nest_sandy", CobblemonBlocks.NEST_SANDY)
val NEST_SHROOMY = blockItem("nest_shroomy", CobblemonBlocks.NEST_SHROOMY)
val NEST_TWIGGY = blockItem("nest_twiggy", CobblemonBlocks.NEST_TWIGGY)
val NEST_WATERY = blockItem("nest_watery", CobblemonBlocks.NEST_WATERY)
@JvmField
val INCUBATOR = blockItem("incubator", CobblemonBlocks.INCUBATOR)
@JvmField
val HABITAT_BLOCK = blockItem("habitat_block", CobblemonBlocks.HABITAT_BLOCK)
@@ -961,7 +977,7 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
@JvmField
val CLEAR_AMULET = heldItem("clear_amulet")
@JvmField
val DESTINY_KNOT = itemNameBlockItem("destiny_knot", CobblemonBlocks.DESTINY_KNOT)
val DESTINY_KNOT = create("destiny_knot", ItemNameBlockItem(CobblemonBlocks.DESTINY_KNOT, Item.Properties().durability(256)))
@JvmField
val DRAGON_FANG = heldItem("dragon_fang")
@JvmField
@@ -1557,6 +1573,10 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
//@JvmField
//val BINDING_SOIL = blockItem("binding_soil", CobblemonBlocks.BINDING_SOIL)
@JvmField
val POKEMON_EGG = eggItem("egg", CobblemonBlocks.EGG, Item.Properties().stacksTo(1))
private fun eggItem(name: String, block: Block, settings: Item.Properties = Item.Properties()): BlockItem = this.create(name, BlockItem(block, settings))
private fun blockItem(name: String, block: Block, rarity: Rarity = Rarity.COMMON): BlockItem = this.create(name, BlockItem(block, Item.Properties().rarity(rarity)))
@@ -1655,9 +1675,9 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, ResourceKey<Registry<It
return create(name, RegionalFoodItem(properties))
}
private fun heldItem(name: String, remappedName: String? = null): CobblemonItem = create(
private fun heldItem(name: String, remappedName: String? = null, settings:Item.Properties = Item.Properties()): CobblemonItem = create(
name,
CobblemonItem(Item.Properties()).also {
CobblemonItem(settings).also {
if (remappedName != null) {
CobblemonHeldItemManager.registerRemap(it, remappedName)
}
@@ -12,15 +12,17 @@ import com.cobblemon.mod.common.api.ai.CobblemonAttackTargetData
import com.cobblemon.mod.common.api.ai.CobblemonWanderControl
import com.cobblemon.mod.common.api.dialogue.ActiveDialogue
import com.cobblemon.mod.common.api.moves.animations.ActionEffectContext
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.ListCodec
import com.mojang.serialization.codecs.PrimitiveCodec
import java.util.Optional
import java.util.UUID
import net.minecraft.core.BlockPos
import net.minecraft.core.GlobalPos
import net.minecraft.core.UUIDUtil
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import java.util.*
import net.minecraft.world.entity.player.Player
object CobblemonMemories {
val memories = mutableMapOf<String, MemoryModuleType<*>>()
@@ -39,6 +41,14 @@ object CobblemonMemories {
@JvmField
val ACTIVE_ACTION_EFFECT = register<ActionEffectContext>("active_action_effect")
@JvmField
val POTENTIAL_MATE = register<PokemonEntity>("potential_mate")
@JvmField
val MATE_SCAN_COOLDOWN = register("mate_scan_cooldown", PrimitiveCodec.BOOL)
@JvmField
val NEST_LOCATION = register<BlockPos>("nest_location")
@JvmField
val PATERNAL_NEST_LOCATION = register<BlockPos>("paternal_nest", BlockPos.CODEC)
@JvmField
val POKEMON_FLYING = register("pokemon_flying", PrimitiveCodec.BOOL)
@JvmField
val POKEMON_DROWSY = register("pokemon_drowsy", PrimitiveCodec.BOOL)
@@ -55,16 +65,28 @@ object CobblemonMemories {
@JvmField
val NEARBY_GROWABLE_CROPS = register<BlockPos>("nearby_growable_crops")
@JvmField
val EGG_THIEF = register<Player>("egg_thief") // Stores the player stealing the egg
@JvmField
val EGG_THIEF_LAST_SEEN_TICK = register("egg_thief_last_seen_tick", PrimitiveCodec.LONG)
@JvmField
val EGG_LOCATION = register<BlockPos>("egg_location") // Stores the last known location of the egg
@JvmField
val EGG_IN_NEST = register("egg_in_nest", PrimitiveCodec.BOOL)
@JvmField
val HOLDING_EGG = register("holding_egg", PrimitiveCodec.BOOL)
@JvmField
val EGG_SEARCH_COUNTDOWN = register ("egg_search_countdown", PrimitiveCodec.BOOL)
@JvmField
val IDEAL_NEST_LOCATION = register<BlockPos>("ideal_nest_location")
@JvmField
val NEST_DESPAWN_IMMUNE_UNTIL_TICK = register("nest_despawn_immune_until_tick", PrimitiveCodec.LONG)
@JvmField
val NEARBY_SWEET_BERRY_BUSH = register<BlockPos>("nearest_sweet_berry_bush")
@JvmField
val DISABLE_WALK_TO_BERRY_BUSH = register<Boolean>("disable_walk_to_berry_bush")
@JvmField
val TIME_TRYING_TO_REACH_BERRY_BUSH = register<Int>("time_trying_to_reach_berry_bush")
@JvmField
val IS_CONSUMING_ITEM = register<Boolean>("is_consuming_item")
@JvmField
val RECENTLY_ATE_GRASS = register<Boolean>("recently_ate_grass")
@JvmField
val HIVE_LOCATION = register<BlockPos>("hive_location", BlockPos.CODEC)
@JvmField
val HIVE_BLACKLIST = register<List<BlockPos>>("hive_blacklist")
@@ -106,4 +128,4 @@ object CobblemonMemories {
memories[id] = memoryModule
return memoryModule
}
}
}
@@ -22,6 +22,7 @@ import com.cobblemon.mod.common.client.net.data.CobblemonMechanicsSyncHandler
import com.cobblemon.mod.common.client.net.data.DataRegistrySyncPacketHandler
import com.cobblemon.mod.common.client.net.data.RideSettingsSyncHandler
import com.cobblemon.mod.common.client.net.debug.OpenRidingStatsDebugGUIHandler
import com.cobblemon.mod.common.client.net.debug.UpdateTrackedBrainDataHandler
import com.cobblemon.mod.common.client.net.dialogue.DialogueClosedHandler
import com.cobblemon.mod.common.client.net.dialogue.DialogueOpenedHandler
import com.cobblemon.mod.common.client.net.effect.PokeSnackBlockParticlesHandler
@@ -84,6 +85,7 @@ import com.cobblemon.mod.common.net.messages.client.cooking.SeasoningRegistrySyn
import com.cobblemon.mod.common.net.messages.client.cooking.ToggleCookingPotLidPacket
import com.cobblemon.mod.common.net.messages.client.data.*
import com.cobblemon.mod.common.net.messages.client.debug.RequestOpenRidingStatsDebugGUIPacket
import com.cobblemon.mod.common.net.messages.client.debug.UpdateTrackedBrainDataPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueClosedPacket
import com.cobblemon.mod.common.net.messages.client.dialogue.DialogueOpenedPacket
import com.cobblemon.mod.common.net.messages.client.effect.PokeSnackBlockParticlesPacket
@@ -166,6 +168,7 @@ import com.cobblemon.mod.common.net.messages.server.behaviour.DamageOnCollisionP
import com.cobblemon.mod.common.net.messages.server.behaviour.SetEntityBehaviourPacket
import com.cobblemon.mod.common.net.messages.server.block.AdjustBlockEntityViewerCountPacket
import com.cobblemon.mod.common.net.messages.server.block.TMMachineTeachMovePacket
import com.cobblemon.mod.common.net.messages.server.breeding.TriggerEggHatchPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectedPacket
import com.cobblemon.mod.common.net.messages.server.callback.party.PartyPokemonSelectedPacket
@@ -224,6 +227,7 @@ import com.cobblemon.mod.common.net.serverhandling.behaviour.DamageOnCollisionPa
import com.cobblemon.mod.common.net.serverhandling.behaviour.SetEntityBehaviourHandler
import com.cobblemon.mod.common.net.serverhandling.block.AdjustBlockEntityViewerCountHandler
import com.cobblemon.mod.common.net.serverhandling.block.TMMachineTeachMoveHandler
import com.cobblemon.mod.common.net.serverhandling.breeding.TriggerEggHatchHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartyPokemonSelectedHandler
@@ -516,6 +520,8 @@ object CobblemonNetwork {
// Debug
list.add(PacketRegisterInfo(OpenRidingStatsDebugGUIPacket.ID, OpenRidingStatsDebugGUIPacket::decode, OpenRidingStatsDebugGUIHandler))
list.add(PacketRegisterInfo(UpdateTrackedBrainDataPacket.ID, UpdateTrackedBrainDataPacket::decode, UpdateTrackedBrainDataHandler))
return list
@@ -639,6 +645,9 @@ object CobblemonNetwork {
list.add(PacketRegisterInfo(SetActiveTMPacket.ID, SetActiveTMPacket::decode, SetActiveTMPacketHandler))
list.add(PacketRegisterInfo(SetTMMachineContainerDataPacket.ID, SetTMMachineContainerDataPacket::decode, SetTMMachineContainerDataPacketHandler))
// Breeding Packets
list.add(PacketRegisterInfo(TriggerEggHatchPacket.ID, TriggerEggHatchPacket::decode, TriggerEggHatchHandler))
// Behaviour Packets
list.add(PacketRegisterInfo(SetEntityBehaviourPacket.ID, SetEntityBehaviourPacket::decode, SetEntityBehaviourHandler))
list.add(PacketRegisterInfo(DamageOnCollisionPacket.ID, DamageOnCollisionPacket::decode, DamageOnCollisionPacketHandler))
@@ -18,6 +18,7 @@ import net.minecraft.resources.ResourceKey
import net.minecraft.world.entity.ai.village.poi.PoiType
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.Blocks
object CobblemonPoiTypes: PlatformRegistry<Registry<PoiType>, ResourceKey<Registry<PoiType>>, PoiType>() {
override val registry: Registry<PoiType> = BuiltInRegistries.POINT_OF_INTEREST_TYPE
@@ -34,6 +35,8 @@ object CobblemonPoiTypes: PlatformRegistry<Registry<PoiType>, ResourceKey<Regist
val HABITAT_BLOCK_KEY: ResourceKey<PoiType> = createKey("habitat_block", CobblemonBlocks.HABITAT_BLOCK, 0, 1)
@JvmField
val HABITAT_BLOCK = create(HABITAT_BLOCK_KEY.location().path, PoiType(getBlockStates(CobblemonBlocks.HABITAT_BLOCK), 0, 1))
@JvmField
val JUKEBOX_KEY = createKey("vanilla_jukebox", Blocks.JUKEBOX, 0, 1)
private fun createKey(string: String, block: Block, maxTickets: Int, validRange: Int ): ResourceKey<PoiType> =
ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, cobblemonResource(string)).also { resourceKey ->
@@ -0,0 +1,59 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.data.JsonDataRegistry
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.api.types.ElementalType
import com.cobblemon.mod.common.api.types.adapters.ElementalTypeAdapter
import com.cobblemon.mod.common.pokemon.ai.moves.RealTimeMove
import com.cobblemon.mod.common.pokemon.ai.moves.events.MoveEventAction
import com.cobblemon.mod.common.util.adapters.ExpressionAdapter
import com.cobblemon.mod.common.util.adapters.ExpressionLikeAdapter
import com.cobblemon.mod.common.util.adapters.IdentifierAdapter
import com.cobblemon.mod.common.util.adapters.RealTimeMoveConfigAdapter
import com.cobblemon.mod.common.util.adapters.RealTimeMoveEventActionConfigAdapter
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import net.minecraft.resources.ResourceLocation
import net.minecraft.server.level.ServerPlayer
import net.minecraft.server.packs.PackType
object CobblemonRealTimeMoves : JsonDataRegistry<RealTimeMove> {
override val type = PackType.SERVER_DATA
override val observable = SimpleObservable<CobblemonRealTimeMoves>()
override val typeToken = TypeToken.get(RealTimeMove::class.java)
override val resourcePath: String = "real_time_moves"
override val id: ResourceLocation = cobblemonResource(resourcePath)
override val gson: Gson = GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(ResourceLocation::class.java, IdentifierAdapter)
.registerTypeAdapter(ExpressionLike::class.java, ExpressionLikeAdapter)
.registerTypeAdapter(Expression::class.java, ExpressionAdapter)
.registerTypeAdapter(RealTimeMove::class.java, RealTimeMoveConfigAdapter)
.registerTypeAdapter(MoveEventAction::class.java, RealTimeMoveEventActionConfigAdapter)
.registerTypeAdapter(ElementalType::class.java, ElementalTypeAdapter)
.create()
val realTimeMoves = mutableMapOf<ResourceLocation, RealTimeMove>()
override fun reload(data: Map<ResourceLocation, RealTimeMove>) {
realTimeMoves.clear()
data.forEach { location, move -> move.id = location }
realTimeMoves.putAll(data)
}
override fun sync(player: ServerPlayer) {
// nah
}
}
@@ -9,13 +9,13 @@
package com.cobblemon.mod.common
import com.cobblemon.mod.common.entity.pokemon.ai.sensors.*
import com.cobblemon.mod.common.pokemon.ai.PokemonDisturbancesSensor
import com.cobblemon.mod.common.entity.sensor.BattlingPokemonSensor
import com.cobblemon.mod.common.entity.sensor.NPCBattlingSensor
import java.util.function.Supplier
import com.cobblemon.mod.common.pokemon.ai.PokemonDisturbancesSensor
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.ai.sensing.Sensor
import net.minecraft.world.entity.ai.sensing.SensorType
import java.util.function.Supplier
object CobblemonSensors {
val sensors = mutableMapOf<String, SensorType<*>>()
@@ -49,9 +49,6 @@ object CobblemonSensors {
@JvmField
val NEARBY_FLOWER = register("nearby_flower", ::FlowerSensor)
@JvmField
val NEARBY_SWEET_BERRY_BUSH = register("nearby_sweet_berry_bush", ::SweetBerryBushSensor)
@JvmField
val POKEMON_NEARBY_WANTED_ITEM = register("pokemon_nearby_wanted_item", ::PokemonItemSensor)
@@ -64,4 +61,4 @@ object CobblemonSensors {
sensors[id] = sensor
return sensor
}
}
}
@@ -94,6 +94,9 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, ResourceKey<Regi
@JvmField
val POKEDEX_SCAN_ZOOM_INCREMENT = this.create("item.pokedex.scan_zoom_increment")
@JvmField
val BREEDING_EGG_HATCH = this.create("breeding.egg_hatch")
@JvmField
val ITEM_USE = this.create("item.use")
@JvmField
@@ -19,6 +19,7 @@ package com.cobblemon.mod.common.api
open class PrioritizedList<T> : Iterable<T> {
protected val priorityMap = mutableMapOf<Priority, MutableList<T>>()
// Please don't change arraylist, we need insertion order
// MutableList doesn't necessarily preserve insertion order apparently
protected val ordered = arrayListOf<T>()
val mapping: Map<Priority, List<T>>
@@ -26,8 +27,8 @@ open class PrioritizedList<T> : Iterable<T> {
private fun reorder() {
ordered.clear()
Priority.values().forEach {
priorityMap[it]?.let { ordered.addAll(it) }
Priority.entries.forEach {
priorityMap[it]?.let(ordered::addAll)
}
}
@@ -11,28 +11,51 @@ package com.cobblemon.mod.common.api.abilities
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.api.PrioritizedList
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addAbilityPoolFunctions
import com.cobblemon.mod.common.api.molang.ObjectValue
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.pokemon.Species
/**
* A pool of potential abilities, as a [PrioritizedList]. The added logic of this subclass
* is that it has selection logic. Given a species and a set of aspects, it will go through
* each priority group, and if it can then it will pick from that group and return it.
* each priority group, and if it can then it will pick from that group and return it. It also
* returns the index of that ability within the type band it is.
*
* @author Hiroku
* @since July 28th, 2022
*/
open class AbilityPool : PrioritizedList<PotentialAbility>() {
fun select(species: Species, aspects: Set<String>): Pair<Ability, Priority> {
val struct = ObjectValue(this)
.also { it.addAbilityPoolFunctions(this) }
fun getInheritedAbility(parent: Pokemon): Ability? {
if (parent.ability.forced) {
return null
}
val parentAbilityType = parent.form.abilities.find { it.template == parent.ability.template }?.type ?: return null // Should be impossible
val matchingTypes = ordered.filter { it.type == parentAbilityType }
val desiredIndex = parent.ability.index
val matchingPotentialAbility = matchingTypes.getOrNull(desiredIndex) ?: return null
return matchingPotentialAbility.template.create().also { it.index = desiredIndex }
}
fun select(species: Species, aspects: Set<String>): Ability {
val typeMap = ordered.groupBy { it.type }
for (priority in Priority.entries) {
val potentialAbilities = priorityMap[priority]?.filter { it.isSatisfiedBy(aspects) } ?: continue
if (potentialAbilities.isNotEmpty()) {
return potentialAbilities.random().template.create() to priority
val selected = potentialAbilities.random()
val ability = selected.template.create(priority = selected.priority)
ability.index = typeMap[selected.type]!!.indexOf(selected)
return ability
}
}
LOGGER.error("Unable to select an ability from the pool for $species and aspects: ${aspects.joinToString()}")
LOGGER.error("Please show this to the Cobblemon developers!")
Exception().printStackTrace()
return Abilities.first().create() to Priority.LOWEST
return Abilities.first().create()
}
}
@@ -12,13 +12,16 @@ import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.Sense
import com.cobblemon.mod.common.api.ai.config.BehaviourConfig
import com.cobblemon.mod.common.api.molang.ExpressionLike
import com.cobblemon.mod.common.api.molang.MoLangFunctions.addStandardFunctions
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.molang.ObjectValue
import com.cobblemon.mod.common.api.scripting.CobblemonScripts
import com.cobblemon.mod.common.entity.MoLangScriptingEntity
import com.cobblemon.mod.common.util.activityRegistry
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
@@ -46,8 +49,15 @@ class BehaviourConfigurationContext {
val memories = mutableSetOf<MemoryModuleType<*>>()
val sensors = mutableSetOf<SensorType<*>>()
val objectives = mutableMapOf<Int, MutableList<Objective>>()
val senses = mutableSetOf<Sense>()
val onAdd = mutableListOf<ExpressionLike>()
init {
memories.add(CobblemonMemories.NEST_DESPAWN_IMMUNE_UNTIL_TICK)
}
fun getOrCreateActivity(activity: Activity): ActivityConfigurationContext {
return activities.firstOrNull { it.activity == activity } ?: ActivityConfigurationContext(activity).also(activities::add)
}
@@ -68,6 +78,22 @@ class BehaviourConfigurationContext {
this.sensors.addAll(sensors)
}
fun addSenses(vararg senses: Sense) {
addSenses(senses.toList())
}
fun addSenses(senses: Collection<Sense>) {
outer@for (sense in senses) {
for (existingSense in this.senses) {
if (existingSense.merge(sense)) {
continue@outer
}
}
this.senses.add(sense)
this.addMemories(sense.memories)
}
}
fun addOnAddScript(script: ExpressionLike) {
onAdd.add(script)
}
@@ -88,8 +114,23 @@ class BehaviourConfigurationContext {
var brain = entity.brain
// Apply the brain config
if (entity is MoLangScriptingEntity) {
brain = entity.assignNewBrainWithMemoriesAndSensors(dynamic, memories, sensors)
val useBiggerBrain = objectives.isNotEmpty() || senses.isNotEmpty()
brain = entity.assignNewBrainWithMemoriesAndSensors(dynamic, memories, if (useBiggerBrain) emptySet() else sensors)
onAdd.forEach { runtime.resolve(it) }
if (useBiggerBrain) {
val wereDebugging = entity.biggerBrain.debuggingPlayers ?: emptySet()
val biggerBrain = BiggerBrain(entity)
entity.biggerBrain = biggerBrain
addSenses(biggerBrain.senses)
val orderedObjectives = objectives.entries.sortedBy { it.key }.flatMap { it.value }
orderedObjectives.forEach(biggerBrain::registerObjective)
biggerBrain.senses.addAll(senses)
biggerBrain.debuggingPlayers.addAll(wereDebugging)
return
} else {
val biggerBrain = BiggerBrain(entity)
entity.biggerBrain = biggerBrain
}
}
activities.forEach { it.apply(entity) }
brain.setCoreActivities(coreActivities)
@@ -136,4 +177,4 @@ class BehaviourConfigurationContext {
}
return struct
}
}
}
@@ -42,7 +42,8 @@ class CobblemonAttackTargetData(
/** An expression that returns false when the target is no longer worth attacking. */
var shouldContinue: Expression = "true".asExpression(),
var hitsUntilDisengage: Int = -1, // -1 means no limit
var disengageAction: (entity: Entity) -> Unit = {}
var disengageAction: (entity: Entity) -> Unit = {},
var hitsLanded : Int = 0
) {
val struct = ObjectValue<CobblemonAttackTargetData>(this).also {
it.addFunction("hits_until_disengage") { DoubleValue(hitsUntilDisengage.toDouble()) }
@@ -9,44 +9,40 @@
package com.cobblemon.mod.common.api.ai
import com.bedrockk.molang.runtime.struct.QueryStruct
import com.bedrockk.molang.runtime.value.DoubleValue
import com.cobblemon.mod.common.util.getBooleanOrNull
import com.cobblemon.mod.common.util.getDoubleOrNull
import kotlin.math.sqrt
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.PathfinderMob
/**
* Used to maintain some settings around how the entity should wander this tick. The idea is you
* reset this with some script task at priority 0 then some number of steps before it gets to the wander
* tasks you can have other conditional tasks jump in to configure parts of this.
* Used to maintain some settings around how the entity should wander this tick. Anything left null
* will fall back to defaults specified by the logic of the WanderAround objective.
*
* @author Hiroku
* @since July 18, 2025
*/
class CobblemonWanderControl(
var center: WanderCenter? = null,
var maxAttempts: Int = 4, // How many times to try to find a suitable point before giving up on that tick.
var allowLand: Boolean = true,
var allowWater: Boolean = false,
var allowAir: Boolean = false,
var pathCooldownTicks: Int = 20 * 5, // Used to mitigate the cost of pathfinding.
var wanderSpeed: Float = 0.35F,
var maxAttempts: Int? = null, // How many times to try to find a suitable point before giving up on that tick.
var allowLand: Boolean? = null,
var allowWater: Boolean? = null,
var allowAir: Boolean? = null,
var wanderSpeed: Float? = null,
var wanderChanceMultiplier: Float? = null
) {
class WanderCenter(val x: Number, val y: Number, val z: Number, val minRange: Float, val maxRange: Float)
@Transient
val struct: QueryStruct = QueryStruct(hashMapOf())
.addFunction("center_x") { center?.x ?: 0.0 }
.addFunction("center_y") { center?.y ?: 0.0 }
.addFunction("center_z") { center?.z ?: 0.0 }
.addFunction("max_attempts") { maxAttempts.toDouble() }
.addFunction("min_range") { center?.minRange ?: 0.0 }
.addFunction("max_range") { center?.maxRange ?: 0.0 }
.addFunction("allow_land") { if (allowLand) 1.0 else 0.0 }
.addFunction("allow_water") { if (allowWater) 1.0 else 0.0 }
.addFunction("allow_air") { if (allowAir) 1.0 else 0.0 }
.addFunction("path_cooldown_ticks") { pathCooldownTicks.toDouble() }
.addFunction("wander_speed") { wanderSpeed }
.addFunction("center_x") { DoubleValue(center?.x ?: 0.0) }
.addFunction("center_y") { DoubleValue(center?.y ?: 0.0) }
.addFunction("center_z") { DoubleValue(center?.z ?: 0.0) }
.addFunction("max_attempts") { DoubleValue(maxAttempts?.toDouble() ?: 0.0) }
.addFunction("min_range") { DoubleValue(center?.minRange ?: 0.0) }
.addFunction("max_range") { DoubleValue(center?.maxRange ?: 0.0) }
.addFunction("allow_land") { DoubleValue(if (allowLand == true) 1.0 else 0.0) }
.addFunction("allow_water") { DoubleValue(if (allowWater == true) 1.0 else 0.0) }
.addFunction("allow_air") { DoubleValue(if (allowAir == true) 1.0 else 0.0) }
.addFunction("wander_speed") { DoubleValue(wanderSpeed ?: 0.0) }
.addFunction("set_center") { params ->
if (params.params.size < 3) {
throw IllegalArgumentException("set_center requires at least 3 parameters: x, y, z")
@@ -68,26 +64,6 @@ class CobblemonWanderControl(
.addFunction("set_allow_land") { params -> allowLand = params.getBooleanOrNull(0) ?: true }
.addFunction("set_allow_water") { params -> allowWater = params.getBooleanOrNull(0) ?: false }
.addFunction("set_allow_air") { params -> allowAir = params.getBooleanOrNull(0) ?: false }
.addFunction("set_path_cooldown_ticks") { params -> pathCooldownTicks = params.getDoubleOrNull(0)?.toInt() ?: (20 * 5) }
.addFunction("set_wander_speed") { params -> wanderSpeed = params.getDoubleOrNull(0)?.toFloat() ?: 0.35F }
.addFunction("reset") { reset() }
fun isSuitable(position: BlockPos): Boolean {
val center = center ?: return true
val centerPos = BlockPos(center.x.toInt(), center.y.toInt(), center.z.toInt())
val distance = sqrt(centerPos.distSqr(position))
val suitable = distance >= center.minRange && distance <= center.maxRange
return suitable
}
fun reset() {
center = null
allowLand = false
allowWater = false
allowAir = false
pathCooldownTicks = 20 * 5
wanderSpeed = 0.35F
maxAttempts = 4
}
}
@@ -9,9 +9,23 @@
package com.cobblemon.mod.common.api.ai
import com.bedrockk.molang.Expression
import com.bedrockk.molang.ast.NumberExpression
import com.bedrockk.molang.ast.StringExpression
import com.bedrockk.molang.runtime.MoLangRuntime
import com.bedrockk.molang.runtime.value.DoubleValue
import com.bedrockk.molang.runtime.value.StringValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.MoLangScriptingEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveDouble
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.resolveString
import com.mojang.datafixers.util.Either
import kotlin.jvm.optionals.getOrNull
import net.minecraft.world.entity.LivingEntity
/**
* The issue in a lot of the behaviour datapacking is that there are times when a property should be exposed to
@@ -31,6 +45,50 @@ import kotlin.jvm.optionals.getOrNull
*/
typealias ExpressionOrEntityVariable = Either<Expression, MoLangConfigVariable>
fun ExpressionOrEntityVariable.asExpression() = map({ it }, { "q.entity.config.${it.variableName}".asExpression() })
fun ExpressionOrEntityVariable.resolveString(runtime: MoLangRuntime) = runtime.resolveString(asExpression())
fun ExpressionOrEntityVariable.resolveBoolean(runtime: MoLangRuntime) = runtime.resolveBoolean(asExpression())
fun ExpressionOrEntityVariable.resolveInt(runtime: MoLangRuntime) = runtime.resolveInt(asExpression())
fun ExpressionOrEntityVariable.resolveDouble(runtime: MoLangRuntime) = runtime.resolveDouble(asExpression())
fun ExpressionOrEntityVariable.resolveFloat(runtime: MoLangRuntime) = runtime.resolveFloat(asExpression())
private fun variable(category: String, name: String, type: MoLangConfigVariable.MoLangVariableType, default: String) = MoLangConfigVariable(
variableName = name,
category = lang("entity.variable.category.$category"),
displayName = lang("entity.variable.$name.name"),
description = lang("entity.variable.$name.desc"),
type = type,
defaultValue = default
)
fun stringVariable(category: String, name: String, default: String) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.TEXT, default = default)
fun numberVariable(category: String, name: String, default: Number) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.NUMBER, default = default.toString())
fun booleanVariable(category: String, name: String, default: Boolean) = variable(category = category, name = name, type = MoLangConfigVariable.MoLangVariableType.BOOLEAN, default = default.toString())
fun getVariableExpression(name: String) = "q.entity.config.$name".asExpression()
fun resolveBooleanVariable(name: String, runtime: MoLangRuntime) = runtime.resolveBoolean(getVariableExpression(name))
fun checkCondition(runtime: MoLangRuntime, expressionOrEntityVariable: ExpressionOrEntityVariable): Boolean {
return expressionOrEntityVariable.resolveBoolean(runtime)
}
fun ExpressionOrEntityVariable.asSimplifiedExpression(entity: LivingEntity): Expression {
return map(
{ it },
{
if (entity is MoLangScriptingEntity) {
val variable = entity.config.map[it.variableName]
if (variable is DoubleValue) {
return@map NumberExpression(variable.value)
} else if (variable is StringValue) {
return@map StringExpression(variable)
}
}
return@map "q.entity.config.${it.variableName}".asExpression()
}
)
}
/**
* In the case of [ExpressionOrEntityVariable] the right side is the only one that requires visibility for a user,
* this function is a shorthand for finding all of the values in the list that have something to show the user to
@@ -0,0 +1,194 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.bedrockk.molang.runtime.MoLangRuntime
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.PrioritizedList
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.ObjectiveStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.Sense
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.molang.MoLangFunctions.setup
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.net.messages.client.debug.UpdateTrackedBrainDataPacket
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.withQueryValue
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
import java.util.UUID
/**
* A better* version of Minecraft's [net.minecraft.world.entity.ai.Brain] system that makes development more
* straightforward and allows easier debugging.
*
* We could name this thing better.
*
* There are three main principles inside this system:
*
* 1: Senses
*
* Senses are simple ticking objects that are instantiated per entity and are expected to just update memories based
* on properties about the entity or its surroundings. This is an analogue of SensorType from Brains.
*
* 2: Objectives
*
* Objectives are also ticking objects that are instantiated per entity. They represent a goal for the entity and
* run in a fixed order.
*
* 3: Fixations
*
* Fixations are a task that can be set on the brain that represents a more total commitment to a certain task. Only
* a single fixation can be active at a time, and they can be 'distracted' by other objectives or potentially external
* factors.
*
* These can also be debugged using the /debugcobblemonai command while looking at a Pokémon or NPC entity.
*
* *that remains to be seen
*
* @author Hiroku
* @since December 29th, 2025
*/
class BiggerBrain(val entity: LivingEntity) {
val runtime = MoLangRuntime().setup().withQueryValue("entity", entity.asMostSpecificMoLangValue())
val senses = mutableListOf<Sense>()
val objectives = mutableListOf<Objective>()
val subscriptions = mutableMapOf<MemoryModuleType<*>, PrioritizedList<MemorySubscription<*>>>()
class MemorySubscription<U>(
val subscription: (U?, labels: MutableSet<String>) -> Boolean
) {
fun handle(value: Any?, labels: MutableSet<String>): Boolean {
val castValue = value as? U
return subscription(castValue, labels)
}
}
fun <U, M : MemoryModuleType<U>> subscribe(priority: Priority = Priority.NORMAL, memory: M, handler: (U?, labels: MutableSet<String>) -> Boolean) {
subscriptions
.getOrPut(memory, ::PrioritizedList)
.add(priority, MemorySubscription(handler))
}
var fixation: EntityFixation? = null
var debuggingPlayers = mutableSetOf<UUID>()
fun registerObjective(objective: Objective) {
objectives.add(objective)
objective.onRegister(entity, this)
}
fun isFixation(fixation: EntityFixation?): Boolean {
return fixation != null && this.fixation == fixation
}
fun sendDebugMessage(message: String) {
debuggingPlayers.forEach {
it.getPlayer()?.sendSystemMessage(message.text())
}
}
fun tick() {
senses.forEach {
it.ticksUntilNextExecution--
if (it.ticksUntilNextExecution <= 0) {
it.tick(entity, this)
}
}
val f = fixation
if (f?.tick(entity, this) == false && fixation === f) {
fixation = null
}
val objectiveStatuses = mutableMapOf<Objective, ObjectiveStatus>()
val activeObjectiveTags = mutableSetOf<String>()
for (objective in objectives) {
val status = objective.perform(entity, this, activeObjectiveTags)
objectiveStatuses[objective] = status
}
if (debuggingPlayers.isNotEmpty()) {
val state = BiggerBrainState(entity = entity, brain = this, objectiveStatuses = objectiveStatuses)
val packet = UpdateTrackedBrainDataPacket(entity.id, state)
debuggingPlayers.removeIf { uuid ->
val player = uuid.getPlayer()
if (player != null && Cobblemon.serverPlayerDebuggingPokemonBrainEntities[player.uuid] != entity.uuid) {
return@removeIf true
} else {
player?.sendPacket(packet)
}
return@removeIf player == null
}
}
}
fun fixate(fixation: EntityFixation): EntityFixation {
this.fixation = fixation
return fixation
}
fun distract(distraction: Distraction): Boolean {
if (fixation?.canDistract(distraction, entity) != false) {
fixation?.onDistract(distraction, entity)
this.fixation = null
return true
}
return false
}
fun canDistract(distraction: Distraction): Boolean {
return fixation?.canDistract(distraction, entity) != false
}
fun <T> setMemory(memory: MemoryModuleType<T>, value: T, expiry: Long? = null) {
if (expiry != null) {
entity.brain.setMemoryWithExpiry(memory, value, expiry)
} else {
entity.brain.setMemory(memory, value)
}
val labels = mutableSetOf<String>()
subscriptions[memory]?.forEach { it.handle(value = value, labels = labels) }
}
fun <T> setMemoryIfChanged(memory: MemoryModuleType<T>, value: T, expiry: Long? = null) {
if (entity.brain.getMemorySafely(memory).orElse(null) != value) {
setMemory(memory, value, expiry)
}
}
fun <T> eraseMemory(memory: MemoryModuleType<T>) {
entity.brain.eraseMemory(memory)
val labels = mutableSetOf<String>()
subscriptions[memory]?.forEach { it.handle(value = null, labels = labels) }
}
fun <T> eraseMemoryIfPresent(memory: MemoryModuleType<T>) {
if (entity.brain.hasMemoryValue(memory)) {
eraseMemory(memory)
}
}
fun hasMemoryValue(memory: MemoryModuleType<*>): Boolean {
return entity.brain.checkMemory(memory, MemoryStatus.VALUE_PRESENT)
}
fun <T> getMemory(memory: MemoryModuleType<T>): T? {
return entity.brain.getMemorySafely(memory).orElse(null)
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.Objective
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.ObjectiveStatus
import kotlin.reflect.jvm.jvmName
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.world.entity.LivingEntity
/**
* A DTO of sorts that is sent to debugging players to keep them informed about the state of an entity's Cobblemon AI.
*
* @author Hiroku
* @since December 29th, 2025
*/
class BiggerBrainState(
val senses: List<SenseState>,
val objectives: List<ObjectiveState>,
val fixation: String? = null
) {
class SenseState(val className: String, val ticksUntilNextExecution: Int) {
fun encode(buffer: FriendlyByteBuf) {
buffer.writeUtf(className)
buffer.writeInt(ticksUntilNextExecution)
}
companion object {
fun decode(buffer: FriendlyByteBuf): SenseState {
return SenseState(buffer.readUtf(), buffer.readInt())
}
}
}
class ObjectiveState(val description: String, val status: ObjectiveStatus) {
fun encode(buffer: FriendlyByteBuf) {
buffer.writeUtf(description)
buffer.writeEnum(status)
}
companion object {
fun decode(buffer: FriendlyByteBuf): ObjectiveState {
return ObjectiveState(buffer.readUtf(), buffer.readEnum(ObjectiveStatus::class.java))
}
}
}
constructor(entity: LivingEntity, brain: BiggerBrain, objectiveStatuses: Map<Objective, ObjectiveStatus>): this(
senses = brain.senses.map { SenseState(className = it::class.simpleName ?: it::class.jvmName, it.ticksUntilNextExecution) },
objectives = objectiveStatuses.entries.map { ObjectiveState(it.key.getDescription(entity), it.value) },
fixation = brain.fixation?.getDescription(entity)
)
fun encode(buffer: FriendlyByteBuf) {
buffer.writeCollection(senses) { _, sense -> sense.encode(buffer) }
buffer.writeCollection(objectives) { _, objective -> objective.encode(buffer) }
buffer.writeNullable(fixation) { _, fixation -> buffer.writeUtf(fixation) }
}
companion object {
fun decode(buffer: FriendlyByteBuf): BiggerBrainState {
val senses = buffer.readList { SenseState.decode(it) }
val objectives = buffer.readList { ObjectiveState.decode(it) }
val fixation = buffer.readNullable { buffer.readUtf() }
return BiggerBrainState(senses, objectives, fixation)
}
}
}
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BlockPosTracker
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.behavior.PositionTracker
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* A trivial wrapper around an entity and a position tracker to make the entity look at the position each tick.
*
* @author Hiroku
* @since December 29th, 2025
*/
class LookingTracker(val entity: PathfinderMob, val lookTarget: PositionTracker) {
companion object {
fun forTargetEntity(entity: PathfinderMob, target: LivingEntity, trackEyeHeight: Boolean = true): LookingTracker {
return LookingTracker(entity, EntityTracker(target, trackEyeHeight))
}
fun fromNavigationPathOrWalkTarget(entity: PathfinderMob, walkTarget: WalkTarget): LookingTracker {
val destinationPoint = entity.navigation.path?.endNode?.asVec3() ?: walkTarget.target.currentPosition()
return LookingTracker(entity, BlockPosTracker(destinationPoint.add(0.0, entity.eyeHeight.toDouble(), 0.0)))
}
}
fun tick() {
entity.lookControl.setLookAt(lookTarget.currentPosition())
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
/**
* A simple enum representing the status of a movement action.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class MovementStatus {
/** Represents when the entity is still en route to the destination. */
PENDING,
/** Represents when the entity has successfully reached the destination. */
COMPLETED,
/**
* Represents when the entity has failed to reach the destination. This can be due to
* a change in surroundings or taking too long or all sorts of things.
*/
FAILED
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* A wrapping around logic that maintains an entity's journey towards a specific destination. Mainly used by fixations
* to keep track of when pathing is done, and whether it failed or succeeded. Can also be told to stop to do any
* necessary clean up. Implemented only by [RegularMovementTracker] which has me questioning if it should be an interface
* or just a simple class like the [LookingTracker].
*
* @author Hiroku
* @since December 29th, 2025
*/
interface MovementTracker {
val walkTarget: WalkTarget
/** The last known status of this movement tracker. */
var lastStatus: MovementStatus
/** Performs a tick of movement tracking logic. Returns the current [MovementStatus]. */
fun tick(): MovementStatus
/** Stops the movement and does any necessary clean up. */
fun stop()
}
@@ -0,0 +1,240 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.entity.ai.OmniPathNavigation
import com.cobblemon.mod.common.pokemon.ai.OmniPathNodeMaker
import com.cobblemon.mod.common.util.deleteNode
import java.util.function.Predicate
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.ai.util.DefaultRandomPos
import net.minecraft.world.level.pathfinder.Path
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* The default movement tracker used for tracking movement towards a [WalkTarget]. This is pretty much entirely
* just the code for FollowWalkTargetTask from Minecraft brain stuff.
*
* @author Hiroku
* @since December 29th, 2025
*/
class RegularMovementTracker(
val entity: PathfinderMob,
override val walkTarget: WalkTarget,
/**
* The traversal rules for this movement. They stay attached to the path, including when it's recomputed or
* re-planned because the target moved. Null uses the legacy rules. Only honoured by [OmniPathNavigation].
*/
policy: TraversalPolicy? = null,
/** An already planned path to follow instead of planning one here. */
initialPath: Path? = null
) : MovementTracker {
companion object {
/**
* Attempts to create a tracker for the given entity and target. Returns null if the path
* couldn't be created.
*/
fun attempt(entity: PathfinderMob, walkTarget: WalkTarget, policy: TraversalPolicy? = null): RegularMovementTracker? {
return RegularMovementTracker(entity, walkTarget, policy).takeIf { it.isValid }
}
/** Creates a tracker that follows a path which was already planned, under the policy it was planned with. */
fun following(entity: PathfinderMob, walkTarget: WalkTarget, path: Path, policy: TraversalPolicy?): RegularMovementTracker? {
return RegularMovementTracker(entity, walkTarget, policy, path).takeIf { it.isValid }
}
}
/** The policy given explicitly, otherwise whatever the walk target asks for. */
val policy: TraversalPolicy? = policy ?: (walkTarget as? CobblemonWalkTarget)?.policy
var isValid = false
private set
var started = false
override var lastStatus: MovementStatus = MovementStatus.PENDING
private var path: Path? = null
private var lastKnownTargetPos: BlockPos? = null
init {
val hasReached = hasReached(entity, walkTarget)
if (!hasReached && initialPath != null) {
this.path = initialPath
this.lastKnownTargetPos = walkTarget.target.currentBlockPosition()
isValid = true
} else if (!hasReached && hasFinishedPath(entity, walkTarget)) {
this.lastKnownTargetPos = walkTarget.target.currentBlockPosition()
isValid = true
} else {
lastStatus = MovementStatus.FAILED
}
}
override fun tick(): MovementStatus {
val path = path
val status = if (path == null || isTargetSpectator(walkTarget)) {
stop(entity)
MovementStatus.FAILED
} else if (hasReached(entity, walkTarget)) {
stop(entity)
MovementStatus.COMPLETED
} else if (started && entity.navigation.isDone) {
stop(entity)
MovementStatus.FAILED
} else {
if (!started) {
startOnPath(entity)
started = true
}
tick(entity)
MovementStatus.PENDING
}
this.lastStatus = status
return status
}
fun startOnPath(entity: PathfinderMob) {
entity.brain.setMemory(MemoryModuleType.PATH, this.path)
entity.navigation.moveTo(this.path, walkTarget.speedModifier.toDouble())
}
override fun stop() {
stop(entity)
}
fun stop(entity: PathfinderMob) {
entity.navigation.stop()
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.brain.eraseMemory(MemoryModuleType.PATH)
}
private fun tick(entity: PathfinderMob) {
val path = entity.navigation.path
if (this.path !== path) {
this.path = path
this.startOnPath(entity)
}
if (path != null && lastKnownTargetPos != null) {
if (walkTarget.target.currentBlockPosition().distSqr(lastKnownTargetPos!!) > 4.0) {
// The target has moved away from where we are pathing, try pathing to its new location
if (hasFinishedPath(entity, walkTarget)) {
lastKnownTargetPos = walkTarget.target.currentBlockPosition()
startOnPath(entity)
} else {
// Uh oh, we can't get closer? Maybe next tick will be better?
}
}
}
}
private fun withNodeFilter(
entity: PathfinderMob,
nodeFilter: Predicate<PathType>,
block: () -> Unit) {
val nodeEvaluator = entity.navigation.nodeEvaluator
if (nodeEvaluator is OmniPathNodeMaker) {
nodeEvaluator.nodeFilter = nodeFilter
block()
nodeEvaluator.nodeFilter = Predicate { true }
} else {
block()
}
}
private fun hasFinishedPath(entity: PathfinderMob, walkTarget: WalkTarget): Boolean {
val blockPos = walkTarget.target.currentBlockPosition()
this.path = generatePath(entity, walkTarget, blockPos)
val hasReached = hasReached(entity, walkTarget)
if (!hasReached && path == null) {
// Desperate attempt to still path to the destination by going somewhere in the vicinity
val vec3d = DefaultRandomPos.getPosTowards(
entity,
10,
7,
Vec3.atBottomCenterOf(blockPos),
Math.PI / 2F
)
if (vec3d != null) {
this.path = generatePath(entity, walkTarget, BlockPos.containing(vec3d))
return this.path != null
}
} else if (!hasReached) {
return true
}
return false
}
private fun generatePath(
entity: PathfinderMob,
walkTarget: WalkTarget,
target: BlockPos
): Path? {
var path: Path? = null
val navigation = entity.navigation
if (policy != null && navigation is OmniPathNavigation) {
// The policy replaces node filtering; destination filtering still applies below.
var planned = navigation.planPath(target, 0, policy)
if (planned != null && walkTarget is CobblemonWalkTarget) {
while (planned.endNode?.type?.let { walkTarget.destinationNodeTypeFilter(it) } == false) {
planned.deleteNode(planned.nodeCount - 1)
}
if (planned.nodeCount == 0) {
planned = null
}
}
path = planned
} else if (walkTarget is CobblemonWalkTarget) {
withNodeFilter(
entity = entity,
nodeFilter = walkTarget.nodeTypeFilter,
) {
var resolvedPath = entity.navigation.createPath(target, 0)
if (resolvedPath != null) {
// A CobblemonWalkTarget may have a destinationNodeTypeFilter, which is used to filter the end node of the path.
// Mainly useful for when the thing setting the target did it a bit crudely or didn't know how far the navigator
// was going to get, and might land on something that is technically traversable by the entity but it doesn't
// fit the intention of the task. Example, a little bird wandering might end up finishing on a flight node,
// but it doesn't really want to fly in place so it'd prefer not ending there.
while (resolvedPath.endNode?.type?.let { walkTarget.destinationNodeTypeFilter(it) } == false) {
resolvedPath.deleteNode(resolvedPath.nodeCount - 1)
}
if (resolvedPath.nodeCount == 0) {
resolvedPath = null
}
}
path = resolvedPath
}
} else {
path = entity.navigation.createPath(target, 0)
}
return path
}
private fun hasReached(entity: PathfinderMob, walkTarget: WalkTarget): Boolean {
return walkTarget.target.currentBlockPosition().distManhattan(entity.blockPosition()) <= walkTarget.closeEnoughDist
}
fun isTargetSpectator(target: WalkTarget): Boolean {
val lookTarget = target.target
return if (lookTarget is EntityTracker) {
lookTarget.entity.isSpectator
} else {
false
}
}
}
@@ -0,0 +1,293 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain
import com.cobblemon.mod.common.api.ai.CobblemonWanderControl.WanderCenter
import com.cobblemon.mod.common.api.ai.config.task.WanderTaskConfig.Companion.MAX_LOOK_DOWN_DISTANCE
import com.cobblemon.mod.common.api.ai.movement.FluidKind
import com.cobblemon.mod.common.api.ai.movement.MovementCapabilities
import com.cobblemon.mod.common.api.ai.movement.MovementIntent
import com.cobblemon.mod.common.api.ai.movement.Occupancy
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.entity.OmniPathingEntity
import com.cobblemon.mod.common.entity.ai.CobblemonRandomSurfacePos
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import kotlin.math.ceil
import kotlin.math.sqrt
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BehaviorUtils
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.ai.util.HoverRandomPos
import net.minecraft.world.entity.ai.util.LandRandomPos
import net.minecraft.world.entity.ai.util.RandomPos
import net.minecraft.world.level.material.Fluids
import net.minecraft.world.level.pathfinder.PathType
/**
* A type of wandering behaviour for an entity. I'm not sure if we keep this.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class WanderType(
val isValid: (PathfinderMob) -> Boolean,
val choosePosition: (PathfinderMob, minimumHeight: Int, maximumHeight: Int, horizontalRange: Int, verticalRange: Int) -> BlockPos?,
val createWalkTarget: (PathfinderMob, position: BlockPos, avoidsTargetingAir: Boolean, speedMultiplier: Float) -> WalkTarget?,
) {
WATER(
isValid = { it.isInWater },
choosePosition = choosePosition@{ entity, _, _, horizontalRange, verticalRange ->
var pos = BehaviorUtils.getRandomSwimmablePos(entity, horizontalRange, verticalRange)?.let(BlockPos::containing)
?: return@choosePosition null
// Move target pos down so that we don't move out of water too much
val requiredDepth = ceil(0.5 + entity.eyeHeight)
// Get the current depth of the block
var depth = 1
var testPos = pos.above()
var blockState = entity.level().getBlockState(testPos)
while (blockState.fluidState.type == Fluids.WATER) {
depth++
testPos = testPos!!.above()
blockState = entity.level().getBlockState(testPos)
}
if (depth < requiredDepth) {
// Iterate down until we reach the desired min depth or we reach a non water block
pos = pos.below()
blockState = entity.level().getBlockState(pos)
while (blockState.fluidState.type == Fluids.WATER && depth < requiredDepth && pos.y > entity.level().minBuildHeight) {
depth++
pos = pos.below()
blockState = entity.level().getBlockState(pos)
}
}
return@choosePosition if (depth < requiredDepth) null else pos
},
createWalkTarget = { entity, pos, _, speedMultiplier ->
CobblemonWalkTarget(
pos = pos,
nodeTypeFilter = { it == PathType.WATER || it == PathType.WATER_BORDER },
speedModifier = speedMultiplier,
completionRange = 0,
// Stays swimming in water, wherever in the water it's comfortable or not.
policy = TraversalPolicy.forIntent(entity, MovementIntent.IDLE) { occupancy, fluid ->
fluid == FluidKind.WATER && (occupancy == Occupancy.SWIM || occupancy == Occupancy.SWIM_SUBMERGED)
}
)
}
),
LAND(
isValid = { entity -> !entity.isInWater && !entity.isInLava },
choosePosition = choosePosition@{ entity, minimumHeight, maximumHeight, horizontalRange, verticalRange ->
val targetVec = when {
maximumHeight != -1 -> {
HoverRandomPos.getPos(
entity,
horizontalRange,
verticalRange,
entity.random.nextFloat() - 0.5,
entity.random.nextFloat() - 0.5,
Math.PI.toFloat(),
maximumHeight,
minimumHeight
)
}
entity.isUnderWater && entity.canBreatheUnderwater() && !((entity as OmniPathingEntity).canSwimInWater()) -> {
BehaviorUtils.getRandomSwimmablePos(
entity,
horizontalRange,
verticalRange
)
}
entity is OmniPathingEntity && (entity.canWalkOnWater() || entity.canWalkOnLava()) -> {
CobblemonRandomSurfacePos.getPos(
entity,
horizontalRange,
verticalRange
)
}
else -> {
LandRandomPos.getPos(
entity,
horizontalRange,
verticalRange
)
}
}
val pos = targetVec?.let(BlockPos::containing) ?: return@choosePosition null
LAND.applyHeightConstraints(pos, minimumHeight, maximumHeight, entity.level() as ServerLevel)
},
createWalkTarget = { entity, pos, avoidsTargetingAir, speedMultiplier ->
CobblemonWalkTarget(
pos = pos,
speedModifier = speedMultiplier,
completionRange = 0,
nodeTypeFilter = { nodeType ->
entity.canBreatheUnderwater() || nodeType !in listOf(
PathType.WATER,
PathType.WATER_BORDER
)
},
destinationNodeTypeFilter = { nodeType ->
!avoidsTargetingAir || nodeType !in listOf(
PathType.OPEN
)
},
// Only goes through what it's comfortable with while idling, e.g. no swimming for non-breathers.
policy = TraversalPolicy.forIntent(entity, MovementIntent.IDLE)
)
}
),
/**
* Seafloor walkers in water: they can't swim, but can breathe, so they wander along the bottom (or wade, or step
* out onto land) instead. Neither [LAND] nor [WATER] applies to them while they're in water.
*/
SEABED(
isValid = { entity -> entity.isInWater && isSeafloorWalker(MovementCapabilities.of(entity)) },
choosePosition = { entity, _, _, horizontalRange, verticalRange ->
chooseBottomPosition(entity, horizontalRange, verticalRange)
},
createWalkTarget = { entity, pos, _, speedMultiplier ->
CobblemonWalkTarget(
pos = pos,
speedModifier = speedMultiplier,
completionRange = 0,
policy = TraversalPolicy.forIntent(entity, MovementIntent.IDLE)
)
}
)
;
fun generateWalkTarget(
entity: PathfinderMob,
maxAttempts: Int,
center: WanderCenter?,
minimumHeight: Int,
maximumHeight: Int,
horizontalRange: Int,
verticalRange: Int,
avoidTargetingAir: Boolean,
speedMultiplier: Float
): WalkTarget? {
var attempts = 0
var pos: BlockPos? = null
while (attempts++ < maxAttempts && pos == null) {
pos = choosePosition(entity, minimumHeight, maximumHeight, horizontalRange, verticalRange)
?: return null
if (!isSuitable(center, pos)) {
pos = null
}
}
if (pos == null) {
return null
}
return createWalkTarget(entity, pos, avoidTargetingAir, speedMultiplier)
}
private fun isSuitable(center: WanderCenter?, position: BlockPos): Boolean {
val center = center ?: return true
val centerPos = BlockPos(center.x.toInt(), center.y.toInt(), center.z.toInt())
val distance = sqrt(centerPos.distSqr(position))
val suitable = distance >= center.minRange && distance <= center.maxRange
return suitable
}
private fun applyHeightConstraints(
pos: BlockPos,
minimumHeight: Int,
maximumHeight: Int,
world: ServerLevel
): BlockPos {
if (minimumHeight <= 0 && maximumHeight == -1) {
return pos // It ain't a hoverer
}
val block = world.getBlockState(pos)
val altitude = if (!block.isAir) {
0
} else {
(1..MAX_LOOK_DOWN_DISTANCE).firstOrNull {
val newPos = pos.below(it)
if (!world.getBlockState(newPos).isAir) {
return@firstOrNull true
} else if (newPos.y <= world.minBuildHeight) {
// Don't adjust downward into the void (Mostly if we're in the end)
// This doesn't stop fliers from wandering off end islands,
// but it does stop them from diving directly into the void.
return pos
}
return@firstOrNull false
} ?: MAX_LOOK_DOWN_DISTANCE
}
if (altitude > maximumHeight && maximumHeight >= 0) {
val excess = altitude - maximumHeight
val excessFromMinimum = altitude - minimumHeight
val correction = world.random.nextIntBetweenInclusive(excess, excessFromMinimum)
return pos.atY(pos.y - correction)
} else if (altitude < minimumHeight && minimumHeight >= 0) {
val deficit = minimumHeight - altitude
val deficitFromMaximum = maximumHeight - altitude
val correction = world.random.nextIntBetweenInclusive(deficit, deficitFromMaximum)
return pos.atY(pos.y + correction)
} else {
return pos
}
}
}
/** Bodies that walk along the bottom of water rather than swimming in it, and can breathe down there. */
private fun isSeafloorWalker(caps: MovementCapabilities) = caps.canWalk && !caps.canSwimInWater && caps.canBreatheUnderwater
private const val BOTTOM_POSITION_SAMPLES = 10
private const val MAX_BOTTOM_DROP = 24
/**
* Picks a random position the entity could stand at, settling sampled points onto the bottom the way a non-swimmer
* would sink onto it. Only positions an idle policy allows are kept; reachability is the pathfinder's job.
*/
private fun chooseBottomPosition(entity: PathfinderMob, horizontalRange: Int, verticalRange: Int): BlockPos? {
val level = entity.level()
val policy = TraversalPolicy.forIntent(entity, MovementIntent.IDLE)
val origin = entity.blockPosition()
val tethering = (entity as? PokemonEntity)?.tethering
repeat(BOTTOM_POSITION_SAMPLES) {
var pos = origin.offset(RandomPos.generateRandomDirection(entity.random, horizontalRange, verticalRange))
var climbed = 0
while (level.getBlockState(pos).isSolid && climbed++ < verticalRange) {
pos = pos.above()
}
var occupancy = Occupancy.at(policy.capabilities, entity.eyeHeight, pos, level::getBlockState)
var dropped = 0
while (occupancy?.isStandable == false && dropped++ < MAX_BOTTOM_DROP && pos.y > level.minBuildHeight) {
pos = pos.below()
occupancy = Occupancy.at(policy.capabilities, entity.eyeHeight, pos, level::getBlockState)
}
if (occupancy == null || pos == origin) {
return@repeat
} else if (policy.cost(occupancy, FluidKind.of(level.getFluidState(pos))) == null) {
return@repeat
} else if (tethering?.canRoamTo(pos) == false) {
return@repeat
}
return pos
}
return null
}
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.distraction
import net.minecraft.world.damagesource.DamageSource
/**
* Something that may distract an entity from its current fixation. The majority of fixations
* will rely on the types of distraction to determine if they should be distracted.
*
* @author Hiroku
* @since December 29th, 2025
*/
open class Distraction(val types: Set<DistractionType>) {
constructor(vararg types: DistractionType) : this(types.toSet())
val isIdleBoredom = DistractionType.IDLE_BOREDOM in types
val isForce = DistractionType.FORCE in types
val isComfort = DistractionType.COMFORT in types
val isDamage = DistractionType.DAMAGE in types
fun hasAnyOf(vararg distractionTypes: DistractionType): Boolean {
return distractionTypes.any { it in types }
}
companion object {
val FORCE = Distraction(DistractionType.FORCE)
}
}
/** Reusable basic distraction for a COMFORT type of distraction. */
val comfortDistraction = Distraction(DistractionType.COMFORT)
/** Reusable basic distraction for an IDLE_BOREDOM type of distraction. */
val idleBoredomDistraction = Distraction(DistractionType.IDLE_BOREDOM)
open class HurtDistraction(val damageSource: DamageSource) : Distraction(DistractionType.DAMAGE)
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
/**
* A categorisation of distractions that can be attempted on an [EntityFixation].
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class DistractionType {
/** Represents a distraction that the entity is not particularly motivated by but would consider doing out of boredom. */
IDLE_BOREDOM,
/** Represents a distraction that is for the sake of the entity's comfort because it isn't comfortable where it is. */
COMFORT,
/** Represents a distraction motivated by being hurt. */
DAMAGE,
/** A forceful distraction. Just about everything should respect this but it's conceivable that something not. */
FORCE,
}
@@ -0,0 +1,178 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.movement.MovementIntent
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.moves.RealTimeMove
import com.cobblemon.mod.common.pokemon.ai.moves.RealTimeMoveInstance
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.player.Player
import kotlin.collections.set
class AttackFixation(
val targetEntity: LivingEntity,
/** Distraction types that will be respected. */
private val speedMultiplier: Expression = "1.0".asExpression(),
private val availableMoves: List<RealTimeMove> = emptyList(),
val distractionTypes: Set<DistractionType>,
) : EntityFixation {
private val globalAttackCooldownTicks: Int = 20 // TODO: pull from pokemon stats
var movementTracker: MovementTracker? = null
var lookingTracker: LookingTracker? = null
var activeMoveInstance: RealTimeMoveInstance? = null
/** Ticks until it may plan again after a failed or impossible path, so it holds instead of re-pathing every tick. */
var remainingRepathTicks = 0
override fun getDescription(entity: LivingEntity): String {
return "Attacking Target"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.types.any(distractionTypes::contains)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity || !entity.isAlive) return false
entity as PokemonEntity // Intellij and my brain says this is redundant but I'm not getting smart casting later on sooo
val targetedEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
?: return false
if (targetedEntity.isRemoved || targetedEntity.isDeadOrDying || brain.getMemory(MemoryModuleType.AVOID_TARGET) != null) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
return false
}
if (targetedEntity is Player && (targetedEntity.isCreative || targetedEntity.isSpectator)) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
return false
}
// If we have a current target, check if it's still valid and within roam range (if tethered)
if (targetedEntity.isAlive) {
val tethering = (entity).tethering
if (tethering != null && !tethering.canRoamTo(targetedEntity.blockPosition())) {
// Target moved out of range let's kill the memory >:)
brain.distract(Distraction.FORCE)
entity.brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
return false
}
}
if (activeMoveInstance != null && activeMoveInstance!!.completed) {
activeMoveInstance = null
}
var runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
runtime = runtime.withQueryValue("target", targetedEntity.asMostSpecificMoLangValue())
val speed = runtime.resolveFloat(speedMultiplier)
var selectedMoveIndex = -1
var distanceToTarget = -1.0f
if (!(entity.biggerBrain.getMemory(MemoryModuleType.ATTACK_COOLING_DOWN) ?: false)) {
// Not blocked by global cooldown, check if any available moves can be performed
var highestPriority = Int.MAX_VALUE
distanceToTarget = entity.distanceTo(targetedEntity)
availableMoves.forEachIndexed { index, move ->
// check for cooldown ticks, priority, and range
// TODO: Account for hitbox sizes when doing range checks
if (move.id !in entity.pokemon.realTimeMoveCooldowns && move.priority < highestPriority
&& (distanceToTarget <= move.maxRange || entity.isWithinMeleeAttackRange(targetedEntity))
&& (distanceToTarget >= move.minRange)
) {
selectedMoveIndex = index
highestPriority = move.priority
}
}
if (selectedMoveIndex != -1) {
val selectedMove = availableMoves[selectedMoveIndex]
activeMoveInstance = selectedMove.createInstance(entity, targetedEntity)
activeMoveInstance?.start()
// Reset cooldowns
entity.pokemon.realTimeMoveCooldowns[selectedMove.id] = selectedMove.cooldownTicks
brain.setMemory(MemoryModuleType.ATTACK_COOLING_DOWN, true, globalAttackCooldownTicks.toLong())
}
}
if (lookingTracker != null) {
lookingTracker!!.tick()
}
if (movementTracker != null) {
val movementStatus = movementTracker!!.tick()
if (movementStatus != MovementStatus.PENDING) {
movementTracker!!.stop()
movementTracker = null
if (movementStatus == MovementStatus.FAILED) {
remainingRepathTicks = REPATH_COOLDOWN_TICKS
}
}
} else if (remainingRepathTicks > 0) {
remainingRepathTicks--
if (lookingTracker == null) {
lookingTracker = LookingTracker.forTargetEntity(entity, targetedEntity, trackEyeHeight = true)
}
} else {
// Not moving right now and we need to figure out to what distance to the enemy we want to move to
var idealDistanceToTarget = Float.MAX_VALUE
var highestPriority = Int.MAX_VALUE
availableMoves.forEachIndexed { index, move ->
// We want the highest priority move that's not on cooldown
if (move.id !in entity.pokemon.realTimeMoveCooldowns && move.priority < highestPriority) {
highestPriority = move.priority
idealDistanceToTarget = move.maxRange
}
}
// Get distance to target if we didn't initialize it in the earlier block
if (distanceToTarget < 0) {
distanceToTarget = entity.distanceTo(targetedEntity)
}
if (idealDistanceToTarget < distanceToTarget) {
val walkTarget = WalkTarget(EntityTracker(targetedEntity, true), speed, idealDistanceToTarget.toInt())
val policy = TraversalPolicy.forIntent(entity, MovementIntent.URGENT)
movementTracker = RegularMovementTracker.attempt(entity, walkTarget, policy)
if (movementTracker == null) {
remainingRepathTicks = REPATH_COOLDOWN_TICKS
}
lookingTracker = LookingTracker.forTargetEntity(entity, targetedEntity, trackEyeHeight = true)
} else if (lookingTracker == null) {
// Fixate at looking at the target so we don't wander off
lookingTracker = LookingTracker.forTargetEntity(entity, targetedEntity, trackEyeHeight = true)
}
}
return true
}
companion object {
const val REPATH_COOLDOWN_TICKS = 20
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* A fixation that rejects all non-force distractions and does nothing, lasting until
* the provided [condition] is no longer true.
*
* @author Hiroku
* @since January 16th, 2026
*/
open class ConditionalLockFixation(
val description: String,
val condition: () -> Boolean
): EntityFixation, LockFixation {
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun getDescription(entity: LivingEntity) = description
override fun tick(entity: LivingEntity, brain: BiggerBrain) = condition()
}
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* A fixation that rejects all non-force distractions and does nothing for some
* number of ticks.
*
* @author Hiroku
* @since January 16th, 2026
*/
open class DurationLockFixation(
val description: String,
var durationTicks: Int
) : EntityFixation, LockFixation {
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun getDescription(entity: LivingEntity) = description.replace("{ticks}", durationTicks.toString())
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
return --durationTicks > 0
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import net.minecraft.world.entity.LivingEntity
/**
* An entity's fixation, representing a task that takes a central role in the entity's behaviour
* and excludes all other possible fixations.
*
* The role of the fixation is to do an action which is the primary focus of the entity at that time,
* and which may be distracted from under some circumstances. An entity may be fixated on moving from
* A to B, and then be distracted upon being hurt. Or maybe it's an attack fixation, in which case
* damage doesn't distract it at all.
*
* The difference between a fixation and an objective is that objectives are capable of running in parallel,
* and a fixation may even be in the pursuit of an objective, but the fixation is central.
*
* @author Hiroku
* @since December 28th, 2025
*/
interface EntityFixation {
/** Returns true if the given distraction can stop this fixation. */
fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean
/** Notifies the fixation that it has been distracted by the given distraction so it can do clean up. */
fun onDistract(distraction: Distraction, entity: LivingEntity) {}
/** Continues doing whatever the fixation does. Returns true if the fixation should continue. */
fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean
/** Gets a current description of the fixation for the debug screen. */
fun getDescription(entity: LivingEntity): String
}
@@ -0,0 +1,18 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
/**
* Represents a fixation that blocks battling, capture, etc. for Pokémon. This is
* used to control the isBusy property on Pokémon.
*
* @author Hiroku
* @since January 16th, 2026
*/
interface LockFixation
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
class LookAndLockFixation(
override val lookingTracker: LookingTracker?,
/** Distraction types that will be respected. */
val distractionTypes: Set<DistractionType>,
val condition: () -> Boolean
) : EntityFixation, LookingTrackerFixation {
override fun getDescription(entity: LivingEntity): String {
return "Looking at a nearby entity (Locked)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.types.any(distractionTypes::contains)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val targetEntity = lookingTracker?.entity ?: return false
if ((targetEntity.isRemoved) || entity !is PathfinderMob) {
return false
}
val lookingTracker = lookingTracker
lookingTracker.tick()
return condition()
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import net.minecraft.world.entity.LivingEntity
/**
* A simple fixation that uses both a looking tracker and a movement tracker.
*
* @author Hiroku
* @since December 29th, 2025
*/
open class LookAndMoveFixation(
/** Distraction types that will be respected. */
val distractionTypes: Set<DistractionType>,
/** How to describe the fixation in the debug overlay. */
val description: String,
override val lookingTracker: LookingTracker,
override val movementTracker: MovementTracker,
val onMovementComplete: ((entity: LivingEntity, brain: BiggerBrain) -> Unit)? = null
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = description
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.types.any(distractionTypes::contains)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
val continueFixation = tickMovementFixation() == MovementStatus.PENDING
if (!continueFixation && onMovementComplete != null) {
onMovementComplete.invoke(entity, brain)
}
return continueFixation
}
}
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
/**
* Applied to fixations which may have looking associated with them. This is useful
* in the case that an objective needs to know if the current fixation intends on (or is)
* controlling their looking direction.
*
* Example: An objective that makes Pokémon bob their heads up and down while music is playing.
* Said objective would not warrant a full fixation, but would still like to ensure that the
* current fixation does not intend on using a looking tracker.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface LookingTrackerFixation {
val lookingTracker: LookingTracker?
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.fixation
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
/**
* Applied to fixations which may have movement associated with them. This is useful
* in the case that an objective needs to know if the current fixation intends on (or is)
* controlling their movement.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface MovementTrackerFixation {
/** The movement tracker at the moment. */
val movementTracker: MovementTracker?
/** Ticks the movement tracker in a way that skips finalized movement trackers. */
fun tickMovementFixation(): MovementStatus? {
val movementTracker = this.movementTracker ?: return null
return if (movementTracker.lastStatus != MovementStatus.PENDING) {
movementTracker.lastStatus
} else {
movementTracker.tick()
}
}
}
@@ -0,0 +1,167 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.AttackFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.resolveString
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class AggressiveBehaviour(
speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
engageRange: Expression = "15.0".asExpression(),
disengageRange: Expression = "20.0".asExpression(),
condition: Expression = "true".asExpression(), // Self/environment condition check
targetCondition: Expression = "true".asExpression(), // target condition (will be checked on entity interaction)
description: Expression = "'Aggressive Behaviour'".asExpression(),
val maxAttackDuration: Expression = "300".asExpression(),
) : EntityResponseObjective(
speedMultiplier = speedMultiplier, // How do we transfer speed to the attack behaviour? Do we want to?
engageRange = engageRange,
disengageRange = disengageRange,
condition = condition, // Self/environment condition check
targetCondition = targetCondition, // target condition (will be checked on entity interaction)
description = description,
) {
private var remainingCooldownTicks = 0
private var attackFixation : EntityFixation? = null
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
if (brain.getMemory(MemoryModuleType.AVOID_TARGET) != null) {
return ObjectiveStatus.BLOCKED
}
val attackTarget = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
if (trackedEntity != null) {
// has active target
if (attackTarget != null && trackedEntity?.uuid == attackTarget.uuid) {
// Check if we continue
if (shouldContinue(entity, brain)) {
return ObjectiveStatus.ACTIVE
} else {
brain.distract(Distraction.FORCE)
attackFixation = null
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(CobblemonMemories.ATTACK_TARGET_DATA)
return ObjectiveStatus.INACTIVE
}
} else {
// Something has overridden us and independently set the attack target
trackedEntity = null
attackFixation = null
return ObjectiveStatus.BLOCKED
}
} else {
// No active target
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = 20
}
val targetEntity = scanForValidTargets(entity, brain)
if (targetEntity != null && brain.distract(Distraction.FORCE)) {
val runtime = mainThreadRuntime
val attackDuration = runtime.resolveInt(maxAttackDuration)
trackedEntity = targetEntity
brain.setMemory(MemoryModuleType.ATTACK_TARGET, targetEntity, attackDuration.toLong())
attackFixation = brain.fixate(
AttackFixation(
targetEntity = trackedEntity!!,
speedMultiplier = speedMultiplier,
distractionTypes = setOf(DistractionType.FORCE),
availableMoves = getRealTimeMoves(entity)
)
)
}
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = CobblemonMemories.ATTACK_TARGET_DATA
) { attackData, labels ->
val targetEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET) ?: return@subscribe true
if (trackedEntity?.uuid == targetEntity.uuid) {
// We smacked them, refresh our attack timer
val runtime = mainThreadRuntime.withQueryValue("entity", (targetEntity).asMostSpecificMoLangValue())
val attackDuration = runtime.resolveInt(maxAttackDuration)
brain.setMemory(MemoryModuleType.ATTACK_TARGET, targetEntity, attackDuration.toLong())
}
return@subscribe true
}
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val engageRange: ExpressionOrEntityVariable = Either.left("15.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("20.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("false".asExpression())
val maxAttackDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val description: ExpressionOrEntityVariable = Either.left("'Aggressive Behaviour'".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
targetCondition,
speedMultiplier,
engageRange,
disengageRange,
maxAttackDuration,
description
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return AggressiveBehaviour(
condition = condition.asSimplifiedExpression(entity),
targetCondition = targetCondition.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
maxAttackDuration = maxAttackDuration.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,196 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.CobblemonAttackTargetData
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.movement.MovementIntent
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.InteractionHand
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.player.Player
class AttackTargetMelee(
private val speedMultiplier: Expression = "1.0".asExpression(),
private val attackRange: Expression = "2.0".asExpression(),
private val attackCooldownTicks: Int = 20
) : Objective {
private var movementTask: EntityFixation? = null
private var movementTracker: MovementTracker? = null
private var remainingCooldownTicks = 0
/** Ticks until the chase may plan again after failing, so an unreachable target doesn't get re-pathed every tick. */
private var remainingRepathTicks = 0
override fun getDescription(entity: LivingEntity) = "Attack target melee"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
val target = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
?: return ObjectiveStatus.INACTIVE
if (target.isRemoved || target.isDeadOrDying) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
return ObjectiveStatus.INACTIVE
}
if (target is Player && (target.isCreative || target.isSpectator)) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
return ObjectiveStatus.INACTIVE
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val range = runtime.resolveFloat(attackRange)
val speed = runtime.resolveFloat(speedMultiplier)
// This is melee thing, but not everything will do melee in the future
if (entity.distanceToSqr(target) <= range * range && entity.hasLineOfSight(target)) {
if (remainingCooldownTicks <= 0) {
if (entity.doHurtTarget(target)) {
entity.swing(InteractionHand.MAIN_HAND)
var attackTargetData = brain.getMemory(CobblemonMemories.ATTACK_TARGET_DATA)
if (attackTargetData != null) {
attackTargetData.hitsLanded += 1
} else {
attackTargetData = CobblemonAttackTargetData()
attackTargetData.hitsLanded = 1
}
brain.setMemory(CobblemonMemories.ATTACK_TARGET_DATA, attackTargetData)
}
remainingCooldownTicks = attackCooldownTicks
}
return ObjectiveStatus.ACTIVE
}
// If we have a current target, check if it's still valid and within roam range (if tethered)
if (target.isAlive) {
val tethering = (entity).tethering
if (tethering != null && !tethering.canRoamTo(target.blockPosition())) {
// Target moved out of range let's kill the memory >:)
brain.distract(Distraction.FORCE)
entity.brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
}
}
if (brain.isFixation(movementTask)) {
return ObjectiveStatus.FIXATED
}
if (movementTracker?.lastStatus == MovementStatus.FAILED) {
// Got as close as it's willing to (e.g. the bank of a lake it won't enter). Hold there for a bit.
movementTracker = null
remainingRepathTicks = REPATH_COOLDOWN_TICKS
}
if (remainingRepathTicks > 0) {
remainingRepathTicks--
entity.lookControl.setLookAt(target)
return ObjectiveStatus.ACTIVE
}
if (!brain.distract(Distraction.FORCE)) return ObjectiveStatus.BLOCKED
val walkTarget = WalkTarget(EntityTracker(target, true), speed, 1)
val policy = TraversalPolicy.forIntent(entity, MovementIntent.URGENT)
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget, policy)
this.movementTracker = movementTracker
if (movementTracker == null) {
remainingRepathTicks = REPATH_COOLDOWN_TICKS
return ObjectiveStatus.ACTIVE
}
movementTask = brain.fixate(LookAndMoveFixation(
distractionTypes = setOf(DistractionType.FORCE),
lookingTracker = LookingTracker.forTargetEntity(entity, target, trackEyeHeight = true),
movementTracker = movementTracker,
description = "Moving to attack target"))
return ObjectiveStatus.FIXATED
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.ATTACK_TARGET
) { value, labels ->
if (value == null) {
if (brain.isFixation(movementTask)) {
brain.distract(Distraction.FORCE)
movementTask = null
}
}
return@subscribe true
}
}
companion object {
const val REPATH_COOLDOWN_TICKS = 20
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("1.0".asExpression())
val attackRange: ExpressionOrEntityVariable = Either.left("2.0".asExpression())
val attackCooldownTicks: ExpressionOrEntityVariable = Either.left("20".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(speedMultiplier, attackRange, attackCooldownTicks).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return AttackTargetMelee(
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
attackRange = attackRange.asSimplifiedExpression(entity),
attackCooldownTicks = behaviourConfigurationContext.runtime.resolveInt(
attackCooldownTicks.asSimplifiedExpression(entity)
)
)
}
}
}
@@ -0,0 +1,173 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.ai.util.LandRandomPos
import net.minecraft.world.entity.player.Player
class AvoidTarget(
private val speedMultiplier: Expression = "0.5".asExpression(),
) : Objective {
private var movementTask: EntityFixation? = null
private var remainingCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Avoiding target"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
val target = brain.getMemory(MemoryModuleType.AVOID_TARGET)
?: return ObjectiveStatus.INACTIVE
if (target.isRemoved || target.isDeadOrDying) {
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
return ObjectiveStatus.INACTIVE
}
if (target is Player && (target.isCreative || target.isSpectator)) {
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
return ObjectiveStatus.INACTIVE
}
if (brain.isFixation(movementTask)) {
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val speed = runtime.resolveFloat(speedMultiplier)
// If we have a current target, check if it's still valid and within roam range (if tethered)
if (target.isAlive) {
val tethering = (entity).tethering
if (tethering != null && !tethering.canRoamTo(target.blockPosition())) {
// Target moved out of range let's kill the memory >:)
brain.distract(Distraction.FORCE)
entity.brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
}
}
if (brain.isFixation(movementTask)) {
return ObjectiveStatus.FIXATED
}
if (!brain.distract(Distraction.FORCE)) return ObjectiveStatus.BLOCKED
var targetPos : BlockPos? = null
// TODO: utilize wander target rules to find a valid target position
val direction = entity.position().subtract(target.position())
for (j in 0..9) {
val targetVec3 = LandRandomPos.getPosAway(entity, 16, 7, direction)
if (targetVec3 != null) {
targetPos = BlockPos.containing(targetVec3)
break
}
}
// val walkTarget = WanderAround.generateWalkTarget(entity)
if (targetPos != null) {
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
targetPos,
speed,
0
)
)
if (movementTracker != null) {
movementTask = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(
DistractionType.FORCE
),
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(
entity,
movementTracker.walkTarget
),
movementTracker = movementTracker,
description = "Moving away from target entity",
)
)
return ObjectiveStatus.FIXATED
}
}
return ObjectiveStatus.ACTIVE
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.AVOID_TARGET
) { value, labels ->
if (value == null) {
if (brain.isFixation(movementTask)) {
brain.distract(Distraction.FORCE)
movementTask = null
}
}
return@subscribe true
}
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(speedMultiplier).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return AvoidTarget(
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
)
}
}
}
@@ -0,0 +1,306 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.DurationLockFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt as resolveVariableInt
import com.cobblemon.mod.common.api.breeding.CobblemonBreeding
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.nest.WildNestType
import com.cobblemon.mod.common.api.nest.WildNestTypes
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.block.WildNestBlock
import com.cobblemon.mod.common.block.entity.NestBlockEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.particles.ParticleTypes
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.phys.Vec3
class Breed(
private val speedMultiplier: Expression = "0.4".asExpression(),
private val condition: Expression = "true".asExpression(),
private val layDurationTicks: Int = 40
) : Objective {
private var fixation: EntityFixation? = null
private var mateFixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Breed"
override fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive)
return ObjectiveStatus.INVALID
val world = entity.level() as? ServerLevel ?: return ObjectiveStatus.INVALID
val mate = brain.getMemory(CobblemonMemories.POTENTIAL_MATE) as? PokemonEntity ?: return ObjectiveStatus.INACTIVE
if (!mate.isAlive || mate.level() != world)
return ObjectiveStatus.INACTIVE
// ignore wild pokemon who are already parents of a nest
if (entity.pokemon.isWild() && brain.hasMemoryValue(CobblemonMemories.PATERNAL_NEST_LOCATION))
return ObjectiveStatus.INACTIVE
// make sure either parent doesn't have an active breeding cooldown (do we want to only do this for the females?)
if (entity.pokemon.breedingCooldown != 0 || mate.pokemon.breedingCooldown != 0)
return ObjectiveStatus.INACTIVE
// is breeding disabled from any preset conditions
if (!mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveBoolean(condition))
return ObjectiveStatus.INACTIVE
// try to get one parent to lead the other one and have the other one not do this stuff
if (entity.uuid > mate.uuid)
return ObjectiveStatus.INACTIVE
val nestPos = brain.getMemory(CobblemonMemories.NEST_LOCATION)
if (nestPos != null)
return breedAtNest(entity, brain, mate, world, nestPos)
val idealNestPos = brain.getMemory(CobblemonMemories.IDEAL_NEST_LOCATION) ?: return ObjectiveStatus.INACTIVE
return buildNest(entity, brain, mate, world, idealNestPos)
}
// get both parents to go to the nest and breed once within range
private fun breedAtNest(entity: PokemonEntity, brain: BiggerBrain, mate: PokemonEntity, world: ServerLevel, nestPos: BlockPos): ObjectiveStatus {
val nest = world.getBlockEntity(nestPos) as? NestBlockEntity ?: return ObjectiveStatus.INACTIVE
if (!canUseNest(entity, mate, world, nest))
return ObjectiveStatus.INACTIVE
if (!nest.getItem().isEmpty)
return ObjectiveStatus.INACTIVE
// make sure these lovers claim the nest because others may try to at the same time
nest.nestClaimedBy = Pair(entity.uuid, mate.uuid)
val nestCenter = Vec3.atCenterOf(nestPos)
val speed = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier)
// path to the nest site with mate until close enough (big bois had issues so we are also going to try to make it easier for them)
if (entity.position().distanceTo(nestCenter) > closeEnough(entity) || mate.position().distanceTo(nestCenter) > closeEnough(mate)) {
bringMate(mate, nestCenter, speed)
return walkToNest(entity, brain, nestCenter, speed, "in Breed fixation: going to nest")
}
return layEgg(entity, brain, mate, world, nest, nestPos)
}
// have both mates go to a ideal spot to make a nest
private fun buildNest(entity: PokemonEntity, brain: BiggerBrain, mate: PokemonEntity, world: ServerLevel, nestPos: BlockPos): ObjectiveStatus {
// probably should stop trying to build nest if there is an attack target
if (brain.hasMemoryValue(MemoryModuleType.ATTACK_TARGET))
return ObjectiveStatus.INACTIVE
// find out what kinds of nests this couple can make togethr
val types = WildNestTypes.combinedTypes(entity, mate)
if (types.isEmpty())
return ObjectiveStatus.INACTIVE
val nestCenter = Vec3.atCenterOf(nestPos)
val speed = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier)
// keep going until both mates are not too far from the nest
if (entity.position().distanceTo(nestCenter) > closeEnough(entity) || mate.position().distanceTo(nestCenter) > closeEnough(mate)) {
bringMate(mate, nestCenter, speed)
return walkToNest(entity, brain, nestCenter, speed, "in Breed fixation: going to nest")
}
// get our nest they are about to build and place it
val nestToBuild = WildNestTypes.resolvePlacement(types, world.getBlockState(nestPos.below()), world.getFluidState(nestPos)) ?: return ObjectiveStatus.INACTIVE
val nestBlock = WildNestTypes.blockFor(nestToBuild.type) as? WildNestBlock ?: return ObjectiveStatus.INACTIVE
var nestState = nestBlock.defaultBlockState().setValue(BlockStateProperties.WATERLOGGED, nestToBuild.waterlogged)
nestBlock.variantProperty?.let { nestState = nestState.setValue(it, nestToBuild.variant) }
world.setBlock(nestPos, nestState, 3)
// set the parents of the nest (hope this isn't too early to do this, might need to be after egg laying instead..)
(world.getBlockEntity(nestPos) as? NestBlockEntity)?.nestClaimedBy = Pair(entity.uuid, mate.uuid)
for (parentBrain in listOf(brain, mate.biggerBrain)) {
parentBrain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
// give our newly made nest to the parents now taht it exists
parentBrain.setMemory(CobblemonMemories.NEST_LOCATION, nestPos)
}
return ObjectiveStatus.ACTIVE
}
// make da baby and tell the parents about their new responsibility in life
private fun layEgg(entity: PokemonEntity, brain: BiggerBrain, mate: PokemonEntity, world: ServerLevel, nest: NestBlockEntity, nestPos: BlockPos): ObjectiveStatus {
if (!brain.distract(Distraction.FORCE))
return ObjectiveStatus.BLOCKED
val egg = CobblemonBreeding.createEgg(entity.pokemon, mate.pokemon) ?: return ObjectiveStatus.INACTIVE
nest.setItem(egg)
// wild nests are probably the only ones where we need to record the parents onto the nest
if (nest.ownerUUID == null) {
nest.parents = Pair(entity.uuid, mate.uuid)
nest.nestClaimedBy = Pair(entity.uuid, mate.uuid)
}
for (parent in listOf(entity, mate)) {
// might want to do the destiny knot damaging here for each parent that has one
if (Cobblemon.config.canDestinyKnotBreak)
if (parent.pokemon.heldItem.item == CobblemonItems.DESTINY_KNOT.asItem()) {
parent.pokemon.heldItemNoCopy().damageValue += 1
}
parent.pokemon.breedingCooldown = CobblemonBreeding.resetBreedingCooldown(parent.pokemon)
parent.biggerBrain.setMemory(CobblemonMemories.PATERNAL_NEST_LOCATION, nestPos)
parent.biggerBrain.setMemory(CobblemonMemories.EGG_IN_NEST, true)
parent.biggerBrain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
// todo do we want to use our own particles? look at this later
world.sendParticles(
ParticleTypes.HEART,
parent.getRandomX(1.0),
parent.getRandomY() + 0.5,
parent.getRandomZ(1.0),
4 + parent.random.nextInt(2),
0.2 * parent.random.nextGaussian(),
0.1 * parent.random.nextGaussian(),
0.2 * parent.random.nextGaussian(),
0.02
)
}
// try to keep them in one spot for a bit to give time for the magic to happen
fixation = brain.fixate(DurationLockFixation("Breed: laying egg", layDurationTicks))
if (mate.biggerBrain.distract(Distraction.FORCE)) {
mateFixation = mate.biggerBrain.fixate(DurationLockFixation("Breed: laying egg as the mate", layDurationTicks))
}
return ObjectiveStatus.FIXATED
}
// path to the nest location
private fun walkToNest(entity: PokemonEntity, brain: BiggerBrain, target: Vec3, speed: Float, description: String): ObjectiveStatus {
if (brain.isFixation(fixation))
return ObjectiveStatus.FIXATED
// wait for mate to get here
if (entity.position().distanceTo(target) <= closeEnough(entity))
return ObjectiveStatus.ACTIVE
if (!brain.distract(comfortDistraction))
return ObjectiveStatus.BLOCKED
val tracker = RegularMovementTracker.attempt(entity, WalkTarget(target, speed, closeEnough(entity).toInt())) ?: return ObjectiveStatus.ACTIVE
fixation = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE),
description = description,
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(entity, tracker.walkTarget),
movementTracker = tracker
)
)
return ObjectiveStatus.FIXATED
}
// have the other mates be told where to go
private fun bringMate(mate: PokemonEntity, target: Vec3, speed: Float) {
val mateBrain = mate.biggerBrain
if (mate.position().distanceTo(target) <= closeEnough(mate) || mateBrain.isFixation(mateFixation))
return
if (!mateBrain.distract(comfortDistraction))
return
val tracker = RegularMovementTracker.attempt(mate, WalkTarget(target, speed, closeEnough(mate).toInt())) ?: return
mateFixation = mateBrain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE),
description = "Breed: folow mate",
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(mate, tracker.walkTarget),
movementTracker = tracker
)
)
}
// checks for what nests are valid for the mates
private fun canUseNest(entity: PokemonEntity, mate: PokemonEntity, world: ServerLevel, nest: NestBlockEntity): Boolean {
val nestType = (nest.blockState.block as? WildNestBlock)?.type ?: return false
if (!isNestTypeAllowed(nestType, entity, mate))
return false
val waterlogged = nest.blockState.getOptionalValue(BlockStateProperties.WATERLOGGED).orElse(false)
if (!isWaterGroupCompatible(entity, mate, waterlogged))
return false
// check if the nest is claimed by other pokemon that exist and maybe on their way to it (CRAB NOTE: This helps prevent swarms of mons going to the same nest which looked weird)
val (existingParent1, existingParent2) = nest.nestClaimedBy
val claimedByMate1 = existingParent1 != null && existingParent1 != entity.uuid && world.getEntity(existingParent1) != null
val claimedByMate2 = existingParent2 != null && existingParent2 != entity.uuid && world.getEntity(existingParent2) != null
if (claimedByMate1 && claimedByMate2)
return false
return true
}
// make sure the nest type works for the mates and that wild use wild nests and owned pokemon use player placed nests
private fun isNestTypeAllowed(nestType: WildNestType, entity: PokemonEntity, mate: PokemonEntity): Boolean {
val allowed = WildNestTypes.combinedTypes(entity, mate).toMutableSet()
if (!entity.pokemon.isWild() && !mate.pokemon.isWild()) {
allowed.add(WildNestType.PLAYER)
allowed.add(WildNestType.KELP)
}
if (nestType == WildNestType.PLAYER || nestType == WildNestType.KELP)
return !entity.pokemon.isWild() && nestType in allowed
return nestType in allowed
}
// waterlogged nests only allow parents that both have a water egg group and land nests dont work for mates that only have water egg groups
private fun isWaterGroupCompatible(entity: PokemonEntity, mate: PokemonEntity, nestWaterlogged: Boolean): Boolean {
val mate1Groups = entity.pokemon.species.eggGroups.map { it.name.lowercase() }
val mate2Groups = mate.pokemon.species.eggGroups.map { it.name.lowercase() }
val mate1HasWaterGroup = mate1Groups.any { it in WATER_EGG_GROUPS || it == "ditto" }
val mate2HasWaterGroup = mate2Groups.any { it in WATER_EGG_GROUPS || it == "ditto" }
val mate1OnlyWaterGroup = mate1Groups.all { it in WATER_EGG_GROUPS }
val mate2OnlyWaterGroup = mate2Groups.all { it in WATER_EGG_GROUPS }
return if (nestWaterlogged) mate1HasWaterGroup && mate2HasWaterGroup else !(mate1OnlyWaterGroup || mate2OnlyWaterGroup)
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val layDurationTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): List<MoLangConfigVariable> {
return listOf(speedMultiplier, condition, layDurationTicks).asVariables()
}
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
behaviourConfigurationContext.addMemories(
CobblemonMemories.POTENTIAL_MATE,
CobblemonMemories.NEST_LOCATION,
CobblemonMemories.PATERNAL_NEST_LOCATION,
CobblemonMemories.IDEAL_NEST_LOCATION,
CobblemonMemories.EGG_IN_NEST,
MemoryModuleType.ATTACK_TARGET
)
return Breed(
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
condition = condition.asSimplifiedExpression(entity),
layDurationTicks = layDurationTicks.resolveVariableInt(behaviourConfigurationContext.runtime)
)
}
}
// lets help those with more cushion for the pushing reach those nests to breed
private fun closeEnough(entity: PokemonEntity) = CLOSE_ENOUGH_DISTANCE + entity.bbWidth / 2
companion object {
private const val CLOSE_ENOUGH_DISTANCE = 1.5 // we will have this be our baseline and then scale based on hitbox (like above) for the bigger mons
private val WATER_EGG_GROUPS = setOf("water_1", "water_2", "water_3")
}
}
@@ -0,0 +1,167 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Swim or fly in a circle objective
*/
class CircleAround(
val poseTypes: Set<PoseType>,
val minTurnAngleDegrees: Float,
val maxTurnAngleDegrees: Float,
val verticalSpeed: Float,
val speed: Float,
val minDurationTicks: Int = 60,
val maxDurationTicks: Int = 180
) : Objective {
var chosenTurnAngle = 0F
var chosenDuration = 0
var fixation: EntityFixation? = null
var moveControl: PokemonMoveControl? = null
override fun getDescription(entity: LivingEntity) = "Circling"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity.getCurrentPoseType() !in poseTypes) {
return ObjectiveStatus.BLOCKED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED // Since this doesn't distract anything then if the brain is fixated at all we are blocked
}
// TODO: should this not be able to distract anything? relates to the above fixation comment
// if (!brain.distract(idleBoredomDistraction)) {
// return ObjectiveStatus.BLOCKED
// }
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
// Gather a random turn angle and random duration
this.chosenTurnAngle = entity.random.nextFloat() * (maxTurnAngleDegrees - minTurnAngleDegrees) + minTurnAngleDegrees
if (entity.random.nextBoolean()) {
chosenTurnAngle = -chosenTurnAngle
}
chosenDuration = entity.random.nextIntBetweenInclusive(minDurationTicks, maxDurationTicks)
// Grab moveControl off the entity to use during fixation
this.moveControl = entity.moveControl as PokemonMoveControl?
// Become fixated
fixation = brain.fixate(
CircleAroundFixation(
this,
null,
chosenDuration
)
)
return ObjectiveStatus.ACTIVE //TODO: should this have a cooldown? Currently just having it as the pure fallback and able to be distracted by anything. I guess fishes should always swim... probably not but I'll sort that later
}
class CircleAroundFixation(
val objective: CircleAround,
override val movementTracker: MovementTracker?,
var timer: Int
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Circling around at ${this.objective.chosenTurnAngle} degrees for ${this.timer} more ticks"
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
super.onDistract(distraction, entity)
objective.moveControl?.stopBanking()
}
// can be distracted by anything
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
objective.moveControl?.startBanking(
forwardBlocksPerTick = objective.speed,
upwardsBlocksPerTick = objective.verticalSpeed,
rightDegreesPerTick = objective.chosenTurnAngle,
durationTicks = 2 //TODO: is it odd we have the check in multiple spots?
)
this.timer--
if (this.timer < 0 || (entity as PokemonEntity).getCurrentPoseType() !in objective.poseTypes) {
objective.moveControl?.stopBanking()
return false
}
return true
}
}
class Config : ObjectiveConfig {
val poseTypes: Set<PoseType> = setOf(PoseType.FLY, PoseType.HOVER)
val minAngularVelocityDegrees: ExpressionOrEntityVariable = Either.left("0.0".asExpression())
val maxAngularVelocityDegrees: ExpressionOrEntityVariable = Either.left("1.0".asExpression())
val speed: ExpressionOrEntityVariable = Either.left("0.6".asExpression())
val verticalSpeed: ExpressionOrEntityVariable = Either.left("0.0".asExpression())
val minDurationTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDurationTicks: ExpressionOrEntityVariable = Either.left("180".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minAngularVelocityDegrees,
maxAngularVelocityDegrees,
speed,
verticalSpeed,
minDurationTicks,
maxDurationTicks
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
if (entity !is PokemonEntity) return null
return CircleAround(
poseTypes = poseTypes,
minTurnAngleDegrees = minAngularVelocityDegrees.resolveFloat(behaviourConfigurationContext.runtime),
maxTurnAngleDegrees = maxAngularVelocityDegrees.resolveFloat(behaviourConfigurationContext.runtime),
speed = speed.resolveFloat(behaviourConfigurationContext.runtime),
verticalSpeed = verticalSpeed.resolveFloat(behaviourConfigurationContext.runtime),
minDurationTicks = minDurationTicks.resolveInt(behaviourConfigurationContext.runtime),
maxDurationTicks = maxDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,158 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.effect.RunPosableMoLangPacket
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Stops movement and plays a Pokemon's dance animation, if available.
*
*/
class Dance(
val minDuration: Int,
val danceChance: Float
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Dancing"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
// Only dance if we feel like it
val danceMemory = brain.getMemory(MemoryModuleType.DANCING) ?: false
if (!danceMemory || entity.random.nextFloat() > danceChance || entity.ticksLived < 4 * 20) {
return ObjectiveStatus.INACTIVE
}
if (!brain.distract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
// Become fixated
fixation = brain.fixate(
DanceFixation(
this,
null,
minDuration
)
)
return ObjectiveStatus.ACTIVE
}
class DanceFixation(
val objective: Dance,
override val movementTracker: MovementTracker?,
val minDuration: Int
) : EntityFixation, MovementTrackerFixation {
var ticksSinceStarted = 0
override fun getDescription(entity: LivingEntity) = "Dancing"
override fun tickMovementFixation() = MovementStatus.PENDING
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
super.onDistract(distraction, entity)
stopDancing(entity)
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
if (distraction.isIdleBoredom) {
return false
}
return true
}
fun stopDancing(entity: LivingEntity) {
val pokemon = entity as? PokemonEntity ?: return
pokemon.setBehaviourFlag(PokemonBehaviourFlag.DANCING, false)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (ticksSinceStarted == 0) { // Makes make me want a Start() for fixations
val pokemon = entity as? PokemonEntity ?: return false
RunPosableMoLangPacket(entity.id, setOf("v.bpm = 100;")).sendToPlayersAround(entity, 64.0)
pokemon.setBehaviourFlag(PokemonBehaviourFlag.DANCING, true)
}
ticksSinceStarted++
if (ticksSinceStarted > minDuration && !entity.brain.getMemorySafely(MemoryModuleType.DANCING).orElse(false)) {
stopDancing(entity)
return false
}
return true
}
}
class Config : ObjectiveConfig {
var danceChance: ExpressionOrEntityVariable = Either.left("1/2".asExpression())
var minDuration: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minDuration,
danceChance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val danceChance = danceChance.resolveFloat(behaviourConfigurationContext.runtime)
return Dance(
minDuration,
danceChance)
}
}
companion object {
private const val ticksBetweenAttempts = 20
}
}
@@ -0,0 +1,384 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.AttackFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndLockFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt as resolveVariableInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.isInBattle
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.particles.ParticleTypes
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.player.Player
import net.minecraft.world.phys.Vec3
class DefendNest(
speedMultiplier: Expression = "0.5".asExpression(),
warnRange: Expression = "15.0".asExpression(),
private val attackRange: Expression = "8.0".asExpression(),
disengageRange: Expression = "20.0".asExpression(),
condition: Expression = "true".asExpression(),
targetCondition: Expression = "true".asExpression(),
description: Expression = "'Defend Nest'".asExpression(),
private val maxAttackDuration: Expression = "300".asExpression(),
private val patrolMinRadius: Int = 4,
private val patrolMaxRadius: Int = 8
) : EntityResponseObjective(
speedMultiplier = speedMultiplier,
engageRange = warnRange,
disengageRange = disengageRange,
condition = condition,
targetCondition = targetCondition,
description = description
) {
private var fixation: EntityFixation? = null
private var scanCooldownTicks = 0
private var cryCooldownTicks = 0
private var patrolCooldownTicks = 0
override fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive)
return ObjectiveStatus.INVALID
// so only wild mons will guard the nest (unless we want them to later on..)
if (!entity.pokemon.isWild())
return ObjectiveStatus.INACTIVE
// if the mon is battling then don't worry about defending (this was causing crying and particle spam lol)
if (entity.isBattling)
return ObjectiveStatus.INACTIVE
val nestPos = brain.getMemory(CobblemonMemories.PATERNAL_NEST_LOCATION)
if (nestPos == null) {
// mates used to give up attacking players if the egg and nest was gone but we should have them chase them to the ends of the earth for their crimes
val thief = brain.getMemory(CobblemonMemories.EGG_THIEF)
if (thief != null && thief.isAlive && entity.hasLineOfSight(thief))
return attack(entity, brain, thief)
return stopDefending(brain)
}
val eggInNest = brain.getMemory(CobblemonMemories.EGG_IN_NEST) == true
val thief = brain.getMemory(CobblemonMemories.EGG_THIEF)
// if we have no egg to watch over and no thief then we should not defend the nest anymore and need to switch to a different task
if (!eggInNest && thief == null)
return stopDefending(brain)
if (scanCooldownTicks > 0)
scanCooldownTicks--
if (cryCooldownTicks > 0)
cryCooldownTicks--
val nestCenter = Vec3.atCenterOf(nestPos)
val attackTarget = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
if (attackTarget != null && attackTarget.uuid != trackedEntity?.uuid) {
trackedEntity = null
return ObjectiveStatus.BLOCKED
}
val tracked = trackedEntity
if (tracked != null) {
if (!keepTrackingPlayer(entity, brain, tracked, nestCenter)) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
trackedEntity = null
fixation = null
return ObjectiveStatus.ACTIVE
}
return respondToIntruder(entity, brain, tracked, nestCenter)
}
if (scanCooldownTicks <= 0) {
scanCooldownTicks = SCAN_INTERVAL_TICKS
trackedEntity = findIntruder(entity, brain, nestCenter)
if (trackedEntity != null) {
cryCooldownTicks = 0
return ObjectiveStatus.ACTIVE
}
}
return patrol(entity, brain, nestCenter, activeObjectiveTags)
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
// Go after any known egg thieves
brain.subscribe(Priority.HIGH, CobblemonMemories.EGG_THIEF) { thief, _ ->
if (entity is PokemonEntity && thief != null) {
if (brain.fixation !is AttackFixation) {
trackedEntity = thief
attack(entity, brain, thief)
}
} else if (thief == null && fixation is AttackFixation && brain.isFixation(fixation)) {
brain.distract(Distraction.FORCE)
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
trackedEntity = null
fixation = null
}
true
}
}
// stop defending the nest and remove the fixation
private fun stopDefending(brain: BiggerBrain): ObjectiveStatus {
if (trackedEntity != null) {
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
trackedEntity = null
fixation = null
}
if (fixation is LookAndLockFixation && brain.isFixation(fixation))
brain.distract(Distraction.FORCE)
return ObjectiveStatus.INACTIVE
}
// various checks on if a player should be tracked still
private fun keepTrackingPlayer(entity: PokemonEntity, brain: BiggerBrain, tracked: LivingEntity, nestCenter: Vec3): Boolean {
if (tracked.isRemoved || !tracked.isAlive)
return false
if (tracked is Player && (tracked.isCreative || tracked.isSpectator))
return false
if (tracked is ServerPlayer && tracked.isInBattle())
return false
if (brain.getMemory(CobblemonMemories.EGG_THIEF)?.uuid == tracked.uuid)
return true
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
return tracked.position().distanceTo(nestCenter) <= runtime.resolveFloat(disengageRange)
}
// warn players that get too close or that steal an egg
private fun respondToIntruder(entity: PokemonEntity, brain: BiggerBrain, tracked: LivingEntity, nestCenter: Vec3): ObjectiveStatus {
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val distanceToNest = tracked.position().distanceTo(nestCenter)
val isThief = brain.getMemory(CobblemonMemories.EGG_THIEF)?.uuid == tracked.uuid
return when {
isThief || distanceToNest <= runtime.resolveFloat(attackRange) -> attack(entity, brain, tracked) // stop you have violated the law!
distanceToNest <= runtime.resolveFloat(engageRange) -> warn(entity, brain, tracked, nestCenter) // almost too close!
else -> ObjectiveStatus.ACTIVE
}
}
// force an attack fixation
private fun attack(entity: PokemonEntity, brain: BiggerBrain, target: LivingEntity): ObjectiveStatus {
if (fixation is AttackFixation && brain.isFixation(fixation))
return ObjectiveStatus.FIXATED
if (!brain.distract(Distraction.FORCE))
return ObjectiveStatus.BLOCKED
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
entity.cry()
// todo we can use our own particles later
(entity.level() as? ServerLevel)?.sendParticles(
ParticleTypes.ANGRY_VILLAGER,
entity.getRandomX(1.0),
entity.getRandomY() + 0.5,
entity.getRandomZ(1.0),
4 + entity.random.nextInt(2),
0.2 * entity.random.nextGaussian(),
0.1 * entity.random.nextGaussian(),
0.2 * entity.random.nextGaussian(),
0.02
)
brain.setMemory(MemoryModuleType.ATTACK_TARGET, target, runtime.resolveInt(maxAttackDuration).toLong())
brain.setMemory(MemoryModuleType.ANGRY_AT, target.uuid)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
fixation = brain.fixate(
AttackFixation(
targetEntity = target,
speedMultiplier = speedMultiplier,
availableMoves = getRealTimeMoves(entity), // idk how this works but looks like Jazz lets us do this now
distractionTypes = setOf(DistractionType.FORCE)
)
)
return ObjectiveStatus.FIXATED
}
// cry at players that get too close to the nest
private fun warn(entity: PokemonEntity, brain: BiggerBrain, target: LivingEntity, nestCenter: Vec3): ObjectiveStatus {
if (cryCooldownTicks <= 0) {
entity.cry()
// todo replace these particles later here too
(entity.level() as? ServerLevel)?.sendParticles(
ParticleTypes.ANGRY_VILLAGER,
entity.getRandomX(1.0),
entity.getRandomY() + 0.5,
entity.getRandomZ(1.0),
4 + entity.random.nextInt(2),
0.2 * entity.random.nextGaussian(),
0.1 * entity.random.nextGaussian(),
0.2 * entity.random.nextGaussian(),
0.02
)
cryCooldownTicks = CRY_COOLDOWN_TICKS + entity.random.nextInt(CRY_COOLDOWN_RANDOM_TICKS)
}
if (fixation is LookAndLockFixation && brain.isFixation(fixation))
return ObjectiveStatus.FIXATED
if (!brain.distract(Distraction.FORCE))
return ObjectiveStatus.BLOCKED
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val warnRange = runtime.resolveFloat(engageRange)
val attackRange = runtime.resolveFloat(attackRange)
fixation = brain.fixate(
LookAndLockFixation(
lookingTracker = LookingTracker.forTargetEntity(entity, target),
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE),
condition = {
val distance = target.position().distanceTo(nestCenter)
trackedEntity?.uuid == target.uuid && distance <= warnRange && distance > attackRange
}
)
)
return ObjectiveStatus.FIXATED
}
// looks for player within the warn range and too close to the nest
private fun findIntruder(entity: PokemonEntity, brain: BiggerBrain, nestCenter: Vec3): LivingEntity? {
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
if (!runtime.resolveBoolean(condition))
return null
val warnRange = runtime.resolveFloat(engageRange)
val visible = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return null
// todo how should we handle creative players?
return visible.findAll { candidate ->
candidate is Player &&
!(candidate is ServerPlayer && candidate.isInBattle()) &&
candidate.position().distanceTo(nestCenter) <= warnRange &&
runtime.withQueryValue("target", candidate.asMostSpecificMoLangValue()).resolveBoolean(targetCondition)
}.minByOrNull { it.position().distanceToSqr(nestCenter) }
}
// pathfind around various spots around the nest
private fun patrol(entity: PokemonEntity, brain: BiggerBrain, nestCenter: Vec3, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING)
if (fixation is LookAndMoveFixation && brain.isFixation(fixation))
return ObjectiveStatus.FIXATED
if (patrolCooldownTicks > 0) {
patrolCooldownTicks--
return ObjectiveStatus.ACTIVE
}
val world = entity.level() as? ServerLevel ?: return ObjectiveStatus.INVALID
val target = findPatrolPosition(world, nestCenter, entity) ?: return ObjectiveStatus.ACTIVE
if (!brain.distract(comfortDistraction))
return ObjectiveStatus.BLOCKED
val speed = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier)
val tracker = RegularMovementTracker.attempt(entity, WalkTarget(target, speed, 1)) ?: return ObjectiveStatus.ACTIVE
fixation = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE, DistractionType.COMFORT),
description = "patrol method in DefendNest objective",
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(entity, tracker.walkTarget),
movementTracker = tracker,
onMovementComplete = { _, _ -> patrolCooldownTicks = PATROL_PAUSE_TICKS + entity.random.nextInt(PATROL_PAUSE_RANDOM_TICKS) }
)
)
return ObjectiveStatus.FIXATED
}
// find pathfindable spot to patrol to
private fun findPatrolPosition(world: ServerLevel, center: Vec3, entity: PokemonEntity): Vec3? {
repeat(PATROL_ATTEMPTS) {
val angle = world.random.nextDouble() * Math.PI * 2
val radius = patrolMinRadius + world.random.nextInt(patrolMaxRadius - patrolMinRadius + 1)
val candidate = center.add(Math.cos(angle) * radius, world.random.nextDouble() * 2 - 1, Math.sin(angle) * radius)
val blockPos = BlockPos.containing(candidate)
if (!world.getBlockState(blockPos).isSolidRender(world, blockPos) && entity.navigation.isStableDestination(blockPos)) {
return Vec3.atCenterOf(blockPos)
}
}
return null
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val warnRange: ExpressionOrEntityVariable = Either.left("15.0".asExpression())
val attackRange: ExpressionOrEntityVariable = Either.left("8.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("20.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val maxAttackDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val description: ExpressionOrEntityVariable = Either.left("'Defend Nest'".asExpression())
val patrolMinRadius: ExpressionOrEntityVariable = Either.left("4".asExpression())
val patrolMaxRadius: ExpressionOrEntityVariable = Either.left("8".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): List<MoLangConfigVariable> {
return listOf(
speedMultiplier,
warnRange,
attackRange,
disengageRange,
condition,
targetCondition,
maxAttackDuration,
description,
patrolMinRadius,
patrolMaxRadius
).asVariables()
}
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
// I don't think we need any other memory than these
behaviourConfigurationContext.addMemories(
CobblemonMemories.PATERNAL_NEST_LOCATION,
CobblemonMemories.EGG_IN_NEST,
CobblemonMemories.EGG_THIEF,
CobblemonMemories.EGG_SEARCH_COUNTDOWN,
MemoryModuleType.ANGRY_AT,
MemoryModuleType.ATTACK_TARGET,
MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES
)
return DefendNest(
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
warnRange = warnRange.asSimplifiedExpression(entity),
attackRange = attackRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
condition = condition.asSimplifiedExpression(entity),
targetCondition = targetCondition.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity),
maxAttackDuration = maxAttackDuration.asSimplifiedExpression(entity),
patrolMinRadius = patrolMinRadius.resolveVariableInt(behaviourConfigurationContext.runtime),
patrolMaxRadius = patrolMaxRadius.resolveVariableInt(behaviourConfigurationContext.runtime)
)
}
}
companion object {
private const val SCAN_INTERVAL_TICKS = 20
private const val CRY_COOLDOWN_TICKS = 75
private const val CRY_COOLDOWN_RANDOM_TICKS = 50
private const val PATROL_PAUSE_TICKS = 40
private const val PATROL_PAUSE_RANDOM_TICKS = 40
private const val PATROL_ATTEMPTS = 20
}
}
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* Defend owner objective
* Handles transition of nearest visible attacker to a valid attack target when wanting to defend owner.
* Could possibly be more configurable in the future
*/
class DefendOwner : Objective {
var cooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Following parent species"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) return ObjectiveStatus.INVALID
if (brain.hasMemoryValue(MemoryModuleType.ATTACK_TARGET)) return ObjectiveStatus.INACTIVE
val attacker = brain.getMemory(CobblemonMemories.NEAREST_VISIBLE_ATTACKER)
?: return ObjectiveStatus.INACTIVE
brain.setMemory(MemoryModuleType.ATTACK_TARGET, attacker)
return ObjectiveStatus.ACTIVE
}
class Config : ObjectiveConfig {
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
emptyList<MoLangConfigVariable>()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective? {
if (entity !is PokemonEntity) return null
return DefendOwner()
}
}
}
@@ -0,0 +1,170 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.CobblemonAttackTargetData
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
class Defensive(
private val speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
private val engageRange: Expression = "5.0".asExpression(),
private val disengageRange: Expression = "20.0".asExpression(),
private val condition: Expression = "true".asExpression(),
private val maxAttackDuration: Expression = "300".asExpression(),
private val retaliationHitCount: Expression = "1".asExpression()
) : Objective {
private var remainingCooldownTicks = 0
private var trackedEntity: LivingEntity? = null
override fun getDescription(entity: LivingEntity) = "Defensive Behavior"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
val attackTarget = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
val avoidTarget = brain.getMemory(MemoryModuleType.AVOID_TARGET)
if (trackedEntity != null) {
if (attackTarget != null && trackedEntity?.uuid == attackTarget.uuid) {
// Check if we continue
return ObjectiveStatus.ACTIVE
} else if (avoidTarget != null && trackedEntity?.uuid === avoidTarget.uuid) {
// Check if we continue
val runtime = mainThreadRuntime.withQueryValue("entity", (trackedEntity!!).asMostSpecificMoLangValue())
val disengageDistance = runtime.resolveFloat(disengageRange)
if (disengageDistance < entity.distanceTo(trackedEntity!!)) {
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
trackedEntity = null
}
} else {
// Something has overrided us
trackedEntity = null
}
} else {
// Scan visible livingEntities
val entities: NearestVisibleLivingEntities =
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return ObjectiveStatus.INACTIVE
val entity = entities.findClosest { it ->
val runtime = mainThreadRuntime.withQueryValue("entity", (it).asMostSpecificMoLangValue())
runtime.resolveBoolean(condition) && runtime.resolveFloat(engageRange) > entity.distanceTo(it)
}.orElse(null)
if (entity != null) {
trackedEntity = entity
brain.setMemory(MemoryModuleType.AVOID_TARGET, entity)
}
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.HURT_BY_ENTITY
) { value, labels -> onHurtByEntityChanged(brain, value, labels) }
brain.subscribe(
priority = Priority.LOW,
memory = CobblemonMemories.ATTACK_TARGET_DATA
) { value, labels -> onAttackTargetDataChanged(brain, value, labels) }
}
fun onHurtByEntityChanged(brain: BiggerBrain, livingEntity: LivingEntity?, labels: MutableSet<String>): Boolean {
if (livingEntity != null) {
// Something just smacked us, see if we should get mad about it.
val livingEntity = livingEntity as LivingEntity
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
val shouldTarget = runtime.resolveBoolean(condition)
if (shouldTarget) {
brain.setMemory(MemoryModuleType.ATTACK_TARGET, livingEntity,
runtime.resolveInt(maxAttackDuration).toLong()
)
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
trackedEntity = livingEntity
}
}
return true
}
fun onAttackTargetDataChanged(brain: BiggerBrain, attackData: CobblemonAttackTargetData?, labels: MutableSet<String>): Boolean {
if (attackData != null) {
// We smacked them, check if it's time for tactical retreat
val livingEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET) ?: return true
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
if (attackData.hitsLanded >= runtime.resolveInt(retaliationHitCount)) {
// Justice served, carry on
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(CobblemonMemories.ATTACK_TARGET_DATA)
brain.setMemory(MemoryModuleType.AVOID_TARGET, trackedEntity)
}
}
return true // Other listeners can handle it that's fine
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val engageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val maxAttackDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val retaliationHitCount: ExpressionOrEntityVariable = Either.left("1".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(condition, speedMultiplier, engageRange, disengageRange, maxAttackDuration, retaliationHitCount).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return Defensive(
condition = condition.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
maxAttackDuration = maxAttackDuration.asSimplifiedExpression(entity),
retaliationHitCount = retaliationHitCount.asSimplifiedExpression(entity),
)
}
}
}
@@ -0,0 +1,147 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.feature.FlagSpeciesFeature
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.level.GameRules
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.predicate.BlockStatePredicate
/**
* The baa's eat the graa's
*
* @author Hiroku
* @since January 9th, 2025
*/
class EatGrass(
val cooldownTicks: Int,
val eatGrassChance: Float
) : Objective {
var fixation: EntityFixation? = null
val grassPredicate = BlockStatePredicate.forBlock(Blocks.GRASS_BLOCK)
var remainingCooldownTicks = cooldownTicks
override fun getDescription(entity: LivingEntity) = "Eat grass"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (!brain.canDistract(comfortDistraction)) {
return ObjectiveStatus.BLOCKED
} else if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
val world = entity.level() as ServerLevel
entity.pokemon.getFeature<FlagSpeciesFeature>(DataKeys.HAS_BEEN_SHEARED)?.enabled?.takeIf { it } ?: run {
return ObjectiveStatus.INACTIVE
}
if (world.random.nextFloat() > eatGrassChance) {
return ObjectiveStatus.ACTIVE
} else {
val blockPos = entity.blockPosition()
// Are we not even on a grass block? Alright don't bother
if (!grassPredicate.test(world.getBlockState(blockPos)) && !world.getBlockState(blockPos.below()).`is`(Blocks.GRASS_BLOCK)) {
return ObjectiveStatus.ACTIVE
}
fixation = brain.fixate(EatGrassFixation(this))
entity.playAnimation("eat")
world.broadcastEntityEvent(entity, 10.toByte())
return ObjectiveStatus.FIXATED
}
}
class EatGrassFixation(val objective: EatGrass) : EntityFixation {
var timer = 40
override fun getDescription(entity: LivingEntity) = "Eating grass"
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isComfort || distraction.isDamage || distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
timer--
if (timer <= 0) {
entity as PokemonEntity
val world = entity.level() as ServerLevel
val blockPos = entity.blockPosition()
if (objective.grassPredicate.test(world.getBlockState(blockPos)) ) {
if (world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING)) {
world.destroyBlock(blockPos, false)
}
entity.ate()
objective.remainingCooldownTicks = objective.cooldownTicks
} else if (world.getBlockState(blockPos.below()).`is`(Blocks.GRASS_BLOCK)) {
val below = blockPos.below()
if (world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING)) {
world.levelEvent(2001, below, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState()))
world.setBlock(below, Blocks.DIRT.defaultBlockState(), 2)
}
entity.ate()
objective.remainingCooldownTicks = objective.cooldownTicks
}
}
return timer > 0
}
}
class Config : ObjectiveConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("400".asExpression())
var eatGrassChance: ExpressionOrEntityVariable = Either.left("1/400".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
cooldownTicks,
eatGrassChance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
val eatGrassChance = eatGrassChance.resolveFloat(behaviourConfigurationContext.runtime)
return if (eatGrassChance == 0F) {
null
} else {
EatGrass(
cooldownTicks = cooldownTicks,
eatGrassChance = eatGrassChance
)
}
}
}
}
@@ -0,0 +1,171 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.objective.PickupItem.Companion.dropItem
import com.cobblemon.mod.common.api.ai.biggerbrain.sense.PokemonItemSense.Companion.PICKUP_ITEMS
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.ObtainableItem
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.findMatchingEntry
import com.cobblemon.mod.common.util.getObjectList
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolve
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.component.DataComponents
import net.minecraft.core.particles.ItemParticleOption
import net.minecraft.core.particles.ParticleTypes
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.server.level.ServerLevel
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
/**
* Eat the currently held item, apply the effect, and drop if it's an undesired item
*
* @author JazzMcNade
* @since February 16th, 2026
*/
class EatHeldItem(
val cooldownTicks: Int,
val pickupItems: List<ObtainableItem>
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = cooldownTicks
override fun getDescription(entity: LivingEntity) = "Eat Held Item"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
val itemStack: ItemStack = entity.pokemon.heldItem()
// FORCE so it still takes over nearly anything, as before, but respects fixations that refuse everything.
if (canEat(itemStack, entity) && brain.distract(Distraction.FORCE)) {
fixation = brain.fixate(EatHeldItemFixation(this))
remainingCooldownTicks = 120
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.INACTIVE
}
fun canEat(item: ItemStack, entity: PokemonEntity): Boolean {
return item.has(DataComponents.FOOD) || pickupItems.findMatchingEntry(entity.registryAccess(), item)?.onUseEffect != null
}
class EatHeldItemFixation(val objective: EatHeldItem) : EntityFixation {
var ticksRemaining = 40
override fun getDescription(entity: LivingEntity) = "Eating held item"
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isComfort || distraction.isDamage || distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val world = entity.level()
if (entity is PokemonEntity && entity.isAlive) {
val itemStack: ItemStack = entity.pokemon.heldItem()
val itemConfig = objective.pickupItems.findMatchingEntry(entity.registryAccess(), itemStack)
if (objective.canEat(itemStack, entity)) {
if (ticksRemaining < 0) {
var resultItemStack = itemStack.finishUsingItem(world, entity)
val configuredReturnItem = itemConfig?.returnItem
resultItemStack = if (configuredReturnItem != ItemStack.EMPTY) ItemStack(BuiltInRegistries.ITEM.get(configuredReturnItem))
else if (resultItemStack.item == itemStack.item)
ItemStack.EMPTY // Items that aren't normally edible return themselves
else
resultItemStack
entity.pokemon.swapHeldItem(resultItemStack)
val onUseEffect = itemConfig?.onUseEffect
if (onUseEffect != null) {
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
mainThreadRuntime.resolve(onUseEffect)
}
if (itemConfig != null && itemConfig.fullnessValue > 0) {
entity.pokemon.feedPokemon(itemConfig.fullnessValue, false)
}
// Check if the result item is something that should be dropped
resultItemStack = entity.pokemon.heldItem()
if ((objective.pickupItems.findMatchingEntry(entity.registryAccess(), resultItemStack)?.pickupPriority ?: 0) < 0) {
// Drop item
resultItemStack = entity.pokemon.swapHeldItem(resultItemStack)
if (!resultItemStack.isEmpty && !entity.level().isClientSide) {
dropItem(entity, resultItemStack)
}
}
return false
} else if ((itemConfig?.fullnessValue ?: 0) > 0 && entity.random.nextFloat() < 0.4f) {
ticksRemaining--
entity.playSound(entity.getEatingSound(itemStack), 1.0f, 1.0f)
world.broadcastEntityEvent(entity, 45.toByte())
spawnFoodParticles(entity, itemStack)
}
}
return true
}
return false
}
private fun spawnFoodParticles(entity: LivingEntity, itemStack: ItemStack) {
val serverLevel = entity.level() as ServerLevel
//TODO: Figure out how to this with snowstorm so we can use mouth/face/head locators
// The issue as of this writing is we don't have a clean way to utilize the item texture for the particle in snowstorm
serverLevel.sendParticles(
ItemParticleOption(ParticleTypes.ITEM, itemStack),
entity.x, entity.y + 0.5, entity.z, // particle position (centered on entity)
5, // count
0.1, 0.1, 0.1, // x, y, z offset spread
0.05 // speed
)
}
}
class Config : ObjectiveConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("120".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
cooldownTicks
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
var pickupItems = emptyList<ObtainableItem>()
if (entity is PokemonEntity) {
pickupItems = entity.config.getObjectList<ObtainableItem>(PICKUP_ITEMS)
}
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return EatHeldItem(
cooldownTicks = cooldownTicks,
pickupItems = pickupItems
)
}
}
}
@@ -0,0 +1,349 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LockFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt as resolveVariableInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.block.entity.NestBlockEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.InteractionHand
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
import net.minecraft.world.phys.Vec3
class EggRecovery(
private val speedMultiplier: Expression = "0.4".asExpression(),
private val searchRadius: Int = 20,
private val searchIntervalTicks: Int = 20
) : Objective {
private var fixation: EntityFixation? = null
private var searchCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Egg Recovery"
override fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive)
return ObjectiveStatus.INVALID
// so only wild mons recover their eggs
if (!entity.pokemon.isWild())
return ObjectiveStatus.INACTIVE
val world = entity.level() as? ServerLevel ?: return ObjectiveStatus.INVALID
// get the nest in memory if it exists and check to see if it has an egg
val nestPos = brain.getMemory(CobblemonMemories.PATERNAL_NEST_LOCATION) ?: return ObjectiveStatus.INACTIVE
if (brain.getMemory(CobblemonMemories.EGG_IN_NEST) != false)
return ObjectiveStatus.INACTIVE
// if there is a theif they are probably being chased so nothing to do about recovery yet
if (brain.hasMemoryValue(CobblemonMemories.EGG_THIEF))
return ObjectiveStatus.INACTIVE
if (brain.isFixation(fixation))
return ObjectiveStatus.FIXATED
// if egg is held it needs to go back to the nest
if (brain.getMemory(CobblemonMemories.HOLDING_EGG) == true)
return returnEgg(entity, brain, world, nestPos)
// if we have a known egg position then go get it
val eggPos = brain.getMemory(CobblemonMemories.EGG_LOCATION)
if (eggPos != null)
return fetchEgg(entity, brain, world, eggPos)
// if any of the above isnt needed then we probably have searching for the egg left
return searchForEgg(entity, brain, world, nestPos, activeObjectiveTags)
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
// start with finding the egg if the location is known when we start.
// should we have an if statement above this to check if we should search for the egg first or go to the egg? idk
brain.subscribe(Priority.LOW, CobblemonMemories.EGG_LOCATION) { eggPos, _ ->
if (eggPos != null && fixation is LookAndMoveFixation && brain.isFixation(fixation)) {
brain.distract(Distraction.FORCE)
fixation = null
}
true
}
}
// look for the egg a while in an area until giving up
private fun searchForEgg(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, nestPos: BlockPos, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING)
// if the countdown is up then clear objective
if (shouldGiveUpSearch(entity, brain, world, nestPos))
return ObjectiveStatus.INACTIVE
// if our cooldown is active then tick it down
if (searchCooldownTicks > 0) {
searchCooldownTicks--
return ObjectiveStatus.ACTIVE
}
// set the cooldown so it can begin
searchCooldownTicks = searchIntervalTicks
// choose a random spot around the nest to check for the egg todo should we have it also consider last seen egg position? or reincorporate player disturbances?
val searchPos = chooseRandomPos(entity, Vec3.atCenterOf(nestPos)) ?: return ObjectiveStatus.ACTIVE
if (!brain.distract(comfortDistraction))
return ObjectiveStatus.BLOCKED
val tracker = RegularMovementTracker.attempt(entity, WalkTarget(searchPos, mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier), 1)) ?: return ObjectiveStatus.ACTIVE
fixation = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE, DistractionType.COMFORT),
description = "Egg Recovery: searching for the egg",
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(entity, tracker.walkTarget),
movementTracker = tracker
)
)
return ObjectiveStatus.FIXATED
}
// has the search countdown ended and should the nest be abandoned?
private fun shouldGiveUpSearch(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, nestPos: BlockPos): Boolean {
// if there is an active countdown and it isnt at the give up timeframe then don't wipe memories yet
if (brain.getMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN) != true)
return false
if (entity.brain.getTimeUntilExpiry(CobblemonMemories.EGG_SEARCH_COUNTDOWN) > GIVE_UP_SEARCH_TIME)
return false
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
brain.eraseMemory(CobblemonMemories.PATERNAL_NEST_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_IN_NEST)
brain.eraseMemory(CobblemonMemories.POTENTIAL_MATE)
val nest = world.getBlockEntity(nestPos) as? NestBlockEntity
// clear the parent info on the nest itself if it is still around
if (nest != null) {
nest.parents = Pair(null, null)
nest.nestClaimedBy = Pair(null, null)
}
return true
}
// path to the egg and pick it up
private fun fetchEgg(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, eggPos: BlockPos): ObjectiveStatus {
val eggCenter = Vec3.atCenterOf(eggPos)
if (entity.position().distanceTo(eggCenter) <= CLOSE_ENOUGH_DISTANCE) {
pickUpEgg(entity, brain, world)
return ObjectiveStatus.ACTIVE
}
if (!brain.distract(comfortDistraction))
return ObjectiveStatus.BLOCKED
val tracker = RegularMovementTracker.attempt(entity, WalkTarget(eggCenter, mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier), 1)) ?: return ObjectiveStatus.ACTIVE
fixation = brain.fixate(FetchEggFixation(this, tracker, LookingTracker.fromNavigationPathOrWalkTarget(entity, tracker.walkTarget)))
return ObjectiveStatus.FIXATED
}
// pickup egg and put it in "hand" of the mon
private fun pickUpEgg(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel): Boolean {
// get any egg item entities that are from the parent and within their pickup radius
val eggItem = world.getEntitiesOfClass(ItemEntity::class.java, entity.boundingBox.inflate(PICKUP_REACH)) { item ->
item.item.item == CobblemonItems.POKEMON_EGG && item.item.get(CobblemonItemComponents.EGG_DATA)?.isParent(entity.pokemon.uuid) == true
}.minByOrNull { it.distanceToSqr(entity) }
if (eggItem == null) {
// the egg isn't where it was last seen so clear location memory
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
return false
}
entity.setItemInHand(InteractionHand.MAIN_HAND, eggItem.item.copy())
eggItem.remove(Entity.RemovalReason.DISCARDED)
brain.setMemory(CobblemonMemories.HOLDING_EGG, true)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
return true
}
// carry the egg back to the nest
private fun returnEgg(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, nestPos: BlockPos): ObjectiveStatus {
// if the nest is gone when trying to bring it back we should maybe drop the egg and stop the objective.... todo or should they just hold the egg forever? build a new nest?
if (world.getBlockEntity(nestPos) !is NestBlockEntity) {
val heldEgg = entity.getItemInHand(InteractionHand.MAIN_HAND)
if (!heldEgg.isEmpty)
entity.spawnAtLocation(heldEgg.copy())
entity.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY)
brain.eraseMemory(CobblemonMemories.HOLDING_EGG)
return ObjectiveStatus.INACTIVE
}
val nestCenter = Vec3.atCenterOf(nestPos)
if (entity.position().distanceTo(nestCenter) <= CLOSE_ENOUGH_DISTANCE) {
placeEgg(entity, brain, world, nestPos)
return ObjectiveStatus.ACTIVE
}
// make sure only forced distactions stop the parent from bringing the egg back
if (!brain.distract(Distraction.FORCE))
return ObjectiveStatus.BLOCKED
val tracker = RegularMovementTracker.attempt(entity, WalkTarget(nestCenter, mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue()).resolveFloat(speedMultiplier), 1)) ?: return ObjectiveStatus.ACTIVE
fixation = brain.fixate(ReturnEggFixation(this, nestPos, tracker, LookingTracker.fromNavigationPathOrWalkTarget(entity, tracker.walkTarget)))
return ObjectiveStatus.FIXATED
}
// place egg in the nest
private fun placeEgg(entity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, nestPos: BlockPos): Boolean {
val nest = world.getBlockEntity(nestPos) as? NestBlockEntity ?: return false
val heldEgg = entity.getItemInHand(InteractionHand.MAIN_HAND)
// if for some reason the parent is not holding the egg anymore
if (heldEgg.isEmpty || heldEgg.item != CobblemonItems.POKEMON_EGG) {
brain.eraseMemory(CobblemonMemories.HOLDING_EGG)
return false
}
// don't place the egg if the nest is not empty
if (!nest.getItem().isEmpty)
return false
nest.setItem(heldEgg.copy())
entity.setItemInHand(InteractionHand.MAIN_HAND, ItemStack.EMPTY)
brain.eraseMemory(CobblemonMemories.HOLDING_EGG)
brain.setMemory(CobblemonMemories.EGG_IN_NEST, true)
return true
}
private fun chooseRandomPos(entity: PokemonEntity, center: Vec3): Vec3? {
// is this bad for performance? At low numbers I assume it won't be too bad but will need to be tested
repeat(SEARCH_ATTEMPTS) {
val offsetX = entity.random.nextDouble() * 2 * searchRadius - searchRadius
val offsetZ = entity.random.nextDouble() * 2 * searchRadius - searchRadius
val blockPos = BlockPos.containing(center.add(offsetX, 0.0, offsetZ))
if (entity.navigation.createPath(blockPos, 0) != null)
return Vec3.atCenterOf(blockPos)
}
return null
}
// fixation for walking to the egg and picking it up
class FetchEggFixation(
private val objective: EggRecovery,
override val movementTracker: MovementTracker,
override val lookingTracker: LookingTracker
) : EntityFixation, MovementTrackerFixation, LookingTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Egg Recovery: going to get egg"
// if they are hurt or forced they should stop being fixated
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isDamage || distraction.isForce
// we should stop the moving tracker when distracted (do we need to stop anything else?)
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity)
return false
val world = entity.level() as? ServerLevel ?: return false
lookingTracker.tick()
when (movementTracker.tick()) {
MovementStatus.PENDING -> return true
// movement is done (hopefully at the right spot) so try to pickup the egg
MovementStatus.COMPLETED -> objective.pickUpEgg(entity, brain, world)
// if anything happens try to get a new egg location
MovementStatus.FAILED -> brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
}
return false
}
}
// path back to nest and place the egg
class ReturnEggFixation(
private val objective: EggRecovery,
private val nestPos: BlockPos,
override val movementTracker: MovementTracker,
override val lookingTracker: LookingTracker
) : EntityFixation, MovementTrackerFixation, LookingTrackerFixation, LockFixation {
override fun getDescription(entity: LivingEntity) = "Egg Recovery: taking egg back to nest"
// only force for now but we might want to distract if damaged later
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
// same as above stop movement if distracted
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity)
return false
val world = entity.level() as? ServerLevel ?: return false
lookingTracker.tick()
if (movementTracker.tick() == MovementStatus.PENDING)
return true
if (movementTracker.lastStatus == MovementStatus.COMPLETED)
objective.placeEgg(entity, brain, world, nestPos)
return false
}
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
val searchRadius: ExpressionOrEntityVariable = Either.left("20".asExpression())
val searchIntervalTicks: ExpressionOrEntityVariable = Either.left("20".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): List<MoLangConfigVariable> {
return listOf(speedMultiplier, searchRadius, searchIntervalTicks).asVariables()
}
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
behaviourConfigurationContext.addMemories(
CobblemonMemories.PATERNAL_NEST_LOCATION,
CobblemonMemories.EGG_IN_NEST,
CobblemonMemories.EGG_LOCATION,
CobblemonMemories.EGG_THIEF,
CobblemonMemories.EGG_SEARCH_COUNTDOWN,
CobblemonMemories.HOLDING_EGG,
CobblemonMemories.POTENTIAL_MATE
)
return EggRecovery(
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
searchRadius = searchRadius.resolveVariableInt(behaviourConfigurationContext.runtime),
searchIntervalTicks = searchIntervalTicks.resolveVariableInt(behaviourConfigurationContext.runtime)
)
}
}
companion object {
private const val CLOSE_ENOUGH_DISTANCE = 1.5 // should this be bigger for the bigger mons or be based off of hitbox?
private const val PICKUP_REACH = 1.5 // slight radius around the mon so they don't have to physically be on top of the egg
private const val SEARCH_ATTEMPTS = 10
private const val GIVE_UP_SEARCH_TIME = 20L // is this enough time for search? Needs playtesting
}
}
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.moves.RealTimeMove
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveString
import com.cobblemon.mod.common.util.withQueryValue
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
abstract class EntityResponseObjective(
val speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
val engageRange: Expression = "15.0".asExpression(),
val disengageRange: Expression = "20.0".asExpression(),
val condition: Expression = "true".asExpression(), // Self/environment condition check
val targetCondition: Expression = "true".asExpression(), // target condition (will be checked on entity interaction)
description: Expression = "'EntityResponseObjective'".asExpression(),
) : Objective {
var trackedEntity: LivingEntity? = null
private val objectiveDescription: String = mainThreadRuntime.resolveString(description)
override fun getDescription(entity: LivingEntity) = objectiveDescription
open fun scanForValidTargets(entity: LivingEntity, brain: BiggerBrain): LivingEntity? {
//TODO: need to apply some sort of awareness modifier
// Sleep obviously should dramatically affect this but it's not hard to imagine other things that could do this
if (entity.isSleeping || (entity is PokemonEntity && entity.pokemon.status?.status == Statuses.SLEEP)) {
// Also why doesn't entity.isSleeping for PokemonEntities return true if the sleep status is applied?
return null
}
// Check if we're in the mood to fight
if (mainThreadRuntime.withQueryValue("entity", (entity).asMostSpecificMoLangValue())
.resolveBoolean(condition)
) {
// Scan visible livingEntities
val entities: NearestVisibleLivingEntities =
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return null
val targetEntity = entities.findClosest { it ->
val runtime = mainThreadRuntime.withQueryValue("target", (it).asMostSpecificMoLangValue())
val isValidTarget =
runtime.resolveBoolean(targetCondition) && runtime.resolveFloat(engageRange) > entity.distanceTo(it)
isValidTarget
}.orElse(null)
if (targetEntity != null) return targetEntity
}
return null
}
open fun shouldContinue(entity: LivingEntity, brain: BiggerBrain): Boolean {
trackedEntity ?: return false
if (trackedEntity!!.isDeadOrDying) return false
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
.withQueryValue("target", (trackedEntity!!).asMostSpecificMoLangValue())
return (runtime.resolveBoolean(condition) // self condition
&& runtime.resolveBoolean(targetCondition) // target condition
&& (runtime.resolveFloat(disengageRange) > entity.distanceTo(trackedEntity!!)))
}
open fun getRealTimeMoves(entity: LivingEntity) : List<RealTimeMove> {
var moves = if (entity is PokemonEntity) entity.pokemon.species.behaviour.combat.moves else emptyList()
if (moves.isEmpty() && entity is PokemonEntity) {
moves = listOf(
if (entity.pokemon.attack > entity.pokemon.specialAttack) RealTimeMove.defaultMelee else RealTimeMove.defaultRange
)
}
return moves
}
}
@@ -0,0 +1,250 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.HurtDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LockFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveBoolean
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.scheduling.afterOnServer
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonBehaviourFlag
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* An objective that ensures the entity, whether it's a PokemonEntity or an NPCEntity, will pay attention to its
* opponents in battle. They will not move, and will look at its opponents. For Pokémon, they will focus on the
* targeted opponent if one exists; otherwise, they will randomly look at one of their opponent Pokémon. For NPCs,
* they will randomly look at one of their opponent Pokémon.
*
* If the entity gets hurt and [stopBattleIfHurt] is true, this objective stops the battle.
*
* @author Hiroku
* @since December 29th, 2025
*/
class FocusDuringBattle(
var stopBattleIfHurt: Boolean = true,
var minDurationTicks: Int = 40,
var maxDurationTicks: Int = 80
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Look at battle opponents"
override fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus {
if (entity !is NPCEntity && entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
}
if (stopBattleIfHurt && brain.hasMemoryValue(MemoryModuleType.HURT_BY)) {
if (brain.isFixation(fixation)) {
if (entity is PokemonEntity) {
entity.battle?.stop()
} else if (entity is NPCEntity) {
entity.battleIds.mapNotNull { BattleRegistry.getBattle(it) }.forEach { it.stop() }
}
brain.distract(Distraction.FORCE)
}
return ObjectiveStatus.INACTIVE
}
val isInBattle = isInBattle(entity)
if (brain.isFixation(fixation)) {
if (isInBattle) {
// Ok this is fine
return ObjectiveStatus.FIXATED
} else {
// Alright my work here is done, going back to inactive.
fixation = null
brain.fixation = null
return ObjectiveStatus.INACTIVE
}
} else if (!isInBattle) {
// Ok we don't need to do anything
fixation = null
return ObjectiveStatus.INACTIVE
} else {
// We need to start focusing
if (brain.distract(Distraction.FORCE)) {
fixation = if (entity is NPCEntity) NPCFocusFixation(this) else PokemonFocusFixation(this)
// Handle kick starting flight for flying pokemon over water
if (entity is PokemonEntity && entity.exposedForm.behaviour.moving.fly.canFly) {
if (entity.ticksLived >= 0 && entity.navigation.isAirborne(entity.level(), entity.blockPosition())) {
// Let flyers fly in battle if they're in the air
entity.setBehaviourFlag(PokemonBehaviourFlag.FLYING, true)
afterOnServer(0.1F) {
entity.navigation.moveTo(entity.x, entity.y + 0.2, entity.z, 1.0)
}
}
}
brain.fixation = fixation
return ObjectiveStatus.FIXATED
} else {
return ObjectiveStatus.BLOCKED
}
}
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.HURT_BY
) { value, labels ->
if (brain.isFixation(fixation) && value != null && stopBattleIfHurt) {
brain.distract(HurtDistraction(value))
}
return@subscribe true
}
}
fun isInBattle(entity: LivingEntity): Boolean {
return when (entity) {
is PokemonEntity -> entity.isBattling
is NPCEntity -> entity.isInBattle()
else -> false
}
}
class NPCFocusFixation(val objective: FocusDuringBattle) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
var ticksUntilReacquireTarget: Int = 0
override fun getDescription(entity: LivingEntity): String {
return if (lookingTracker == null) {
"Looking for an opponent Pokémon to look at"
} else {
"Looking at targeted or opponent Pokémon"
}
}
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
fun acquireLookTarget(entity: NPCEntity, brain: BiggerBrain) {
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return
val randomBattlingPokemon = battlingPokemon.randomOrNull()?.let { (entity.level() as ServerLevel).getEntity(it) }
if (randomBattlingPokemon != null) {
lookingTracker = LookingTracker(entity, EntityTracker(randomBattlingPokemon, true))
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is NPCEntity) {
return false
}
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return false
val lookingTracker = lookingTracker
if (lookingTracker != null && lookingTracker.entity.uuid !in battlingPokemon) {
this.lookingTracker = null
ticksUntilReacquireTarget = 0
}
if (ticksUntilReacquireTarget <= 0) {
acquireLookTarget(entity, brain)
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
} else {
ticksUntilReacquireTarget--
}
lookingTracker?.tick()
return true
}
}
class PokemonFocusFixation(val objective: FocusDuringBattle) : EntityFixation, LookingTrackerFixation, LockFixation {
var ticksUntilReacquireTarget: Int = 0
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return if (lookingTracker == null) {
"Looking for an opponent Pokémon to look at"
} else {
"Looking at targeted or opponent Pokémon"
}
}
override fun canDistract(distraction: Distraction, entity: LivingEntity) = distraction.isForce
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) {
return false
}
val battlingPokemon = brain.getMemory(CobblemonMemories.BATTLING_POKEMON) ?: return false
val targetedBattlePokemon = brain.getMemory(CobblemonMemories.TARGETED_BATTLE_POKEMON)
val lookingTracker = lookingTracker
// If there is a targetedBattlePokemon then that is the highest priority, and we should not look away
// Otherwise, look at one of the entities for a while and occasionally reacquire the target.
if (targetedBattlePokemon != null && (lookingTracker == null || lookingTracker.entity.uuid != targetedBattlePokemon)) {
// We should be targeting the targetedBattlePokemon
val targetedPokemon = (entity.level() as ServerLevel).getEntity(targetedBattlePokemon) ?: return false
this.lookingTracker = LookingTracker(entity, EntityTracker(targetedPokemon, true))
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
} else if (targetedBattlePokemon == null && ticksUntilReacquireTarget <= 0) {
// Choose someone to look at
val randomBattlingPokemon = battlingPokemon.randomOrNull()?.let { (entity.level() as ServerLevel).getEntity(it) }
if (randomBattlingPokemon != null) {
this.lookingTracker = LookingTracker(entity, EntityTracker(randomBattlingPokemon, true))
ticksUntilReacquireTarget = (objective.minDurationTicks..objective.maxDurationTicks).random()
}
}
ticksUntilReacquireTarget--
this.lookingTracker?.tick()
return true
}
}
class Config : ObjectiveConfig {
var stopBattleIfHurt: ExpressionOrEntityVariable = Either.left("true".asExpression())
var minDurationTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
var maxDurationTicks: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
stopBattleIfHurt,
minDurationTicks,
maxDurationTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val stopBattleIfHurt = stopBattleIfHurt.resolveBoolean(behaviourConfigurationContext.runtime)
val minDurationTicks = minDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
val maxDurationTicks = maxDurationTicks.resolveInt(behaviourConfigurationContext.runtime)
return FocusDuringBattle(
stopBattleIfHurt = stopBattleIfHurt,
minDurationTicks = minDurationTicks,
maxDurationTicks = maxDurationTicks
)
}
}
}
@@ -0,0 +1,257 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
import net.minecraft.world.entity.ai.memory.WalkTarget
class FriendlyBehaviour(
speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
engageRange: Expression = "10.0".asExpression(),
disengageRange: Expression = "20.0".asExpression(),
condition: Expression = "true".asExpression(),
targetCondition: Expression = "false".asExpression(),
private val maxDuration: Expression = "300".asExpression(),
private val description: Expression = "Friendly Behaviour".asExpression(),
) : EntityResponseObjective(
speedMultiplier = speedMultiplier, // How do we transfer speed to the attack behaviour? Do we want to?
engageRange = engageRange,
disengageRange = disengageRange,
condition = condition, // Self/environment condition check
targetCondition = targetCondition, // target condition (will be checked on entity interaction)
description = description,
) {
private var remainingCooldownTicks = 0
private var fixation: EntityFixation? = null
private val closeEnoughDistance = 1.5
private var remainingTicks = 0
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return if (brain.isFixation(fixation)) ObjectiveStatus.FIXATED else ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = 5
}
if (brain.isFixation(fixation)) {
if (remainingTicks > 0) {
remainingTicks--
} else {
// Got bored, move on
brain.distract(Distraction.FORCE)
trackedEntity = null
fixation = null
}
if (trackedEntity != null) {
// Check if we continue
return attemptFixation(entity, brain)
} else {
trackedEntity = null
fixation = null
brain.distract(comfortDistraction)
}
return ObjectiveStatus.FIXATED
} else {
// Scan visible livingEntities
val targetEntity = scanForValidTargets(entity, brain)
if (targetEntity != null) {
trackedEntity = targetEntity
val status = attemptFixation(entity, brain)
if (status == ObjectiveStatus.FIXATED) {
remainingTicks = mainThreadRuntime.resolveInt(maxDuration)
}
return status
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
}
fun attemptFixation(entity: PathfinderMob, brain: BiggerBrain) : ObjectiveStatus {
if (trackedEntity != null) {
// Check if we continue
val runtime = mainThreadRuntime.withQueryValue("entity", (entity).asMostSpecificMoLangValue())
.withQueryValue("target", trackedEntity!!.asMostSpecificMoLangValue())
val distance = entity.distanceTo(trackedEntity!!)
if (runtime.resolveFloat(disengageRange) < distance || !shouldContinue(entity, brain)) {
brain.distract(comfortDistraction)
trackedEntity = null
fixation = null
return ObjectiveStatus.INACTIVE
} else if (distance <= closeEnoughDistance && !(brain.isFixation(fixation) && fixation is IdleLookFixation)) {
// transition to look
val distraction = if(brain.isFixation(fixation)) Distraction.FORCE else idleBoredomDistraction
if (brain.distract(distraction)) {
this.fixation = brain.fixate(
IdleLookFixation(
LookingTracker(
entity,
EntityTracker(trackedEntity!!, true)
),
remainingTicks
)
)
return ObjectiveStatus.FIXATED
} else {
// could not distract
return ObjectiveStatus.BLOCKED
}
} else if (distance > closeEnoughDistance && !(brain.isFixation(fixation) && fixation is LookAndMoveFixation)) {
// transition to walk
val distraction = if(brain.isFixation(fixation)) Distraction.FORCE else idleBoredomDistraction
if (brain.distract(distraction)) {
val walkTarget =
WalkTarget(EntityTracker(trackedEntity!!, true), runtime.resolveFloat(speedMultiplier), 0)
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.INACTIVE
this.fixation = brain.fixate(
LookAndMoveFixation(
description = "Following targeted entity",
distractionTypes = setOf(
DistractionType.COMFORT,
DistractionType.DAMAGE,
DistractionType.FORCE
),
lookingTracker = LookingTracker.forTargetEntity(entity, trackedEntity!!),
movementTracker = movementTracker,
onMovementComplete = { _, _ -> attemptFixation(entity, brain) } // maintains fixation between moving and looking
)
)
return ObjectiveStatus.FIXATED
} else {
return ObjectiveStatus.BLOCKED
}
} else {
return ObjectiveStatus.FIXATED
}
}
return ObjectiveStatus.INACTIVE
}
class IdleLookFixation(
override val lookingTracker: LookingTracker?,
var remainingTicks: Int,
) : EntityFixation, LookingTrackerFixation {
override fun getDescription(entity: LivingEntity): String {
return "Looking at a nearby entity ($remainingTicks ticks left)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return !distraction.isIdleBoredom
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val targetEntity = lookingTracker?.entity ?: return false
if ((targetEntity.isRemoved) || entity !is PathfinderMob) {
return false
}
val lookingTracker = lookingTracker
remainingTicks--
lookingTracker.tick()
return remainingTicks > 0
}
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = CobblemonMemories.ATTACK_TARGET_DATA
) { value, labels ->
if (value != null) {
val livingEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET) ?: return@subscribe true
if (trackedEntity?.uuid == livingEntity.uuid) {
// We smacked them, refresh our attack timer
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
val attackDuration = runtime.resolveInt(maxDuration)
brain.setMemory(MemoryModuleType.ATTACK_TARGET, livingEntity, attackDuration.toLong())
}
}
return@subscribe true
}
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val engageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("20.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val maxDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val description: ExpressionOrEntityVariable = Either.left("Test".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
targetCondition,
speedMultiplier,
engageRange,
disengageRange,
maxDuration,
description,
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return FriendlyBehaviour(
condition = condition.asSimplifiedExpression(entity),
targetCondition = targetCondition.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
maxDuration = maxDuration.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,508 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.task.PollinateFlowerTaskConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.block.SaccharineLeafBlock
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.MemoryStatus
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.level.block.BeehiveBlock
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.phys.Vec3
/**
* Mimics the vanilla bee behavior, with added interactions with Saccharine leaves.
* Only wild bees are allowed to enter hives because of dupe risks with pasture blocks.
*
* @author JazzMcNade
* @since February 23th, 2026
*/
class GatherNectar(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.2".asExpression()
) : Objective {
var workerFixation: EntityFixation? = null
var shelterFixation: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Worker Bee"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(shelterFixation)) {
// Never preempt the shelter fixation
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else if (!entity.biggerBrain.hasMemoryValue(CobblemonMemories.HIVE_LOCATION) && !entity.biggerBrain.hasMemoryValue(CobblemonMemories.NEARBY_SACC_LEAVES)) {
return ObjectiveStatus.INACTIVE
}
val world = entity.level()
if ((world.isRaining || world.isNight) ) {
if (!brain.distract(comfortDistraction)) {
return ObjectiveStatus.BLOCKED
}
// Return to hive or do nothing
if (entity.pokemon.isWild()) {
// Only wilds can path to hives
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos != null && wantsToEnterHive(entity)) {
// Deliver to hive
if (!tryEnterHive(entity)) { // Attempt to enter the hive, if we fail, probably too far away
val hiveEntrance = getHiveEntrance(hivePos, entity)
if (hiveEntrance != null) {
// Move to hive
shelterFixation = tryMovementFixation(entity, hiveEntrance, "Sheltering in Hive", ::onHiveMovementComplete)
} else {
// Blacklist the hive
dropAndBlackListHive(entity)
}
} // no else the entity is gone and is stored in the hive
}
} else {
return ObjectiveStatus.INACTIVE
}
} else if (brain.isFixation(workerFixation)) {
// Already fixated on the work
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
} else {
// Perform nectar gathering/delivery
if (!brain.distract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
if (entity.biggerBrain.hasMemoryValue(CobblemonMemories.HAS_NECTAR) ) {
// Deliver nectar to hive or Sacc leaves
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos != null && wantsToEnterHive(entity) && entity.pokemon.isWild()) {
// Deliver to hive
if (!tryEnterHive(entity)) { // Attempt to enter the hive, if we fail, probably too far away
val hiveEntrance = getHiveEntrance(hivePos, entity)
if (hiveEntrance != null) {
// Move to hive
workerFixation = tryMovementFixation(entity, hiveEntrance, "Delivering nectar to hive", ::onHiveMovementComplete)
} else {
// Blacklist the hive
dropAndBlackListHive(entity)
}
} // no else the entity is gone and is stored in the hive
} else {
// Deliver to Saccharine Leaves
val sacLeafPos : BlockPos = entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
?: return ObjectiveStatus.INACTIVE
if (entity.blockPosition() != sacLeafPos) {
workerFixation = tryMovementFixation(entity, sacLeafPos, "Delivering nectar to Saccharine Leaves")
return ObjectiveStatus.ACTIVE
} else {
// Do nectar deposit fixation
workerFixation = brain.fixate(DepositNectarInSaccharineLeavesFixation())
return ObjectiveStatus.ACTIVE
}
}
} else {
// Gather Nectar
val flowerPos =
entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_FLOWER) ?: return ObjectiveStatus.INACTIVE
val distance = entity.distanceTo(flowerPos)
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
if (distance < 1.0) {
// Pollinate/Gather nectar from the flower
if (workerFixation !is PollinateFlowerFixation && brain.distract(idleBoredomDistraction)) {
workerFixation = brain.fixate(PollinateFlowerFixation())
return ObjectiveStatus.FIXATED
}
} else if (distance < maxDistance) {
// Move to the flower
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction) && !brain.hasMemoryValue(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN
)
) {
remainingCooldownTicks = ticksBetweenAttempts
workerFixation = tryMovementFixation(entity, flowerPos, "Moving to flower")
}
}
}
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
return ObjectiveStatus.ACTIVE
}
/*
* This Fixation has movement, but it doesn't utilize pathfinding, and it's more about flavor than accomplishing a goal
*
*
*/
class PollinateFlowerFixation(
) : EntityFixation {
var successfulPollinationTicks = 0
var lastSoundPlayedTick = 0
var hoverPos: Vec3? = null
override fun getDescription(entity: LivingEntity) = "Pollinating Flower"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || distraction.isComfort || entity.brain.hasMemoryValue(
CobblemonMemories.HAS_NECTAR
)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PollinateFlowerTaskConfig.Companion.PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
val flowerPos = entity.brain.getMemorySafely(CobblemonMemories.NEARBY_FLOWER).orElse(null)
if (!(flowerPos != null && Vec3.atCenterOf(flowerPos).distanceTo(entity.position()) <= 1.0)) {
onStop(entity)
return false
}
++successfulPollinationTicks
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
onStop(entity)
return false
}
if (entity.random.nextFloat() < 0.05f && successfulPollinationTicks > this.lastSoundPlayedTick + 60) {
this.lastSoundPlayedTick = successfulPollinationTicks
entity.playSound(SoundEvents.BEE_POLLINATE, 1.0f, 1.0f)
}
val bl = hoverPos == null || entity.position().distanceTo(hoverPos!!) <= 0.1
val bl3 = entity.random.nextInt(40) == 0
if (bl && bl3) {
// mimics the wriggling over a flower the vanilla bees do
if (hoverPos == null) {
hoverPos = flowerPos.bottomCenter.add(0.0, 0.4, 0.0)
}
hoverPos = flowerPos.bottomCenter.add(
Vec3(
(entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 5.0),
0.3 + (entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 7.0),
(entity.random.nextDouble() * 2.0 - 1.0) * (1.0 / 5.0)
)
)
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
entity.lookControl.setLookAt(flowerPos.bottomCenter.add(0.0, 0.5, 0.0))
} else if (!bl) {
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
}
entity.lookControl.setLookAt(flowerPos.bottomCenter.add(0.0, 0.5, 0.0))
return true
}
fun onStop(entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
}
class DepositNectarInSaccharineLeavesFixation() : EntityFixation {
var successfulPollinationTicks = 0
var lastSoundPlayedTick = 0
var hoverPos: Vec3? = null
override fun getDescription(entity: LivingEntity) = "Depositing nectar in Saccharine Leaves"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || distraction.isComfort || entity.brain.hasMemoryValue(
CobblemonMemories.HAS_NECTAR
)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
hoverPos = null
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
entity.brain.setMemory(CobblemonMemories.HAS_NECTAR, true)
}
successfulPollinationTicks = 0
entity.brain.setMemoryWithExpiry(
CobblemonMemories.PATH_TO_NEARBY_FLOWER_COOLDOWN, true,
PollinateFlowerTaskConfig.Companion.PATH_TO_FLOWER_COOLDOWN_TICKS
)
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PokemonEntity) return false
++successfulPollinationTicks
if (successfulPollinationTicks > REQUIRED_SUCCESSFUL_POLLINATION_TICKS) {
val blockPos = brain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES)
blockPos?.let {
val world = entity.level()
val blockState = world.getBlockState(blockPos)
if (blockState.block == CobblemonBlocks.SACCHARINE_LEAVES) {
val saccAge = blockState.getValue( SaccharineLeafBlock.AGE)
if (saccAge < SaccharineLeafBlock.MAX_AGE) {
brain.eraseMemory(CobblemonMemories.HAS_NECTAR)
val newBlockState = blockState.setValue(SaccharineLeafBlock.AGE, saccAge + 1)
world.setBlock(blockPos, newBlockState, 3)
}
}
}
return false
}
if (entity.random.nextFloat() < 0.05f && successfulPollinationTicks > this.lastSoundPlayedTick + 60) {
this.lastSoundPlayedTick = successfulPollinationTicks
entity.playSound(SoundEvents.BEEHIVE_DRIP, 1.0f, 1.0f)
}
val leavesPos = brain.getMemory(CobblemonMemories.NEARBY_SACC_LEAVES) ?: return false
val bl = hoverPos == null || entity.position().distanceTo(hoverPos!!) <= 0.1
val bl3 = entity.random.nextInt(40) == 0
if (bl && bl3) {
// mimics the wriggling over a flower the vanilla bees do
if (hoverPos == null) {
hoverPos = leavesPos.bottomCenter.add(0.0, 0.4, 0.0)
}
hoverPos = leavesPos.bottomCenter.add(Vec3((entity.random.nextDouble() * 2.0 - 1.0) * (1.0/5.0), 0.3 + (entity.random.nextDouble() * 2.0 - 1.0) * (1.0/7.0), (entity.random.nextDouble() * 2.0 - 1.0) * (1.0/5.0)))
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
entity.lookControl.setLookAt(leavesPos.bottomCenter.add(0.0,0.5,0.0))
} else if (!bl) {
entity.getMoveControl()
.setWantedPosition(hoverPos!!.x(), hoverPos!!.y(), hoverPos!!.z(), 0.35)
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return GatherNectar(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
fun onHiveMovementComplete(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is PokemonEntity) return
if(!tryEnterHive(entity)) {
dropAndBlackListHive(entity)
}
}
fun tryMovementFixation(
entity: PokemonEntity,
blockPos: BlockPos,
description : String,
onMovementComplete : ((entity: LivingEntity, brain: BiggerBrain) -> Unit)? = null,
) : EntityFixation? {
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
blockPos,
speedMultiplier,
0
)
)
if (movementTracker != null) {
val fixation = entity.biggerBrain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(
DistractionType.DAMAGE,
DistractionType.COMFORT,
DistractionType.FORCE
),
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(
entity,
movementTracker.walkTarget
),
movementTracker = movementTracker,
description = description,
onMovementComplete = onMovementComplete
)
)
return fixation
}
return null
}
fun getHiveEntrance(hiveLocation: BlockPos, entity: LivingEntity) : BlockPos? {
val sidesByClosest = listOf(
hiveLocation.north(),
hiveLocation.south(),
hiveLocation.east(),
hiveLocation.west()
).sortedBy { it.distSqr(entity.blockPosition()) }
val world = entity.level()
var openSide = BlockPos.ZERO
for (side in sidesByClosest) {
if (world.getBlockState(side).isAir) {
openSide = side
break
}
}
if (openSide == BlockPos.ZERO) {
if (world.getBlockState(hiveLocation.above()).isAir) {
// If the above position is also air, we can use it
openSide = hiveLocation.above() // Fallback to above if no open sides found
} else if (world.getBlockState(hiveLocation.below()).isAir) {
// If the below position is also air, we can use it
openSide = hiveLocation.below() // Fallback to below if no open sides found
} else {
// If no open sides or above/below positions are found, we cannot proceed
return null
}
}
return openSide
}
fun tryEnterHive(entity: LivingEntity): Boolean {
if (entity !is PokemonEntity || !wantsToEnterHive(entity)) {
return false
}
val hiveLocation = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION) ?: return false
val targetVec = Vec3.atCenterOf(hiveLocation)
// if we are not close to it then end early
if (entity.distanceToSqr(targetVec) > 1.6 * 1.6) {
return false
}
val state = entity.level().getBlockState(hiveLocation)
val block = state.block
if (block is BeehiveBlock) {
val blockEntity = entity.level().getBlockEntity(hiveLocation)
if (blockEntity !is BeehiveBlockEntity) return false
if (blockEntity.isFull) {
// Erase Hive memory and give the bee a moment to locate a new hive
dropAndBlackListHive(entity)
} else {
blockEntity.addOccupant(entity)
return true
}
}
return false
}
fun wantsToEnterHive(entity: LivingEntity): Boolean {
val result = !entity.brain.checkMemory(CobblemonMemories.HIVE_COOLDOWN, MemoryStatus.VALUE_PRESENT)
&& (entity.level().isRaining || entity.level().isNight || entity.brain.getMemory(CobblemonMemories.HAS_NECTAR)
.orElse(false))
if (result) {
val blockPos = entity.brain.getMemorySafely(CobblemonMemories.HIVE_LOCATION).orElse(null)
val blockEntity = entity.level().getBlockEntity(blockPos)
return blockEntity is BeehiveBlockEntity && !blockEntity.isFireNearby
}
return false
}
fun dropAndBlackListHive(entity: PokemonEntity) {
val hivePos = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_LOCATION)
if (hivePos == null) return
val blackList : MutableList<BlockPos> = entity.biggerBrain.getMemory(CobblemonMemories.HIVE_BLACKLIST)?.toMutableList() ?: emptyList<BlockPos>().toMutableList()
blackList.add(hivePos)
if (blackList.count() > 3) {
blackList.removeFirst()
}
entity.brain.eraseMemory(CobblemonMemories.HIVE_LOCATION)
entity.brain.setMemory(CobblemonMemories.HIVE_BLACKLIST, blackList)
}
companion object {
const val PATH_TO_FLOWER_COOLDOWN_TICKS: Long = 200
const val HAS_NECTAR_ASPECT = "has_nectar"
const val MIN_DURATION: Int = 300
const val MAX_DURATION: Int = 400
const val REQUIRED_SUCCESSFUL_POLLINATION_TICKS = 250
}
}
@@ -0,0 +1,155 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonActivities
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.status.PersistentStatusContainer
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Sleeps the entity.
*
* @author Hiroku
* @since December 29th, 2025
*/
class GoToSleep(
val onlyFromStatus: Expression = "false".asExpression(),
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Sleeping"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
}
// Don't sleep if we're not tired
brain.getMemory(CobblemonMemories.POKEMON_DROWSY)
?: return ObjectiveStatus.INACTIVE
val hasSleepStatus = entity.pokemon.status?.status === Statuses.SLEEP
if (entity.behaviour.resting.canSleep && entity.canSleepAt(entity.blockPosition().below()) || hasSleepStatus) {
if (!hasSleepStatus) {
if (mainThreadRuntime.resolveBoolean(onlyFromStatus)) {
return ObjectiveStatus.BLOCKED
}
entity.pokemon.status = PersistentStatusContainer(Statuses.SLEEP)
}
entity.brain.eraseMemory(MemoryModuleType.WALK_TARGET)
entity.navigation.stop()
entity.brain.setActiveActivityToFirstValid(listOf(CobblemonActivities.POKEMON_SLEEPING_ACTIVITY))
entity.brain.setMemory(CobblemonMemories.POKEMON_SLEEPING, true)
// Become fixated
fixation = brain.fixate(
SleepFixation(
this,
null
)
)
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.BLOCKED
}
class SleepFixation(
val objective: GoToSleep,
override val movementTracker: MovementTracker?,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity): String {
return "Sleeping"
}
override fun tickMovementFixation(): MovementStatus? {
return MovementStatus.PENDING
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
if (distraction.isIdleBoredom) {
return false
}
wakeUp(entity)
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (!entity.brain.getMemorySafely(CobblemonMemories.POKEMON_DROWSY).orElse(false)) {
wakeUp(entity)
return false
}
return true
}
fun wakeUp(entity: LivingEntity) {
if (entity !is PokemonEntity) return
val hasSleepStatus = entity.pokemon.status?.status == Statuses.SLEEP
if (hasSleepStatus && entity.pokemon.storeCoordinates.get()?.store is PartyStore) {
return // You can't wake up if you're in the party with the sleep status.
}
if (hasSleepStatus) {
entity.pokemon.status = null
}
entity.brain.eraseMemory(CobblemonMemories.POKEMON_SLEEPING)
entity.brain.useDefaultActivity()
}
}
class Config : ObjectiveConfig {
val onlyFromStatus: ExpressionOrEntityVariable = Either.left("false".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
onlyFromStatus
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return GoToSleep(
onlyFromStatus = onlyFromStatus.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,204 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.level.GameRules
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.CaveVines
import net.minecraft.world.level.block.SweetBerryBushBlock
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.gameevent.GameEvent
/**
* Paths to ripened sweet berry bushes AND glowberry vines with berries.
* Upon reaching the target harvests the berries and stashes one in its
* held item slot if possible.
* Requires NEARBY_SWEET_BERRY_BUSH memory
*
* @author JazzMcNade
* @since February 8th, 2026
*/
class HarvestSweetBerryBush(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var harvestTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Harvesting sweet/glow berry"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(harvestTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val berryPosition = entity.biggerBrain.getMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH) ?: return ObjectiveStatus.INACTIVE
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val distance = entity.distanceTo(berryPosition)
if (distance < maxDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
berryPosition,
speedMultiplier,
1
)
)
if (movementTracker != null) {
harvestTask = brain.fixate(
fixation = HarvestSweetBerryBushFixation(
entity = entity,
movementTracker = movementTracker
)
)
}
}
}
return ObjectiveStatus.ACTIVE
}
class HarvestSweetBerryBushFixation(
entity: PathfinderMob,
override val movementTracker: MovementTracker,
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
override val lookingTracker: LookingTracker = LookingTracker(entity = entity, lookTarget = movementTracker.walkTarget.target)
override fun getDescription(entity: LivingEntity) = "Harvesting sweet/glow berry"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || (movementTracker.lastStatus == MovementStatus.COMPLETED && entity.brain.getMemorySafely(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) != null)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
movementTracker.tick()
if (movementTracker.lastStatus == MovementStatus.COMPLETED) {
val world = entity.level()
if (entity !is PokemonEntity) return false
if (!world.gameRules.getRule(GameRules.RULE_MOBGRIEFING).get()) {
// Not allowed to alter the world
return false
}
val blockPos = entity.brain.getMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) ?: return false
val blockState = world.getBlockState(blockPos)
if (CaveVines.hasGlowBerries(blockState)) { // Glow Berries Case
CaveVines.use(entity, blockState, world, blockPos)
} else if (blockState.`is`(Blocks.SWEET_BERRY_BUSH)) { // Sweet Berries Case
blockState.setValue(SweetBerryBushBlock.AGE, 1)
var j: Int = 1 + entity.level().random.nextInt(2) + if (blockState.getValue<Int>(SweetBerryBushBlock.AGE) == 3) 1 else 0
val itemStack: ItemStack = entity.pokemon.heldItem
if (itemStack.isEmpty) {
entity.pokemon.swapHeldItem(ItemStack(Items.SWEET_BERRIES))
--j
}
if (j > 0) {
Block.popResource(entity.level(), blockPos, ItemStack(Items.SWEET_BERRIES, j))
}
entity.playSound(SoundEvents.SWEET_BERRY_BUSH_PICK_BERRIES, 1.0f, 1.0f)
entity.level().setBlock(blockPos, blockState.setValue(SweetBerryBushBlock.AGE, 1) as BlockState, 2)
entity.level().gameEvent(GameEvent.BLOCK_CHANGE, blockPos, GameEvent.Context.of(entity))
}
entity.brain.eraseMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH)
return false
} else if (movementTracker.lastStatus == MovementStatus.FAILED) {
// Cannot reach, give up for a awhile
entity.brain.setMemoryWithExpiry(CobblemonMemories.DISABLE_WALK_TO_BERRY_BUSH, true, 200)
entity.brain.eraseMemory(CobblemonMemories.NEARBY_SWEET_BERRY_BUSH)
return false
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return HarvestSweetBerryBush(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,409 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.CobblemonWanderControl
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.storage.party.PartyStore
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.pokemon.ai.ToleratedHerdLeader
import com.cobblemon.mod.common.pokemon.status.PersistentStatusContainer
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.toBlockPos
import com.mojang.datafixers.util.Either
import java.util.UUID
import kotlin.math.cos
import kotlin.math.sin
import net.minecraft.server.level.ServerLevel
import net.minecraft.util.Mth
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.phys.Vec3
class Herd(
var checkTicks: Int = 60,
var tooFar: Float = 8F,
var closeEnough: Float = 4F,
/** Chance per tick of following the herd leader. */
val chance: Float = 1 / 60F,
val pathingCooldownTicks: Int = 80
) : Objective {
var wanderCenter: CobblemonWanderControl.WanderCenter? = null
var fixation: EntityFixation? = null
var leader: PokemonEntity? = null
var ticksUntilMaintainLeader: Int = checkTicks
var remainingPathingCooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Herd"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
entity as PokemonEntity
val moveControl = entity.moveControl as? PokemonMoveControl ?: return ObjectiveStatus.INVALID
if (remainingPathingCooldownTicks > 0) {
remainingPathingCooldownTicks--
}
val level = entity.level() as ServerLevel
if (leader == null && brain.hasMemoryValue(CobblemonMemories.HERD_LEADER)) {
leader = level.getEntity(brain.getMemory(CobblemonMemories.HERD_LEADER).let(UUID::fromString)) as? PokemonEntity
if (leader == null) {
brain.eraseMemory(CobblemonMemories.HERD_LEADER)
}
}
if (ticksUntilMaintainLeader > 0) {
ticksUntilMaintainLeader--
} else if (ticksUntilMaintainLeader == 0) {
if (brain.fixation == null || brain.isFixation(fixation)) {
// Don't maintain the herd leader if we're busy with something else
maintainHerdLeader(entity, brain)
}
ticksUntilMaintainLeader = checkTicks
}
if (leader?.level() != level) {
this.leader = null
}
val leader = leader
if (leader == null && brain.isFixation(fixation)) {
brain.distract(Distraction.FORCE)
}
val wanderControl = brain.getMemory(CobblemonMemories.WANDER_CONTROL)
?: CobblemonWanderControl()
if (this.wanderCenter != null && leader == null) {
if (wanderControl.center == this.wanderCenter) {
wanderControl.center = null
wanderControl.wanderChanceMultiplier = null
brain.setMemory(CobblemonMemories.WANDER_CONTROL, wanderControl)
}
this.wanderCenter = null
} else if (leader != null) {
wanderControl.center = CobblemonWanderControl.WanderCenter(
x = leader.x,
y = leader.y,
z = leader.z,
minRange = 1F,
maxRange = tooFar
)
this.wanderCenter = wanderControl.center
wanderControl.wanderChanceMultiplier = 0.25F
brain.setMemory(CobblemonMemories.WANDER_CONTROL, wanderControl)
}
leader ?: return ObjectiveStatus.INACTIVE
if (brain.isFixation(fixation) && fixation is MovementTrackerFixation) {
return ObjectiveStatus.FIXATED
}
val leaderFixation = leader.biggerBrain.fixation
val canMove = brain.canDistract(comfortDistraction) || brain.isFixation(fixation)
val isMovingCloser = brain.isFixation(fixation) && fixation is LookAndMoveFixation
val leaderMoveControl = leader.moveControl as? PokemonMoveControl ?: return ObjectiveStatus.INVALID
if (leader.distanceTo(entity) > tooFar) {
return when {
isMovingCloser -> ObjectiveStatus.FIXATED // Already have the fixation to move closer
remainingPathingCooldownTicks > 0 -> manageFixation(brain) // Still cooling down from last pathing attempt
!canMove -> ObjectiveStatus.BLOCKED // I'm not able to distract the brain and move closer
else -> tryMovingCloser(entity, brain, level, leader) // let's give it a fair shake then
}
} else if (leader.isFlying() && !entity.isFlying() && !isMovingCloser) {
if (!entity.canFly()) {
entity.brain.eraseMemory(CobblemonMemories.HERD_LEADER) // We can't go where this guy's going
this.leader = null
return ObjectiveStatus.INACTIVE
} else if (!canMove) {
return ObjectiveStatus.BLOCKED
}
return tryMovingCloser(entity, brain, level, leader)
} else if (leaderMoveControl.banking && !isMovingCloser) {
if (!canMove) {
return ObjectiveStatus.BLOCKED
}
if (leader.isInLiquid && !entity.isInLiquid) {
if (remainingPathingCooldownTicks > 0) {
return manageFixation(brain) // Still cooling down from last pathing attempt
}
// We should get into water asap so we can mimic the banking
return tryMovingCloser(entity, brain, level, leader, completionRange = 1)
} else {
removeSleep(entity, brain)
entity.yRot = leader.yRot
moveControl.startBanking(
forwardBlocksPerTick = leaderMoveControl.bankForwardBlocksPerTick,
upwardsBlocksPerTick = leaderMoveControl.bankUpwardsBlocksPerTick,
durationTicks = 2,
rightDegreesPerTick = 0F // Relying on the above yRot = leader.yRot because we dunno when we first started mimicking the banking
)
return ObjectiveStatus.FIXATED
}
} else if (leaderFixation is MovementTrackerFixation && leaderFixation.movementTracker?.lastStatus == MovementStatus.PENDING) {
if (entity.random.nextFloat() > chance) {
return manageFixation(brain) // Not this tick
} else if (!canMove) {
return ObjectiveStatus.BLOCKED
} else if (isMovingCloser) {
return ObjectiveStatus.FIXATED // Already moving
}
val leaderWalkTarget = leaderFixation.movementTracker?.walkTarget ?: return manageFixation(brain)
// We're already closer to the walk target than the leader is, so no need to move. If anything we should get out of the way
if (entity.distanceToSqr(leaderWalkTarget.target.currentPosition()) + closeEnough < leader.distanceToSqr(leaderWalkTarget.target.currentPosition())) {
return manageFixation(brain)
}
// Go to the leader's walk target, roughly.
val walkTarget = CobblemonWalkTarget(
pos = leaderWalkTarget.target.currentPosition().add(getRandomOffset(entity, level)).toBlockPos(),
speedModifier = leaderWalkTarget.speedModifier,
nodeTypeFilter = (leaderWalkTarget as? CobblemonWalkTarget)?.nodeTypeFilter ?: { true },
completionRange = closeEnough.toInt()
)
return tryMovingCloser(entity, brain, level, leader, walkTarget = walkTarget)
} else if (leader.getCurrentPoseType() == PoseType.SLEEP) {
// Leader is sleeping, if I'm drowsy and can sleep here then I will sleep too.
if (entity.canSleepAt(entity.blockPosition().offset(0, -1, 0)) && brain.getMemory(CobblemonMemories.POKEMON_DROWSY) == true) {
if (entity.random.nextFloat() < 1 / 40F) {
applySleep(entity, brain)
}
}
} else if (brain.getMemory(CobblemonMemories.POKEMON_SLEEPING) == true) {
// Leader is awake, so we should be awake too. Maybe.
if (entity.random.nextFloat() < 1 / 15F) {
removeSleep(entity, brain)
}
}
return manageFixation(brain)
}
fun manageFixation(brain: BiggerBrain): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (leader != null) {
return ObjectiveStatus.ACTIVE
} else {
return ObjectiveStatus.INACTIVE
}
}
fun tryMovingCloser(
entity: PokemonEntity,
brain: BiggerBrain,
level: ServerLevel,
leader: PokemonEntity,
walkTarget: WalkTarget? = null,
completionRange: Int = closeEnough.toInt()
): ObjectiveStatus {
val walkTarget = walkTarget ?: CobblemonWalkTarget(
pos = leader.position().add(getRandomOffset(entity, level)).toBlockPos(),
speedModifier = 0.4F,
completionRange = completionRange
)
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
remainingPathingCooldownTicks = pathingCooldownTicks
if (movementTracker == null) {
// Couldn't find a path, wait a bit before trying again
return manageFixation(brain)
} else if (!(brain.isFixation(fixation) && brain.distract(Distraction.FORCE)) && !brain.distract(comfortDistraction)) {
return manageFixation(brain) // Not likely based on checks run on callers to this function.
}
brain.sendDebugMessage("Moving closer, to ${movementTracker.walkTarget.target.currentBlockPosition()}")
removeSleep(entity, brain)
fixation = brain.fixate(
LookAndMoveFixation(
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.COMFORT, DistractionType.FORCE),
lookingTracker = LookingTracker.forTargetEntity(entity, leader, trackEyeHeight = true),
movementTracker = movementTracker,
description = "Moving towards herd leader"
)
)
return ObjectiveStatus.FIXATED
}
fun maintainHerdLeader(entity: PokemonEntity, brain: BiggerBrain) {
val world = entity.level() as ServerLevel
val leader = brain.getMemory(CobblemonMemories.HERD_LEADER)?.let(UUID::fromString).let(world::getEntity) as? PokemonEntity
val currentLeaderDefinition = leader?.let { leader ->
entity.behaviour.herd.toleratedLeaders.find { it.pokemon.matches(leader) }
}
if (leader == null || currentLeaderDefinition == null) {
entity.brain.eraseMemory(CobblemonMemories.HERD_LEADER)
this.leader = null
}
val bestLeader = getBestHerdLeader(
currentLeader = if (leader == null || currentLeaderDefinition == null) null else (leader to currentLeaderDefinition),
nearbyEntities = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return,
entity = entity
)
if (bestLeader != null && bestLeader != leader) {
bestLeader.brain.eraseMemory(CobblemonMemories.HERD_LEADER)
entity.brain.setMemory(CobblemonMemories.HERD_LEADER, bestLeader.uuid.toString())
bestLeader.adjustHerdSize(1)
leader?.adjustHerdSize(-1)
this.leader = bestLeader
}
}
fun getRandomOffset(entity: PokemonEntity, level: ServerLevel): Vec3 {
val leader = leader ?: return Vec3.ZERO
val minRange = closeEnough.toDouble()
val maxRange = (tooFar - closeEnough / 2).toDouble()
val randomDistance = Mth.nextDouble(level.random, minRange, maxRange)
val randomAngle = Mth.nextDouble(level.random, 0.0, 2 * Math.PI)
var offset = Vec3(cos(randomAngle) * randomDistance, 0.0, sin(randomAngle) * randomDistance)
if ((entity.isInLiquid && leader.isInLiquid) || (entity.isFlying() && leader.isFlying())) {
val verticalRange = randomDistance * 0.5
val randomY = Mth.nextDouble(level.random, -verticalRange, verticalRange)
offset = offset.add(0.0, randomY, 0.0)
}
return offset
}
fun applySleep(entity: PokemonEntity, brain: BiggerBrain) {
brain.setMemory(CobblemonMemories.POKEMON_SLEEPING, true)
entity.pokemon.status = PersistentStatusContainer(Statuses.SLEEP)
}
fun removeSleep(entity: PokemonEntity, brain: BiggerBrain) {
if (brain.hasMemoryValue(CobblemonMemories.POKEMON_SLEEPING)) {
brain.eraseMemory(CobblemonMemories.POKEMON_SLEEPING)
val status = entity.pokemon.status
if (status != null && status.status == Statuses.SLEEP) {
entity.pokemon.status = null
}
}
}
/**
* Logic used to choose the best herd leader from nearby visible entities.
*
* - Higher tier leaders are always preferred.
* - Same-tier leaders that are closer are preferred except for when they're the same tier as the current leader.
* - We don't want to exceed the target's herd size limit.
* - We don't want to choose a leader that is themselves following a leader.
* - Some leader definitions allow lower-level Pokémon to lead them.
* - Leaders just have to not be in a party - pastured and wild Pokémon can mingle.
*/
fun getBestHerdLeader(
currentLeader: Pair<PokemonEntity, ToleratedHerdLeader>?,
nearbyEntities: NearestVisibleLivingEntities,
entity: PokemonEntity,
): PokemonEntity? {
var bestLeader: PokemonEntity? = null
val (currentLeaderEntity, currentLeaderDefinition) = currentLeader ?: Pair(null, null)
var bestTier = currentLeaderDefinition?.tier?.let { it + 1 } ?: 0 // Only upgrade to a higher tier leader
var bestDistance = Float.MAX_VALUE
nearbyEntities.findAll {
it is PokemonEntity &&
it != currentLeader &&
it.pokemon.storeCoordinates.get()?.store !is PartyStore &&
it.getHerdSize() < it.behaviour.herd.maxSize &&
!it.brain.hasMemoryValue(CobblemonMemories.POKEMON_DROWSY)
}.forEach { possibleLeader ->
possibleLeader as PokemonEntity
val bestMatchingHerdLeader = entity.behaviour.herd.bestMatchLeader(entity, possibleLeader) ?: return@forEach
val possibleLeaderIsAlreadyALeader = possibleLeader.brain.hasMemoryValue(CobblemonMemories.HERD_SIZE)
val currentLeaderHerdTier = currentLeaderEntity?.getHerdTier() ?: entity.getHerdTier()
if (currentLeaderHerdTier >= bestMatchingHerdLeader.tier) {
return@forEach // This leader is following a leader of a higher tier, we can't replace them
}
val distance = entity.distanceTo(possibleLeader)
if (bestMatchingHerdLeader.tier < bestTier) {
return@forEach // No need to check further if this leader is worse than the best found so far
} else if ((distance > bestDistance && !possibleLeaderIsAlreadyALeader) && bestMatchingHerdLeader.tier == bestTier) {
return@forEach // No need to check further if this leader is farther than the best found so far, unless they are already a leader - I'd prefer to join a pack
} else {
bestLeader = possibleLeader
bestDistance = distance
bestTier = bestMatchingHerdLeader.tier
}
}
return bestLeader ?: currentLeaderEntity
}
class Config : ObjectiveConfig {
// How frequently to check for whether it should herd. Probably isn't that expensive but might use this for chance.
val checkTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
val tooFar: ExpressionOrEntityVariable = Either.left("8".asExpression())
val closeEnough: ExpressionOrEntityVariable = Either.left("4".asExpression())
val chance: ExpressionOrEntityVariable = Either.left("1 / 60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(checkTicks, tooFar, closeEnough, chance).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
behaviourConfigurationContext.addMemories(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
behaviourConfigurationContext.addMemories(CobblemonMemories.HERD_LEADER)
behaviourConfigurationContext.addMemories(CobblemonMemories.HERD_SIZE)
return Herd(
checkTicks = checkTicks.resolveInt(behaviourConfigurationContext.runtime),
tooFar = tooFar.resolveFloat(behaviourConfigurationContext.runtime),
closeEnough = closeEnough.resolveFloat(behaviourConfigurationContext.runtime),
chance = chance.resolveFloat(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,166 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.sounds.SoundEvents
import net.minecraft.tags.FluidTags
import net.minecraft.util.Mth
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.level.material.FluidState
import kotlin.math.atan2
/**
* Swimming Pokemon perform a cool little jump out of the water if they're near the surface
*
*/
class JumpOutOfWater(
val ticksBetweenAttempts: Int = 60,
) : Objective {
var inWater = false
var remainingCooldownTicks = ticksBetweenAttempts
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Jump out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(fixation)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
if (entity.random.nextInt(CHANCE) != 0) {
return ObjectiveStatus.INACTIVE
} else {
if (!brain.distract(idleBoredomDistraction)) return ObjectiveStatus.BLOCKED
val direction = entity.motionDirection
val x = direction.stepX
val z = direction.stepZ
val blockPos = entity.blockPosition()
val offsets = OFFSET_MULTIPLIERS
for (offset in offsets) {
if (!this.isWater(entity, blockPos, x, z, offset) || !this.isAirAbove(entity, blockPos, x, z, offset)) {
return ObjectiveStatus.ACTIVE
}
}
val newVelocity = entity.deltaMovement.add(direction.stepX.toDouble() * 0.6, 0.7, direction.stepZ.toDouble() * 0.6)
entity.deltaMovement = newVelocity
entity.getNavigation().stop()
fixation = brain.fixate(
fixation = JumpOutOfWaterFixation(
this,
movementTracker = null
)
)
}
return ObjectiveStatus.ACTIVE
}
class JumpOutOfWaterFixation(
val objective: JumpOutOfWater,
override val movementTracker: MovementTracker?,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Jumping out of water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val bl: Boolean = objective.inWater
if (!bl) {
val fluidState: FluidState = entity.level().getFluidState(entity.blockPosition())
objective.inWater = fluidState.`is`(FluidTags.WATER)
}
if (objective.inWater && !bl) {
// Transition tick from in water to out of water
entity.playSound(SoundEvents.DOLPHIN_JUMP, 1.0f, 1.0f)
}
val vec3d = entity.deltaMovement
if (vec3d.y * vec3d.y < 0.029999999329447746 && entity.xRot != 0.0f) {
entity.xRot = Mth.rotLerp(0.2f, entity.xRot, 0.0f)
} else if (vec3d.length() > 9.999999747378752E-6) {
val d = vec3d.horizontalDistance()
val e = atan2(-vec3d.y, d) * 57.2957763671875
entity.xRot = e.toFloat()
}
val d: Double = vec3d.y
return (!(d * d < 0.029999999329447746) || entity.xRot == 0.0f || !(Math.abs(entity.xRot) < 10.0f) || !entity.isInWater) && !entity.onGround()
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return JumpOutOfWater(
ticksBetweenAttempts = ticksBetweenAttempts,
)
}
}
private fun isWater(entity: PokemonEntity, pos: BlockPos, offsetX: Int, offsetZ: Int, multiplier: Int): Boolean {
val blockPos = pos.offset(offsetX * multiplier, 0, offsetZ * multiplier)
return entity.level().getFluidState(blockPos).`is`(FluidTags.WATER) && !entity.level().getBlockState(blockPos)
.blocksMotion()
}
private fun isAirAbove(entity: PokemonEntity, pos: BlockPos, offsetX: Int, offsetZ: Int, multiplier: Int): Boolean {
return entity.level().getBlockState(pos.offset(offsetX * multiplier, 1, offsetZ * multiplier))
.isAir && entity.level().getBlockState(pos.offset(offsetX * multiplier, 2, offsetZ * multiplier))
.isAir
}
companion object {
private const val CHANCE = 10
private val OFFSET_MULTIPLIERS = intArrayOf(0, 1, 4, 5, 6, 7)
}
}
@@ -0,0 +1,136 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import kotlin.math.pow
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Randomly looks at nearby entities out of curiosity. Very easily distracted once doing so.
*
* @author Hiroku
* @since December 29th, 2025
*/
class LookAtNearbyEntities(
val maxDistance: Double = 10.0,
val minDuration: Int = 20,
val maxDuration: Int = 80
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Look at nearby entities"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
}
val nearestVisibleLivingEntities = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
?: return ObjectiveStatus.INVALID
val closest = nearestVisibleLivingEntities.findClosest(
{ otherEntity -> otherEntity.distanceToSqr(entity) <= maxDistance.pow(2) && !entity.hasPassenger(otherEntity) }
).orElse(null)
if (closest == null) {
return ObjectiveStatus.INACTIVE
} else {
// Become fixated
fixation = brain.fixate(
IdleLookFixation(
this,
closest,
(minDuration..maxDuration).random()
)
)
return ObjectiveStatus.FIXATED
}
}
class IdleLookFixation(
val objective: LookAtNearbyEntities,
val targetEntity: LivingEntity,
var remainingTicks: Int
) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return "Looking at a nearby entity ($remainingTicks ticks left)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Bro literally anything will distract me
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (targetEntity.isRemoved || entity !is PathfinderMob) {
return false
}
if (lookingTracker == null) {
lookingTracker = LookingTracker(entity, EntityTracker(targetEntity, true))
}
val lookingTracker = lookingTracker!!
remainingTicks--
lookingTracker.tick()
return remainingTicks > 0
}
}
class Config : ObjectiveConfig {
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val minDuration: ExpressionOrEntityVariable = Either.left("20".asExpression())
val maxDuration: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
maxDistance,
minDuration,
maxDuration
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val maxDistance = maxDistance.resolveDouble(behaviourConfigurationContext.runtime)
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val maxDuration = maxDuration.resolveInt(behaviourConfigurationContext.runtime)
return LookAtNearbyEntities(
maxDistance = maxDistance,
minDuration = minDuration,
maxDuration = maxDuration
)
}
}
}
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.OmniPathingEntity
import net.minecraft.world.entity.LivingEntity
class MaintainFluidY : Objective {
override fun getDescription(entity: LivingEntity) = "Maintain Y in fluids"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is OmniPathingEntity) {
return ObjectiveStatus.INVALID
}
val fixation = brain.fixation
if (fixation is MovementTrackerFixation) {
return ObjectiveStatus.BLOCKED
}
if (entity.isFlying()) {
return ObjectiveStatus.INACTIVE
}
if (entity.canSwimInWater() && entity.isUnderWater) {
entity.isNoGravity = true
} else if (entity.canSwimInLava() && entity.isInLava) {
entity.isNoGravity = true
} else {
entity.isNoGravity = false
}
return if (entity.isNoGravity) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
class Config : ObjectiveConfig {
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return emptyList()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return MaintainFluidY()
}
}
}
@@ -0,0 +1,251 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.behavior.BehaviorUtils
import net.minecraft.world.entity.ai.util.RandomPos
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* Tries to path into water if the entity usually avoids land.
* Will pathfind through land even if the entity usually filters out land nodes.
* If water cannot be found in the entity's wander range it'll wander randomly in a spiral-ish pattern
*
* @author JazzMcNade
* @since January 25th, 2026
*/
class MoveIntoWater(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
var wanderDirection: Vec3? = null
var isWanderTurnDirectionClockwise = true
var wanderTurnChance = BASE_TURN_CHANCE
var failCount = 0
override fun getDescription(entity: LivingEntity) = "Move into water if currently out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
}
if (entity.isInWater) {
// All good, nothing to do here
return ObjectiveStatus.INACTIVE
}
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
if (brain.distract(comfortDistraction)) {
val maxDistance = mainThreadRuntime.resolveInt(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val runtime = mainThreadRuntime
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val allowLand = wanderControl?.allowLand
?: runtime.resolveBoolean("(q.entity.movement.can_walk && q.entity.movement.avoids_land) || q.entity.movement.can_fly".asExpression())
val allowAir = wanderControl?.allowAir
?: runtime.resolveBoolean("q.entity.movement.can_fly && !q.entity.movement.can_walk".asExpression())
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir)) {
types.add(WanderType.WATER)
}
if (types.isEmpty()) {
return ObjectiveStatus.INACTIVE
}
var walkTarget: CobblemonWalkTarget? = null
val targetVec3 = BehaviorUtils.getRandomSwimmablePos(entity, 10, 7)
if (targetVec3 != null) {
walkTarget = CobblemonWalkTarget(
BlockPos.containing(targetVec3.x, targetVec3.y, targetVec3.z),
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
}
if (walkTarget == null) {
if (failCount >= 5) {
// No out of water target could be found.
// Need to choose a direction and move as far as possible, hoping we randomly find water
// Totally possible that a shoreline is *just* outside the entity's wander range and
// we choose a direction that's opposite of the shoreline
// To counteract this, the pokemon moves in a (very roughly) spiral pattern outward from the origin
var wanderPosition: BlockPos? = null
if (wanderDirection == null) {
val wanderOffset = RandomPos.generateRandomDirection(entity.level().random, maxDistance / 2, 0)
wanderDirection = wanderOffset.toVec3d().normalize()
isWanderTurnDirectionClockwise = entity.random.nextInt(2) > 0
wanderTurnChance = BASE_TURN_CHANCE
wanderPosition = entity.blockPosition().offset(wanderOffset.x, wanderOffset.y, wanderOffset.z)
} else {
if (entity.level().random.nextFloat() < wanderTurnChance) {
// Turn 30 degrees
wanderDirection =
wanderDirection!!.yRot(Math.PI.toFloat() / 3.0f * if (isWanderTurnDirectionClockwise) -1f else 1f)
wanderTurnChance *= 0.7
}
val wanderVec = entity.position().add(wanderDirection!!.scale(maxDistance.toDouble()))
wanderPosition = BlockPos.containing(wanderVec)
}
val wanderTarget = generateWaterSafePosToward(entity, maxDistance, wanderPosition)
if (wanderTarget != null) {
walkTarget = CobblemonWalkTarget(
wanderPosition,
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
} else {
return ObjectiveStatus.ACTIVE
}
} else {
failCount++
}
}
if (walkTarget != null) {
failCount = 0
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
brain.distract(comfortDistraction)
movementTask = brain.fixate(
fixation = MoveIntoWaterFixation(
movementTracker = movementTracker
)
)
}
}
return ObjectiveStatus.ACTIVE
}
fun generateWaterSafePosToward(
mob: PathfinderMob,
range: Int,
targetPos: BlockPos
): BlockPos? {
for (i in 0..4) {
val candidate: BlockPos? = RandomPos.generateRandomPosTowardDirection(
mob,
range,
mob.level().random,
targetPos
)
if (candidate == null) continue
val pathType = mob.navigation.nodeEvaluator.getPathType(mob, candidate)
// Don't actually care if it can be reached, only if it's not hazardous
if (pathType == PathType.WALKABLE || mob.getPathfindingMalus(pathType) <= 0)
return candidate
}
return null
}
companion object {
val BASE_TURN_CHANCE = 0.8
}
class MoveIntoWaterFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving into water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
if (!entity.isInWater) {
return false
}
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveIntoWater(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,258 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.entity.ai.CobblemonWalkTarget
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.util.LandRandomPos
import net.minecraft.world.entity.ai.util.RandomPos
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.phys.Vec3
/**
* Tries to path out of water if the entity usually water to avoid water.
* Will pathfind through water even if the entity usually filters out water path nodes.
* If land cannot be found in the entity's wander range it'll wander randomly in a spiral-ish pattern
*
* @author JazzMcNade
* @since January 17th, 2026
*/
class MoveOutOfWater(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
var wanderDirection: Vec3? = null
var isWanderTurnDirectionClockwise = true
var wanderTurnChance = BASE_TURN_CHANCE
var failCount = 0
override fun getDescription(entity: LivingEntity) = "Move out of water"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
}
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (!entity.isInWater || entity.isUnderWater) {
// Focus on not drowning first
// TODO: 100% boned if in an underwater cave
return ObjectiveStatus.INACTIVE
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
val maxDistance = mainThreadRuntime.resolveInt(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val runtime = mainThreadRuntime
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val allowLand = wanderControl?.allowLand
?: runtime.resolveBoolean("(q.entity.movement.can_walk && !q.entity.movement.avoids_land) || q.entity.movement.can_fly".asExpression())
val allowAir = wanderControl?.allowAir
?: runtime.resolveBoolean("q.entity.movement.can_fly && !q.entity.movement.can_walk".asExpression())
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir)) {
types.add(WanderType.LAND)
}
if (types.isEmpty()) {
return ObjectiveStatus.INACTIVE
}
if (brain.distract(comfortDistraction)) {
var walkTarget: CobblemonWalkTarget? = null
val targetVec3 = LandRandomPos.getPos(entity, maxDistance, maxDistance)
if (targetVec3 != null) {
walkTarget = CobblemonWalkTarget(
BlockPos.containing(targetVec3.x, targetVec3.y, targetVec3.z),
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
}
if (walkTarget == null) {
if (failCount >= 5) {
// No out of water target black with a malus of 0 could be found.
// Need to choose a direction and move as far as possible, hoping we randomly find land
// Totally possible that a shoreline is *just* outside of the entity's wander range and
// we choose a direction that's opposite of the shoreline
// To counteract this, the pokemon moves in a (very roughly) spiral pattern outward from the origin
var wanderPosition: BlockPos? = null
if (wanderDirection == null) {
val wanderOffset = RandomPos.generateRandomDirection(entity.level().random, maxDistance / 2, 0)
wanderDirection = wanderOffset.toVec3d().normalize()
isWanderTurnDirectionClockwise = entity.random.nextInt(2) > 0
wanderTurnChance = BASE_TURN_CHANCE
wanderPosition = entity.blockPosition().offset(wanderOffset.x, wanderOffset.y, wanderOffset.z)
} else {
if (entity.level().random.nextFloat() < wanderTurnChance) {
// Turn 30 degrees
wanderDirection =
wanderDirection!!.yRot(Math.PI.toFloat() / 3.0f * if (isWanderTurnDirectionClockwise) -1f else 1f)
wanderTurnChance *= 0.7
}
val wanderVec = entity.position().add(wanderDirection!!.scale(maxDistance.toDouble()))
wanderPosition = BlockPos.containing(wanderVec)
}
val wanderTarget = generateWaterSafePosToward(entity, maxDistance, wanderPosition)
if (wanderTarget != null) {
walkTarget = CobblemonWalkTarget(
wanderPosition,
speedMultiplier,
0,
nodeTypeFilter = { nodeType ->
true
}
)
} else {
return ObjectiveStatus.ACTIVE
}
} else {
failCount++
}
}
if (walkTarget != null) {
failCount = 0
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
movementTask = brain.fixate(
fixation = StayOutOfWaterFixation(
movementTracker = movementTracker
)
)
}
}
return ObjectiveStatus.ACTIVE
}
fun generateWaterSafePosToward(
mob: PathfinderMob,
range: Int,
targetPos: BlockPos
): BlockPos? {
for (i in 0..4) {
val candidate: BlockPos? = RandomPos.generateRandomPosTowardDirection(
mob,
range,
mob.level().random,
targetPos
)
if (candidate == null) continue
val pathType = mob.navigation.nodeEvaluator.getPathType(mob, candidate)
// Don't actually care if it can be reached, only if it's not hazardous
if (pathType == PathType.WATER || mob.getPathfindingMalus(pathType) <= 0)
return candidate
}
return null
}
companion object {
const val BASE_TURN_CHANCE = 0.8
}
class StayOutOfWaterFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
var ticksOutOfWater = 0
override fun getDescription(entity: LivingEntity) = "Moving out of water"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Easily distracted once we are no longer touching water.
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
if (entity.isInWater) {
ticksOutOfWater = 0
} else {
ticksOutOfWater++
if (ticksOutOfWater > 20) {
// Made it out of water, job done
return false
}
}
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveOutOfWater(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,166 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.*
import com.cobblemon.mod.common.api.ai.biggerbrain.*
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.*
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.phys.AABB
/**
* Looks for a resting place if the Pokemon is drowsy, and if available paths to it.
*
* @author JazzMcNade
* @since February 3rd, 2026
*/
class MoveToRestingPlace(
val ticksBetweenAttempts: Int = 80,
val horizontalSearchDistance: Expression = "14.0".asExpression(),
val verticalSearchDistance: Expression = "6.0".asExpression(),
val onlyFromStatus: Expression = "false".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var movementTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Moving to a resting place"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
}
brain.getMemory(CobblemonMemories.POKEMON_DROWSY)
?: return ObjectiveStatus.INACTIVE
if (brain.isFixation(movementTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
val hasSleepStatus = entity.pokemon.status?.status === Statuses.SLEEP
if (hasSleepStatus) return ObjectiveStatus.INACTIVE // Already sleeping
if (entity.behaviour.resting.canSleep) {
if (mainThreadRuntime.resolveBoolean(onlyFromStatus)) {
return ObjectiveStatus.BLOCKED
}
if (remainingCooldownTicks > 0 || entity.canSleepAt(entity.blockPosition().below())) {
// Can sleep where we're at, no need to go anywhere
return ObjectiveStatus.INACTIVE
}
val hSearchDistance = mainThreadRuntime.resolveDouble(horizontalSearchDistance)
val vSearchDistance = mainThreadRuntime.resolveDouble(verticalSearchDistance)
val positionList = entity.level()
.getBlockPositions(AABB.ofSize(entity.position(), hSearchDistance, vSearchDistance, hSearchDistance))
.filter(entity::canSleepAt)
val position = if (positionList.isEmpty()) null else positionList.random(1).firstOrNull()
if (position != null && brain.distract(comfortDistraction)) {
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
position,
speedMultiplier,
0
)
)
if (movementTracker != null) {
// Become fixated
movementTask = brain.fixate(
fixation = MoveToRestingPlaceFixation(
movementTracker = movementTracker,
)
)
}
} else {
return ObjectiveStatus.INACTIVE
}
return ObjectiveStatus.ACTIVE
}
return ObjectiveStatus.INACTIVE
}
class MoveToRestingPlaceFixation(
override val movementTracker: MovementTracker,
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving to a resting place"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
val movementStatus = tickMovementFixation()
if (movementStatus == MovementStatus.COMPLETED) return false
return movementStatus != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val horizontalSearchDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val verticalSearchDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
val onlyFromStatus: ExpressionOrEntityVariable = Either.left("false".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
horizontalSearchDistance,
verticalSearchDistance,
speedMultiplier,
onlyFromStatus
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return MoveToRestingPlace(
ticksBetweenAttempts = ticksBetweenAttempts,
horizontalSearchDistance = horizontalSearchDistance.asSimplifiedExpression(entity),
verticalSearchDistance = verticalSearchDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
onlyFromStatus = onlyFromStatus.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,176 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.AttackFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class NeutralBehaviour(
speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
engageRange: Expression = "5.0".asExpression(),
disengageRange: Expression = "20.0".asExpression(),
condition: Expression = "true".asExpression(),
targetCondition: Expression = "true".asExpression(), // target condition (will be checked on entity interaction)
description: Expression = "'Neutral Behaviour'".asExpression(),
private val maxAttackDuration: Expression = "300".asExpression(),
private val retaliationHitCount: Expression = "1".asExpression()
) : EntityResponseObjective(
speedMultiplier = speedMultiplier, // How do we transfer speed to the attack behaviour? Do we want to?
engageRange = engageRange,
disengageRange = disengageRange,
condition = condition, // Self/environment condition check
targetCondition = targetCondition, // target condition (will be checked on entity interaction)
description = description,
) {
private var fixation: EntityFixation? = null
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
if (trackedEntity != null) {
val attackTarget = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
val avoidTarget = brain.getMemory(MemoryModuleType.AVOID_TARGET)
if (attackTarget != null && trackedEntity?.uuid == attackTarget.uuid) {
// Check if we continue
return ObjectiveStatus.ACTIVE
} else if (avoidTarget != null && trackedEntity?.uuid === avoidTarget.uuid) {
// Check if we continue
val runtime = mainThreadRuntime.withQueryValue("entity", (trackedEntity!!).asMostSpecificMoLangValue())
val disengageDistance = runtime.resolveFloat(disengageRange)
if (disengageDistance < entity.distanceTo(trackedEntity!!)) {
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
trackedEntity = null
}
} else {
// Something has overridden us
trackedEntity = null
}
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.HURT_BY_ENTITY
) { value, labels ->
if (value != null) {
// Something just smacked us, see if we should get mad about it.
val livingEntity = value
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
val shouldTarget = runtime.resolveBoolean(condition)
if (shouldTarget && brain.fixation !is AttackFixation) {
brain.setMemory(
MemoryModuleType.ATTACK_TARGET, livingEntity,
runtime.resolveInt(maxAttackDuration).toLong()
)
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
trackedEntity = livingEntity
fixation = brain.fixate(
AttackFixation(
targetEntity = trackedEntity!!,
speedMultiplier = speedMultiplier,
distractionTypes = setOf(DistractionType.FORCE),
availableMoves = getRealTimeMoves(entity)
)
)
}
}
return@subscribe true
}
brain.subscribe(
priority = Priority.LOW,
memory = CobblemonMemories.ATTACK_TARGET_DATA
) { value, labels ->
if (value != null) {
// We smacked them, check if it's time for tactical retreat
val attackData = value
val livingEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET) ?: return@subscribe true
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
if (attackData.hitsLanded >= runtime.resolveInt(retaliationHitCount)) {
// Justice served, carry on
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
brain.eraseMemory(CobblemonMemories.ATTACK_TARGET_DATA)
brain.setMemory(MemoryModuleType.AVOID_TARGET, trackedEntity)
}
}
return@subscribe true
}
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val engageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("false".asExpression())
val maxAttackDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val retaliationHitCount: ExpressionOrEntityVariable = Either.left("1".asExpression())
val description: ExpressionOrEntityVariable = Either.left("'Neutral Behaviour'".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
targetCondition,
engageRange,
disengageRange,
retaliationHitCount,
description
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return NeutralBehaviour(
condition = condition.asSimplifiedExpression(entity),
targetCondition = condition.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
maxAttackDuration = maxAttackDuration.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity),
retaliationHitCount = retaliationHitCount.asSimplifiedExpression(entity),
)
}
}
}
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* An ongoing priority for an entity. Objectives are managed by the [BiggerBrain] system. Objectives can act out
* entirely within their own logic, or they can alter memories or create fixations for the entity to take up its
* entire attention.
*
* @author Hiroku
* @since December 29th, 2025
*/
interface Objective {
companion object {
/**
* The idea behind this is that later objectives may like to know or respect that something impacting wandering
* has taken place.
*/
val OBJECTIVE_TAG_WANDERING = "WANDERING"
}
/** Gets a current description for this objective. This is purely used for the debug overlay. */
fun getDescription(entity: LivingEntity): String
/** Performs this objective's logic for a tick. */
fun perform(entity: LivingEntity, brain: BiggerBrain, activeObjectiveTags: MutableSet<String>): ObjectiveStatus
/** Runs when an objective is added to a [BiggerBrain]. Prime opportunity to register memory subscriptions. */
fun onRegister(entity: LivingEntity, brain: BiggerBrain) {}
}
@@ -0,0 +1,28 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
/**
* The current status of an [Objective]. Used for the debug overlay.
*
* @author Hiroku
* @since December 29th, 2025
*/
enum class ObjectiveStatus {
/** States that this objective owns the current fixation. */
FIXATED,
/** States that the objective's logic is ongoing and not impeded. */
ACTIVE,
/** States that the objective is not performing any meaningful logic right now but isn't actively blocked. */
INACTIVE,
/** States that there are other objectives, fixations, etc. in play which prevents the objective from being performed. */
BLOCKED,
/** States that the objective is not valid and shouldn't have been registered on the entity in the first place, such as when placed on the wrong entity type. */
INVALID
}
@@ -0,0 +1,234 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveDouble
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.sounds.SoundEvents
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.item.ItemStack
import net.minecraft.world.level.GameRules
import kotlin.math.ceil
import kotlin.math.min
/**
* Paths to whatever item entity is marked by NEAREST_VISIBLE_WANTED_ITEM
* Upon reaching the target attempts to place it in held item slot
* held item slot if possible.
* Requires NEARBY_SWEET_BERRY_BUSH memory
*
* @author JazzMcNade
* @since February 8th, 2026
*/
class PickupItem(
val ticksBetweenAttempts: Int = 60,
val maxDistance: Expression = "14.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression(),
val maxReach: Expression = "1.0".asExpression(),
) : Objective {
var collectItemTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Pickup item"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(collectItemTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val itemEntity = entity.biggerBrain.getMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM) ?: return ObjectiveStatus.INACTIVE
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.ACTIVE
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
// See if the item can be picked up without needing to path to it
val success = tryPickupItem(entity, itemEntity)
if (!success) {
// Item is too far away, need to path to it
if (remainingCooldownTicks <= 0 && brain.distract(idleBoredomDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val horizontalHitboxRadius = maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
itemEntity,
speedMultiplier,
min(ceil(horizontalHitboxRadius).toInt() - 1, 1),
)
)
if (movementTracker != null) {
val lookingTracker = LookingTracker(entity = entity, lookTarget = movementTracker.walkTarget.target)
collectItemTask = brain.fixate(
fixation = PickupItemFixation(
objective = this,
itemEntity = itemEntity,
movementTracker = movementTracker,
lookingTracker = lookingTracker,
)
)
}
}
} else {
remainingCooldownTicks = ticksBetweenAttempts
}
return ObjectiveStatus.ACTIVE
}
fun tryPickupItem(entity: PokemonEntity, itemEntity: ItemEntity) : Boolean {
val maxReach = mainThreadRuntime.resolveDouble(maxReach) + maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
if (itemEntity.distanceTo(entity) > maxReach || !entity.hasLineOfSight(itemEntity)) {
return false
}
entity.brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM)
entity.take(itemEntity, 1) // This creates the effect of the item going into the entity along with the item pickup sound
val stack = entity.pokemon.swapHeldItem(itemEntity.item)
if (!stack.isEmpty && !entity.level().isClientSide) {
dropItem(entity, stack)
}
return true
}
class PickupItemFixation(
val objective: PickupItem,
val itemEntity: ItemEntity,
override val movementTracker: MovementTracker,
override val lookingTracker : LookingTracker,
): EntityFixation, MovementTrackerFixation, LookingTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Moving to desired item"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return distraction.isDamage || distraction.isForce || (movementTracker.lastStatus == MovementStatus.COMPLETED && entity.brain.getMemorySafely(
CobblemonMemories.NEARBY_SWEET_BERRY_BUSH).orElse(null) != null)
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
movementTracker.tick()
if (movementTracker.lastStatus == MovementStatus.COMPLETED || movementTracker.lastStatus == MovementStatus.FAILED) {
// May have failed but let's check if we're still close enoug to grab it
val world = entity.level()
if (entity !is PokemonEntity) return false
if (!world.gameRules.getRule(GameRules.RULE_MOBGRIEFING).get()) {
// Not allowed to alter the world
return false
}
if (!itemEntity.isAlive || !entity.pokemon.canDropHeldItem) {
return false
}
val succeeded = objective.tryPickupItem(entity, itemEntity)
if (!succeeded && movementTracker.lastStatus == MovementStatus.FAILED) {
// Cannot reach, give up for a while
entity.brain.setMemoryWithExpiry(CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM, true, 200)
entity.brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM)
}
return false
}
return true
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
maxDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return PickupItem(
ticksBetweenAttempts = ticksBetweenAttempts,
maxDistance = maxDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
companion object {
fun dropItem(entity: Entity, stack: ItemStack) {
val itemEntity = ItemEntity(
entity.level(),
entity.x + entity.lookAngle.x,
entity.y + 1.0,
entity.z + entity.lookAngle.z,
stack
)
itemEntity.setPickUpDelay(40)
itemEntity.setThrower(entity)
entity.playSound(SoundEvents.FOX_SPIT, 1.0f, 1.0f) // TODO: customize this sound?
entity.level().addFreshEntity(itemEntity)
}
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import kotlin.math.pow
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.BlockPosTracker
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.behavior.PositionTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.MemoryStatus
import net.minecraft.world.phys.Vec3
/**
* Randomly points toward spawn. Very easily distracted once doing so.
*
*/
class PointToSpawn(
val minDuration: Int = 20,
val maxDuration: Int = 200
) : Objective {
var fixation: EntityFixation? = null
override fun getDescription(entity: LivingEntity) = "Point towards spawn"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (brain.fixation != null) {
fixation = null
return ObjectiveStatus.BLOCKED
} else if (!entity.brain.checkMemory(MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED)
|| !entity.brain.checkMemory(MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT)
) {
return ObjectiveStatus.BLOCKED
}
val blockPos = Vec3.atCenterOf(entity.level().sharedSpawnPos).with(Direction.Axis.Y, entity.eyeY)
brain.setMemory(
MemoryModuleType.LOOK_TARGET,
BlockPosTracker(blockPos)
)
// Become fixated
fixation = brain.fixate(
IdleLookFixation(
this,
blockPos,
(minDuration..maxDuration).random()
)
)
return ObjectiveStatus.FIXATED
}
class IdleLookFixation(
val objective: PointToSpawn,
val targetPosition: Vec3,
var remainingTicks: Int
) : EntityFixation, LookingTrackerFixation {
override var lookingTracker: LookingTracker? = null
override fun getDescription(entity: LivingEntity): String {
return "Looking at spawn position ($remainingTicks ticks left)"
}
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
return true
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
if (entity !is PathfinderMob) {
return false
}
if (lookingTracker == null) {
lookingTracker = LookingTracker(entity, BlockPosTracker(targetPosition))
}
val lookingTracker = lookingTracker!!
remainingTicks--
lookingTracker.tick()
return remainingTicks > 0
}
}
class Config : ObjectiveConfig {
val minDuration: ExpressionOrEntityVariable = Either.left("20".asExpression())
val maxDuration: ExpressionOrEntityVariable = Either.left("80".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minDuration,
maxDuration
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
val minDuration = minDuration.resolveInt(behaviourConfigurationContext.runtime)
val maxDuration = maxDuration.resolveInt(behaviourConfigurationContext.runtime)
return PointToSpawn(
minDuration = minDuration,
maxDuration = maxDuration
)
}
}
}
@@ -0,0 +1,112 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class SkittishBehaviour(
engageRange: Expression = "5.0".asExpression(),
disengageRange: Expression = "20.0".asExpression(),
condition: Expression = "true".asExpression(),
targetCondition: Expression = "false".asExpression(),
description: Expression = "'Skittish Behaviour'".asExpression(),
) : EntityResponseObjective(
// speedMultiplier = speedMultiplier, // How do we transfer speed to the attack behaviour? Do we want to?
engageRange = engageRange,
disengageRange = disengageRange,
condition = condition, // Self/environment condition check
targetCondition = targetCondition, // target condition (will be checked on entity interaction)
description = description,
) {
private var remainingCooldownTicks = 0
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || !entity.isAlive) return ObjectiveStatus.INVALID
val avoidTarget = brain.getMemory(MemoryModuleType.AVOID_TARGET)
if (trackedEntity != null) {
if (avoidTarget != null && trackedEntity?.uuid === avoidTarget.uuid) {
// Check if we continue
if(!shouldContinue(entity, brain)) {
brain.eraseMemory(MemoryModuleType.AVOID_TARGET)
trackedEntity = null
}
} else {
// Something has overridden us
trackedEntity = null
}
} else {
// Scan visible livingEntities
val targetedEntity = scanForValidTargets(entity, brain)
if (targetedEntity != null) {
trackedEntity = targetedEntity
brain.setMemory(MemoryModuleType.AVOID_TARGET, trackedEntity)
}
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
class Config : ObjectiveConfig {
val engageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("false".asExpression())
val description: ExpressionOrEntityVariable = Either.left("'Skittish Behaviour'".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
targetCondition,
engageRange,
disengageRange,
description,
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return SkittishBehaviour(
condition = condition.asSimplifiedExpression(entity),
targetCondition = targetCondition.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,79 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.booleanVariable
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.config.task.SharedEntityVariables
import com.cobblemon.mod.common.api.ai.numberVariable
import com.cobblemon.mod.common.api.ai.resolveBoolean
import com.cobblemon.mod.common.api.ai.resolveFloat
import net.minecraft.tags.FluidTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
class StayAfloat(
val chance: Float = 0.8F
) : Objective {
override fun getDescription(entity: LivingEntity) = "Stay Afloat"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PathfinderMob) {
return ObjectiveStatus.INVALID
}
val fixation = brain.fixation
if (fixation is MovementTrackerFixation) {
// Ok if movement is in progress then we don't try staying afloat
return ObjectiveStatus.BLOCKED
}
if (entity.isInWater && (entity.getFluidHeight(FluidTags.WATER) > entity.fluidJumpThreshold) ||
(entity.isInLava && !entity.fireImmune())) {
// Cool do something
if (entity.random.nextFloat() < this.chance) {
entity.jumpControl.jump()
}
return ObjectiveStatus.ACTIVE
} else {
return ObjectiveStatus.INACTIVE
}
}
class Config : ObjectiveConfig {
val condition = booleanVariable(SharedEntityVariables.MOVEMENT_CATEGORY, "can_float", true).asExpressible()
val chance = numberVariable(SharedEntityVariables.MOVEMENT_CATEGORY, "float_chance", 0.8F).asExpressible()
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
chance
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): StayAfloat? {
return when {
condition.resolveBoolean(behaviourConfigurationContext.runtime) -> StayAfloat(chance.resolveFloat(behaviourConfigurationContext.runtime))
else -> null
}
}
}
}
@@ -0,0 +1,244 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookingTrackerFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.movement.MovementIntent
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import kotlin.math.abs
import kotlin.math.ceil
import net.minecraft.core.BlockPos
import net.minecraft.util.RandomSource
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.TamableAnimal
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.WalkTarget
import net.minecraft.world.level.pathfinder.PathType
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator
/**
* Keeps track of the owner entity, and if they are in the same world but are too far away, fixates on getting closer.
* If they are extremely far away, will attempt to teleport to them. When walking to the owner, it pauses for a short
* duration after reaching them to look at them. It's cute.
*
* @author Hiroku
* @since December 29th, 2025
*/
class StayNearOwner(
val ticksBetweenAttempts: Int = 60,
val completionRange: Expression = "4.0".asExpression(),
val maxDistance: Expression = "14.0".asExpression(),
val teleportDistance: Expression = "24.0".asExpression(),
val speedMultiplier: Expression = "0.4".asExpression()
) : Objective {
var followTask: EntityFixation? = null
var remainingCooldownTicks = ticksBetweenAttempts
override fun getDescription(entity: LivingEntity) = "Stay near owner"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is TamableAnimal) {
return ObjectiveStatus.INVALID
} else if (brain.isFixation(followTask)) {
remainingCooldownTicks = ticksBetweenAttempts
return ObjectiveStatus.FIXATED
}
val owner = entity.owner ?: return ObjectiveStatus.INVALID
if (owner.level() != entity.level()) {
return ObjectiveStatus.INVALID
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
}
mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val teleportDistance = mainThreadRuntime.resolveFloat(teleportDistance)
val maxDistance = mainThreadRuntime.resolveFloat(maxDistance)
val speedMultiplier = mainThreadRuntime.resolveFloat(speedMultiplier)
val completionRange = mainThreadRuntime.resolveInt(completionRange)
val horizontalHitboxRadius = maxOf(entity.boundingBox.xsize, entity.boundingBox.zsize) / 2
val distance = entity.distanceTo(owner) - horizontalHitboxRadius
if (distance > teleportDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(Distraction.FORCE)) {
remainingCooldownTicks = ticksBetweenAttempts
tryTeleport(entity, owner)
return ObjectiveStatus.ACTIVE
}
return if (remainingCooldownTicks <= 0) ObjectiveStatus.BLOCKED else ObjectiveStatus.ACTIVE
} else if (distance > maxDistance) {
if (remainingCooldownTicks <= 0 && brain.distract(comfortDistraction)) {
remainingCooldownTicks = ticksBetweenAttempts
val movementTracker = RegularMovementTracker.attempt(
entity = entity,
walkTarget = WalkTarget(
owner,
speedMultiplier,
maxOf(completionRange, ceil(horizontalHitboxRadius).toInt()) - 1
),
// Will put up with some discomfort to keep up, but not as much as when chasing something.
policy = TraversalPolicy.forIntent(entity, MovementIntent.COMFORT)
)
if (movementTracker != null) {
followTask = brain.fixate(
fixation = FollowOwnerFixation(
entity = entity,
owner = owner,
teleportDistance = teleportDistance,
movementTracker = movementTracker
)
)
}
}
}
return ObjectiveStatus.ACTIVE
}
private fun tryTeleport(entity: TamableAnimal, owner: Entity): Boolean {
val blockPos = owner.blockPosition()
for (i in 0..9) {
val j = this.getRandomInt(entity.random, -3, 3)
val k = this.getRandomInt(entity.random, -1, 1)
val l = this.getRandomInt(entity.random, -3, 3)
val succeeded = this.tryTeleportTo(entity, owner, blockPos.x + j, blockPos.y + k, blockPos.z + l)
if (succeeded) {
return true
}
}
return false
}
private fun tryTeleportTo(entity: TamableAnimal, owner: Entity, x: Int, y: Int, z: Int): Boolean {
if (abs(x.toDouble() - owner.x) < 2.0 && abs(z - owner.z) < 2.0) {
return false
} else if (!this.canTeleportTo(entity, BlockPos(x, y, z))) {
return false
} else {
entity.moveTo(
x.toDouble() + 0.5, y.toDouble(), z.toDouble() + 0.5,
entity.yRot,
entity.xRot
)
entity.navigation.stop()
return true
}
}
private fun canTeleportTo(entity: TamableAnimal, pos: BlockPos): Boolean {
val pathNodeType = WalkNodeEvaluator.getPathTypeStatic(entity, pos.mutable())
if (pathNodeType != PathType.WALKABLE) {
return false // Could be more complex to support fliers and swimmers
} else {
val blockPos = pos.subtract(entity.blockPosition())
return entity.level().noCollision(entity, entity.boundingBox.move(blockPos))
}
}
private fun getRandomInt(random: RandomSource, min: Int, max: Int) = random.nextInt(max - min + 1) + min
class FollowOwnerFixation(
entity: PathfinderMob,
val owner: LivingEntity,
val teleportDistance: Float,
override val movementTracker: MovementTracker,
): EntityFixation, LookingTrackerFixation, MovementTrackerFixation {
// Look at the owner for some amount of time after reaching them. For cuteness!
var lingeringStareTicks = (20..40).random()
override val lookingTracker: LookingTracker = LookingTracker(entity = entity, lookTarget = EntityTracker(owner, true))
override fun getDescription(entity: LivingEntity) = "Moving to owner"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Easily distracted once we've reached the player.
return distraction.isDamage || distraction.isForce || movementTracker.lastStatus == MovementStatus.COMPLETED
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
lookingTracker.tick()
if (entity.distanceTo(owner) > teleportDistance) {
// Too far away, give up, the teleport will handle it
return false
}
if (movementTracker.lastStatus == MovementStatus.COMPLETED) {
lingeringStareTicks--
return lingeringStareTicks > 0
}
return tickMovementFixation() != MovementStatus.FAILED
}
}
class Config : ObjectiveConfig {
val ticksBetweenAttempts: ExpressionOrEntityVariable = Either.left("60".asExpression())
val completionRange: ExpressionOrEntityVariable = Either.left("4.0".asExpression())
val maxDistance: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
val teleportDistance: ExpressionOrEntityVariable = Either.left("24.0".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
ticksBetweenAttempts,
completionRange,
maxDistance,
teleportDistance,
speedMultiplier
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val ticksBetweenAttempts = ticksBetweenAttempts.resolveInt(behaviourConfigurationContext.runtime)
return StayNearOwner(
ticksBetweenAttempts = ticksBetweenAttempts,
completionRange = completionRange.asSimplifiedExpression(entity),
maxDistance = maxDistance.asSimplifiedExpression(entity),
teleportDistance = teleportDistance.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,257 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.Priority
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.AttackFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndLockFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.resolveString
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import com.sun.jna.Memory
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
class TerritorialBehaviour(
speedMultiplier: Expression = "0.5".asExpression(), // How do we transfer speed to the attack behaviour? Do we want to?
val attackRange: Expression = "3.0".asExpression(),
engageRange: Expression = "10.0".asExpression(),
disengageRange: Expression = "15.0".asExpression(),
condition: Expression = "true".asExpression(), // Self/environment condition check
targetCondition: Expression = "true".asExpression(), // target condition (will be checked on entity interaction)
description: Expression = "'Territorial Behaviour'".asExpression(),
val maxAttackDuration: Expression = "300".asExpression(),
) : EntityResponseObjective(
speedMultiplier = speedMultiplier, // How do we transfer speed to the attack behaviour? Do we want to?
engageRange = engageRange,
disengageRange = disengageRange,
condition = condition, // Self/environment condition check
targetCondition = targetCondition, // target condition (will be checked on entity interaction)
description = description,
) {
private var remainingCooldownTicks = 0
private val objectiveDescription: String = mainThreadRuntime.resolveString(description)
private var cryCooldownTicks = 0
private var proximityAttackCooldown = 0
private var satiationHitCount = 999
private var fixation : EntityFixation? = null
override fun getDescription(entity: LivingEntity) = objectiveDescription
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity || entity.isDeadOrDying) return ObjectiveStatus.INVALID
if (brain.getMemory(MemoryModuleType.AVOID_TARGET) != null) {
return ObjectiveStatus.BLOCKED
}
val attackTarget = brain.getMemory(MemoryModuleType.ATTACK_TARGET)
if (trackedEntity != null) {
if (shouldContinue(entity, brain)) {
// tick behaviour cooldowns
if (proximityAttackCooldown > 0) proximityAttackCooldown--
if (cryCooldownTicks > 0) cryCooldownTicks--
if (attackTarget == null) {
// approach, cry, or fight
val runtime = mainThreadRuntime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
.withQueryValue("target", trackedEntity!!.asMostSpecificMoLangValue())
val distanceToTarget = entity.distanceTo(trackedEntity!!)
val _attackRange = runtime.resolveFloat(attackRange)
if (_attackRange > distanceToTarget && proximityAttackCooldown <= 0) {
// give em a warning shot
val attackDuration = runtime.resolveInt(maxAttackDuration)
satiationHitCount = 1
brain.setMemory(MemoryModuleType.ATTACK_TARGET, trackedEntity, attackDuration.toLong())
fixation = brain.fixate(
AttackFixation(
targetEntity = trackedEntity!!,
speedMultiplier = speedMultiplier,
distractionTypes = setOf(DistractionType.FORCE),
availableMoves = getRealTimeMoves(entity)
)
)
} else {
// be unhappy about it.
if (cryCooldownTicks <= 0) {
entity.cry()
cryCooldownTicks = CRY_COOLDOWN_TICKS + entity.level().random.nextInt(CRY_COOLDOWN_RANDOM_TICKS)
}
if (!brain.isFixation(fixation) && brain.fixation !is LookAndLockFixation) {
if (brain.distract(Distraction.FORCE)) {
fixation = brain.fixate(
LookAndLockFixation(
distractionTypes = setOf(DistractionType.FORCE, DistractionType.DAMAGE),
lookingTracker = LookingTracker.forTargetEntity(entity, trackedEntity!!, trackEyeHeight = true),
condition = { true }
)
)
}
}
}
} else {
if (attackTarget.uuid != trackedEntity?.uuid) {
// Something has overridden us and independently set the attack target
trackedEntity = null
return ObjectiveStatus.BLOCKED
}
}
} else {
trackedEntity = null
}
} else {
// No active target
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
} else {
remainingCooldownTicks = 20
}
val targetEntity = scanForValidTargets(entity, brain)
if (targetEntity != null) {
cryCooldownTicks = 0
proximityAttackCooldown = 0
trackedEntity = targetEntity
}
}
return if (trackedEntity != null) ObjectiveStatus.ACTIVE else ObjectiveStatus.INACTIVE
}
override fun onRegister(entity: LivingEntity, brain: BiggerBrain) {
// TODO: handle conflicts between different behaviours
brain.subscribe(
priority = Priority.LOW,
memory = CobblemonMemories.ATTACK_TARGET_DATA
) { value, labels ->
if (value != null) {
val livingEntity = brain.getMemory(MemoryModuleType.ATTACK_TARGET) ?: return@subscribe true
if (trackedEntity?.uuid == livingEntity.uuid) {
val attackData = value
if (attackData.hitsLanded >= satiationHitCount) {
// Justice served, give the fool a chance to back off
proximityAttackCooldown = PROXIMITY_AGGRO_COOLDOWN_TICKS
brain.eraseMemory(CobblemonMemories.ATTACK_TARGET_DATA)
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
} else {
// We smacked them, refresh our attack timer
val runtime = mainThreadRuntime.withQueryValue("entity", (livingEntity).asMostSpecificMoLangValue())
val attackDuration = runtime.resolveInt(maxAttackDuration)
brain.setMemory(MemoryModuleType.ATTACK_TARGET, livingEntity, attackDuration.toLong())
}
}
}
return@subscribe true
}
brain.subscribe(
priority = Priority.LOW,
memory = MemoryModuleType.HURT_BY_ENTITY
) { value, labels ->
// Of course you know this means war.
if (value != null) {
// Something just smacked us, see if we should get mad about it.
val livingEntity = value
val runtime = mainThreadRuntime.withQueryValue("entity", (entity).asMostSpecificMoLangValue())
.withQueryValue("target", livingEntity.asMostSpecificMoLangValue())
val shouldTarget = runtime.resolveBoolean(condition) && runtime.resolveBoolean(targetCondition)
if (shouldTarget && brain.distract(Distraction.FORCE)) {
brain.setMemory(
MemoryModuleType.ATTACK_TARGET, livingEntity,
runtime.resolveInt(maxAttackDuration).toLong()
)
satiationHitCount = 999
trackedEntity = livingEntity
fixation = brain.fixate(
AttackFixation(
targetEntity = trackedEntity!!,
speedMultiplier = speedMultiplier,
distractionTypes = setOf(DistractionType.FORCE),
availableMoves = getRealTimeMoves(entity)
)
)
}
}
return@subscribe true
}
}
companion object {
val CRY_COOLDOWN_TICKS = 75
val CRY_COOLDOWN_RANDOM_TICKS = 50
val PROXIMITY_AGGRO_COOLDOWN_TICKS = 75
}
class Config : ObjectiveConfig {
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.5".asExpression())
val attackRange: ExpressionOrEntityVariable = Either.left("7.0".asExpression())
val engageRange: ExpressionOrEntityVariable = Either.left("13.0".asExpression())
val disengageRange: ExpressionOrEntityVariable = Either.left("15.0".asExpression())
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val targetCondition: ExpressionOrEntityVariable = Either.left("false".asExpression())
val maxAttackDuration: ExpressionOrEntityVariable = Either.left("300".asExpression())
val description: ExpressionOrEntityVariable = Either.left("'Territorial Behaviour'".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
targetCondition,
speedMultiplier,
attackRange,
engageRange,
disengageRange,
maxAttackDuration,
description
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return TerritorialBehaviour(
condition = condition.asSimplifiedExpression(entity),
targetCondition = targetCondition.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
attackRange = attackRange.asSimplifiedExpression(entity),
engageRange = engageRange.asSimplifiedExpression(entity),
disengageRange = disengageRange.asSimplifiedExpression(entity),
maxAttackDuration = maxAttackDuration.asSimplifiedExpression(entity),
description = description.asSimplifiedExpression(entity)
)
}
}
}
@@ -0,0 +1,224 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementStatus
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.movement.FluidKind
import com.cobblemon.mod.common.api.ai.movement.MovementCapabilities
import com.cobblemon.mod.common.api.ai.movement.Occupancy
import com.cobblemon.mod.common.api.ai.movement.TraversalPolicy
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.ai.OmniPathNavigation
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* Gets the entity out of a fluid that's killing it:
* - A fluid it can neither swim nor breathe in, once its head is under. It sinks, and this looks for a route along the
* bottom to anywhere its head would be above the surface, preferring the route that spends the least time under.
* - Lava, when it isn't fire immune. Everything can swim in lava, so this looks for the quickest way to dry land or,
* failing that, water.
*
* If there's no route, nothing is done about it and the entity drowns or burns. Once a route is found, the entity is
* committed to it: damage and forceful distractions don't interrupt it while it's still in danger.
*
* @author Hiroku
* @since September 30th, 2026
*/
class WalkOutOfWater(
/** How far horizontally to look for somewhere to surface. */
val horizontalRange: Int = 12,
/** How far above the entity to look for somewhere to surface. */
val verticalRange: Int = 12,
/** How many of the closest exits to hand to the pathfinder. More exits make the search slower. */
val maxExits: Int = 48,
val speedMultiplier: Float = 0.4F,
/**
* How many times a route may be searched for while submerged. A search that finds nothing ends the attempt
* outright; extra searches are only for when a found route gets blocked along the way.
*/
val maxSearches: Int = 3,
) : Objective {
var fixation: EntityFixation? = null
/** Searches done since the entity's head last went under. */
var searches = 0
/** Set when a search found no way out. Reset once the entity's head is out of the fluid. */
var gaveUp = false
override fun getDescription(entity: LivingEntity) = when {
gaveUp -> "Escape deadly fluid (no way out)"
else -> "Escape deadly fluid"
}
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PathfinderMob || entity.navigation !is OmniPathNavigation) {
return ObjectiveStatus.INVALID
}
// Cheap check first since this runs every tick for every Pokémon.
val capabilities = if (entity.isInWater || entity.isInLava) MovementCapabilities.of(entity) else null
val danger = capabilities?.let { deadlyFluid(entity, it) } ?: FluidKind.NONE
if (capabilities == null || danger == FluidKind.NONE) {
searches = 0
gaveUp = false
return if (brain.isFixation(fixation)) ObjectiveStatus.FIXATED else ObjectiveStatus.INACTIVE
}
if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED
} else if (gaveUp || searches >= maxSearches) {
return ObjectiveStatus.INACTIVE
} else if (!brain.canDistract(Distraction.FORCE)) {
return ObjectiveStatus.BLOCKED
}
searches++
val navigation = entity.navigation as OmniPathNavigation
val policy = TraversalPolicy.escapeFluid(entity, danger)
val searchRange = horizontalRange * 1.5F + verticalRange
// Dry land first so the escape doesn't end knee-deep, then anywhere else that's safe.
val isDryLand: (Occupancy, FluidKind) -> Boolean = { occupancy, fluid -> occupancy == Occupancy.WALK && fluid == FluidKind.NONE }
val isSafe: (Occupancy, FluidKind) -> Boolean = when (danger) {
// Wading in it is fine since the head's out. Lava is never a way out of water.
FluidKind.LAVA -> { occupancy, fluid -> fluid != FluidKind.LAVA && policy.allows(occupancy, fluid) }
else -> { occupancy, fluid -> occupancy == Occupancy.WADE && fluid == danger }
}
val path = sequenceOf(isDryLand, isSafe)
.map { findExits(entity, capabilities, it) }
.filter { it.isNotEmpty() }
.mapNotNull { navigation.planPath(it, 0, policy, searchRange) }
.firstOrNull { it.canReach() }
if (path == null) {
gaveUp = true
return ObjectiveStatus.INACTIVE
}
val walkTarget = WalkTarget(path.target, speedMultiplier, 0)
val tracker = RegularMovementTracker.following(entity, walkTarget, path, policy)
if (tracker == null) {
gaveUp = true
return ObjectiveStatus.INACTIVE
}
// Only interrupt whatever else was going on once there's actually somewhere to go.
brain.distract(Distraction.FORCE)
fixation = brain.fixate(WalkOutOfWaterFixation(capabilities, tracker))
return ObjectiveStatus.FIXATED
}
/**
* Nearby positions matching [accepts], closest first. Only positions the entity could be in are considered;
* whether they can be reached is left to the pathfinder.
*/
private fun findExits(
entity: PathfinderMob,
capabilities: MovementCapabilities,
accepts: (Occupancy, FluidKind) -> Boolean
): Set<BlockPos> {
val level = entity.level()
val origin = entity.blockPosition()
val exits = mutableListOf<BlockPos>()
// Hardly anything below is useful: the way out of water is up the bank, not into a cave under the bed.
for (pos in BlockPos.betweenClosed(
origin.offset(-horizontalRange, -MAX_EXIT_DEPTH_BELOW, -horizontalRange),
origin.offset(horizontalRange, verticalRange, horizontalRange)
)) {
val occupancy = Occupancy.at(capabilities, entity.eyeHeight, pos, level::getBlockState) ?: continue
if (occupancy.isStandable && accepts(occupancy, FluidKind.of(level.getFluidState(pos)))) {
exits.add(pos.immutable())
}
}
// Closest horizontally so that exits straight overhead (unreachable cliff tops) don't crowd out the shore.
return exits
.sortedBy { (it.x - origin.x) * (it.x - origin.x) + (it.z - origin.z) * (it.z - origin.z) }
.take(maxExits)
.toSet()
}
class WalkOutOfWaterFixation(
private val capabilities: MovementCapabilities,
override val movementTracker: MovementTracker
) : EntityFixation, MovementTrackerFixation {
override fun getDescription(entity: LivingEntity) = "Escaping deadly fluid"
override fun canDistract(distraction: Distraction, entity: LivingEntity): Boolean {
// Nothing is more important than surviving, but once out of danger it's fair game.
return deadlyFluid(entity, capabilities) == FluidKind.NONE
}
override fun onDistract(distraction: Distraction, entity: LivingEntity) {
movementTracker.stop()
}
override fun tick(entity: LivingEntity, brain: BiggerBrain): Boolean {
// Keeps going after surfacing, but by then canDistract lets anything more interesting take over.
return tickMovementFixation() == MovementStatus.PENDING
}
}
class Config : ObjectiveConfig {
val horizontalRange: ExpressionOrEntityVariable = Either.left("12".asExpression())
val verticalRange: ExpressionOrEntityVariable = Either.left("12".asExpression())
val maxExits: ExpressionOrEntityVariable = Either.left("48".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
val maxSearches: ExpressionOrEntityVariable = Either.left("3".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
listOf(horizontalRange, verticalRange, maxExits, speedMultiplier, maxSearches).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Objective {
val runtime = behaviourConfigurationContext.runtime
return WalkOutOfWater(
horizontalRange = horizontalRange.resolveInt(runtime),
verticalRange = verticalRange.resolveInt(runtime),
maxExits = maxExits.resolveInt(runtime),
speedMultiplier = speedMultiplier.resolveFloat(runtime),
maxSearches = maxSearches.resolveInt(runtime)
)
}
}
companion object {
const val MAX_EXIT_DEPTH_BELOW = 2
/** Whether the entity's head is in a fluid it can neither swim nor breathe in. */
fun isDrowningIn(capabilities: MovementCapabilities, headFluid: FluidKind): Boolean {
return headFluid != FluidKind.NONE && !capabilities.canSwimIn(headFluid) && !capabilities.canBreatheIn(headFluid)
}
/** The fluid that's currently killing the entity, or [FluidKind.NONE]. */
fun deadlyFluid(entity: LivingEntity, capabilities: MovementCapabilities): FluidKind {
val headFluid = FluidKind.atEyes(entity)
return when {
isDrowningIn(capabilities, headFluid) -> headFluid
entity.isInLava && capabilities.isHarmedBy(FluidKind.LAVA) -> FluidKind.LAVA
else -> FluidKind.NONE
}
}
}
}
@@ -0,0 +1,127 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.MovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.Distraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.comfortDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.MovementTrackerFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveFloat
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.PoseType
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.entity.pokemon.ai.PokemonMoveControl
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.behavior.EntityTracker
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.WalkTarget
/**
* Walk towards parent of same species objective
*/
class WalkTowardsParent(
val minRange: Int,
val maxRange: Int,
val speed: Float
) : Objective {
var fixation: EntityFixation? = null
var cooldownTicks = 0
override fun getDescription(entity: LivingEntity) = "Following parent species"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (entity !is PokemonEntity) {
return ObjectiveStatus.INVALID // its gotta be a pokemon to have a parent species
} else if (brain.isFixation(fixation)) {
return ObjectiveStatus.FIXATED // we are already fixated on this objectives fixation
} else if (brain.fixation != null) {
fixation = null // our brain has chosen another fixation
}
// Check to see if the cooldown has been completed
// TODO: should cooldown checks happen first? Do we only want them ticked down
if (cooldownTicks > 0) {
cooldownTicks--
return ObjectiveStatus.INACTIVE
}
// if no trusted adult is around then the objective is inactive
val adult = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT) ?: return ObjectiveStatus.INACTIVE
// If we are too close or too far then don't follow
// TODO: the too far doesn't make that much sense to me. We don't want it treating it as a herd?
val dist = entity.distanceTo(adult)
if (dist > maxRange + 1 || dist < minRange) return ObjectiveStatus.INACTIVE
// Can we comfort ourselves?
if (!brain.distract(comfortDistraction)) return ObjectiveStatus.BLOCKED
// Get our walk target and movement tracker
val walkTarget = WalkTarget(EntityTracker(adult, false), speed, minRange - 1)
val movementTracker = RegularMovementTracker.attempt(entity as PathfinderMob, walkTarget)
?: return ObjectiveStatus.INACTIVE
this.fixation = brain.fixate(
LookAndMoveFixation(
description = "Following parent",
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE), // We are very fine to ignore this movement if forced or hurt
lookingTracker = LookingTracker.forTargetEntity(entity, adult),
movementTracker = movementTracker,
onMovementComplete = { _, _ -> cooldownTicks = 60 }
)
)
return ObjectiveStatus.FIXATED // We are now fixated on
}
class Config : ObjectiveConfig {
val minRange: ExpressionOrEntityVariable = Either.left("5".asExpression())
val maxRange: ExpressionOrEntityVariable = Either.left("16".asExpression())
val speed: ExpressionOrEntityVariable = Either.left("0.4".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
minRange,
maxRange,
speed
).asVariables()
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective? {
if (entity !is PokemonEntity) return null
return WalkTowardsParent(
minRange = minRange.resolveInt(behaviourConfigurationContext.runtime),
maxRange = maxRange.resolveInt(behaviourConfigurationContext.runtime),
speed = speed.resolveFloat(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,258 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.objective
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.LookingTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.RegularMovementTracker
import com.cobblemon.mod.common.api.ai.biggerbrain.WanderType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.DistractionType
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.idleBoredomDistraction
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.EntityFixation
import com.cobblemon.mod.common.api.ai.biggerbrain.fixation.LookAndMoveFixation
import com.cobblemon.mod.common.api.ai.config.objective.ObjectiveConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.molang.MoLangFunctions.asMostSpecificMoLangValue
import com.cobblemon.mod.common.api.npc.configuration.MoLangConfigVariable
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.mainThreadRuntime
import com.cobblemon.mod.common.util.resolveBoolean
import com.cobblemon.mod.common.util.resolveFloat
import com.cobblemon.mod.common.util.resolveInt
import com.cobblemon.mod.common.util.withQueryValue
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.WalkTarget
/*
* I've scuffed the hell out of this thing. The logic for what types of wandering to do is unclear, and I haven't
* really decided whether it should be one mega function for finding a wander target and figuring out the type of
* goal in the process or if it should be cleanly separated for each type of wander target. I've done a bit of both
* and it's not pretty.
*/
class WanderAround(
val condition: Expression = "true".asExpression(),
val cooldownTicks: Int = 80,
val allowLand: Expression = "(q.entity.movement.can_walk && !q.entity.movement.avoids_land) || q.entity.movement.can_fly".asExpression(),
val allowWater: Expression = "q.entity.movement.can_swim_in_water && !q.entity.movement.avoids_water".asExpression(),
val allowAir: Expression = "q.entity.movement.can_fly && !q.entity.movement.can_walk".asExpression(),
val wanderChance: Expression = "1/(20*6)".asExpression(),
val horizontalRange: Expression = "10".asExpression(),
val verticalRange: Expression = "5".asExpression(),
val speedMultiplier: Expression = "0.35".asExpression(),
val avoidTargetingAir: Expression = "false".asExpression(),
val minimumHeight: Expression = "0".asExpression(),
val maximumHeight: Expression = "6".asExpression()
) : Objective {
var fixation: EntityFixation? = null
var remainingCooldownTicks = 10
override fun getDescription(entity: LivingEntity) = "Wander around"
override fun perform(
entity: LivingEntity,
brain: BiggerBrain,
activeObjectiveTags: MutableSet<String>
): ObjectiveStatus {
if (brain.isFixation(fixation)) {
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING)
return ObjectiveStatus.FIXATED
} else if (entity !is PathfinderMob) {
return ObjectiveStatus.INVALID
} else if (Objective.OBJECTIVE_TAG_WANDERING in activeObjectiveTags) {
return ObjectiveStatus.BLOCKED
} else if (!brain.canDistract(idleBoredomDistraction)) {
return ObjectiveStatus.BLOCKED
}
fixation = null
val runtime = mainThreadRuntime
runtime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
if (!runtime.resolveBoolean(condition)) {
return ObjectiveStatus.INACTIVE
} else if (Objective.OBJECTIVE_TAG_WANDERING in activeObjectiveTags) {
return ObjectiveStatus.BLOCKED
}
if (remainingCooldownTicks > 0) {
remainingCooldownTicks--
return ObjectiveStatus.INACTIVE
}
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
val wanderChance = runtime.resolveFloat(this.wanderChance) * (wanderControl?.wanderChanceMultiplier ?: 1.0F)
if (wanderChance <= 1.0F && entity.level().random.nextFloat() > wanderChance) {
return ObjectiveStatus.ACTIVE
}
val allowLand = wanderControl?.allowLand ?: runtime.resolveBoolean(allowLand)
val allowWater = wanderControl?.allowWater ?: runtime.resolveBoolean(allowWater)
val allowAir = wanderControl?.allowAir ?: runtime.resolveBoolean(allowAir)
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir) && WanderType.LAND.isValid(entity)) {
types.add(WanderType.LAND)
}
if (allowWater && WanderType.WATER.isValid(entity)) {
types.add(WanderType.WATER)
}
// Seafloor walkers can't swim, so allowWater's default never covers them; only an explicit opt-out stops them.
if (wanderControl?.allowWater != false && WanderType.SEABED.isValid(entity)) {
types.add(WanderType.SEABED)
}
if (types.isEmpty()) {
return ObjectiveStatus.INVALID
}
remainingCooldownTicks = cooldownTicks
val walkTarget = types.firstNotNullOfOrNull {
it.generateWalkTarget(
entity = entity,
horizontalRange = runtime.resolveInt(horizontalRange),
verticalRange = runtime.resolveInt(verticalRange),
minimumHeight = runtime.resolveInt(minimumHeight),
maximumHeight = runtime.resolveInt(maximumHeight),
avoidTargetingAir = runtime.resolveBoolean(avoidTargetingAir),
speedMultiplier = runtime.resolveFloat(speedMultiplier),
center = wanderControl?.center,
maxAttempts = wanderControl?.maxAttempts ?: 4
)
} ?: return ObjectiveStatus.ACTIVE
val movementTracker = RegularMovementTracker.attempt(entity, walkTarget)
?: return ObjectiveStatus.ACTIVE
if (brain.distract(idleBoredomDistraction)) {
movementTracker.tick()
fixation = brain.fixate(
LookAndMoveFixation(
description = "Wandering",
distractionTypes = setOf(DistractionType.DAMAGE, DistractionType.FORCE),
lookingTracker = LookingTracker.fromNavigationPathOrWalkTarget(entity, walkTarget),
movementTracker = movementTracker
)
)
activeObjectiveTags.add(Objective.OBJECTIVE_TAG_WANDERING) // unsure if we need this
return ObjectiveStatus.FIXATED
}
return ObjectiveStatus.BLOCKED
}
class Config : ObjectiveConfig {
val condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
val cooldownTicks: ExpressionOrEntityVariable = Either.left("80".asExpression())
val allowLand: ExpressionOrEntityVariable = Either.left("(q.entity.movement.can_walk && !q.entity.movement.avoids_land) || q.entity.movement.can_fly".asExpression())
val allowWater: ExpressionOrEntityVariable = Either.left("q.entity.movement.can_swim_in_water && !q.entity.movement.avoids_water".asExpression())
val allowAir: ExpressionOrEntityVariable = Either.left("q.entity.movement.can_fly && !q.entity.movement.can_walk".asExpression())
val wanderChance: ExpressionOrEntityVariable = Either.left("1/(20*6)".asExpression())
val horizontalRange: ExpressionOrEntityVariable = Either.left("10".asExpression())
val verticalRange: ExpressionOrEntityVariable = Either.left("5".asExpression())
val speedMultiplier: ExpressionOrEntityVariable = Either.left("0.35".asExpression())
val avoidTargetingAir: ExpressionOrEntityVariable = Either.left("false".asExpression())
val minimumHeight: ExpressionOrEntityVariable = Either.left("0".asExpression())
val maximumHeight: ExpressionOrEntityVariable = Either.left("6".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): List<MoLangConfigVariable> {
return listOf(
condition,
cooldownTicks,
allowLand,
allowWater,
allowAir,
wanderChance,
horizontalRange,
verticalRange,
speedMultiplier,
avoidTargetingAir,
minimumHeight,
maximumHeight
).asVariables()
}
override fun create(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
): Objective {
return WanderAround(
condition = condition.asSimplifiedExpression(entity),
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
allowLand = allowLand.asSimplifiedExpression(entity),
allowWater = allowWater.asSimplifiedExpression(entity),
allowAir = allowAir.asSimplifiedExpression(entity),
wanderChance = wanderChance.asSimplifiedExpression(entity),
horizontalRange = horizontalRange.asSimplifiedExpression(entity),
verticalRange = verticalRange.asSimplifiedExpression(entity),
speedMultiplier = speedMultiplier.asSimplifiedExpression(entity),
avoidTargetingAir = avoidTargetingAir.asSimplifiedExpression(entity),
minimumHeight = minimumHeight.asSimplifiedExpression(entity),
maximumHeight = maximumHeight.asSimplifiedExpression(entity)
)
}
}
companion object {
fun generateWalkTarget(entity: LivingEntity) : WalkTarget? {
if (entity !is PathfinderMob) return null
val runtime = mainThreadRuntime
val wanderControl = entity.brain.getMemorySafely(CobblemonMemories.WANDER_CONTROL).orElse(null)
runtime.withQueryValue("entity", entity.asMostSpecificMoLangValue())
val allowLand = wanderControl?.allowLand ?: runtime.resolveBoolean("(q.entity.movement.can_walk && !q.entity.movement.avoids_land) || q.entity.movement.can_fly".asExpression())
val allowWater = wanderControl?.allowWater ?: runtime.resolveBoolean("q.entity.movement.can_swim_in_water && !q.entity.movement.avoids_water".asExpression())
val allowAir = wanderControl?.allowAir ?: runtime.resolveBoolean("q.entity.movement.can_fly && !q.entity.movement.can_walk".asExpression())
val types = mutableSetOf<WanderType>()
if ((allowLand || allowAir) && WanderType.LAND.isValid(entity)) {
types.add(WanderType.LAND)
}
if (allowWater && WanderType.WATER.isValid(entity)) {
types.add(WanderType.WATER)
}
if (wanderControl?.allowWater != false && WanderType.SEABED.isValid(entity)) {
types.add(WanderType.SEABED)
}
if (types.isEmpty()) {
return null
}
return types.firstNotNullOfOrNull {
it.generateWalkTarget(
entity = entity,
horizontalRange = 10,
verticalRange = 5,
minimumHeight = 0,
maximumHeight = 6,
avoidTargetingAir = false, // runtime.resolveBoolean(avoidTargetingAir),
speedMultiplier = 0.50f,
center = wanderControl?.center,
maxAttempts = wanderControl?.maxAttempts ?: 4
)
}
}
}
}
@@ -0,0 +1,90 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Senses whether the entity is battling or not. Maintains the BATTLING_POKEMON memory.
*
* @author Hiroku
* @since December 29th, 2025
*/
class BattlingPokemonSense(
var cooldownTicks: Int = 2
) : Sense {
override var ticksUntilNextExecution: Int = 10
override val memories: Set<MemoryModuleType<*>> = setOf(CobblemonMemories.BATTLING_POKEMON)
override fun merge(other: Sense): Boolean {
if (other is BattlingPokemonSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
val battles = when (entity) {
is PokemonEntity -> entity.battleId?.let { BattleRegistry.getBattle(it) }?.let { listOf(it) } ?: emptyList()
is NPCEntity -> entity.battleIds.mapNotNull(BattleRegistry::getBattle)
else -> emptyList()
}
val entityUUIDs = if (entity is PokemonEntity) { // Pokemon can look at opponents, never allies
battles.flatMap { battle ->
val actor = battle.getActor(entity)
if (actor != null) {
actor.getSide().getOppositeSide().activePokemon.mapNotNull { it.battlePokemon?.entity?.uuid }
} else {
emptyList()
}
}
} else if (entity is NPCEntity) { // NPCs can look at any of the pokemon in play
battles.flatMap { it.activePokemon }.mapNotNull { it.battlePokemon?.entity?.uuid }
} else {
emptyList()
}
brain.setMemory(CobblemonMemories.BATTLING_POKEMON, entityUUIDs)
if (entityUUIDs.isEmpty() && entity is PokemonEntity) {
brain.eraseMemoryIfPresent(CobblemonMemories.TARGETED_BATTLE_POKEMON)
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return BattlingPokemonSense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,159 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.server.level.ServerLevel
import net.minecraft.tags.PoiTypeTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiRecord
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
class BeeHiveSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = cooldownTicks
override val memories = setOf(
CobblemonMemories.HIVE_LOCATION,
CobblemonMemories.HIVE_BLACKLIST,
)
override fun merge(other: Sense): Boolean {
if (other is BeeHiveSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val world = entity.level() as? ServerLevel ?: return
val brain = entity.brain
val currentHive = brain.getMemory(CobblemonMemories.HIVE_LOCATION).orElse(null)
if (currentHive != null) {
val state = world.getBlockState(currentHive)
if (!isValidHive(state) || !hasReachableAdjacentSide(world, currentHive)) {
brain.eraseMemory(CobblemonMemories.HIVE_LOCATION)
} else {
return // We already have a valid hive, no need to search for another
}
}
var closestHivePos: BlockPos? = null
val list = findNearbyHivesWithSpace(entity)
if (!list.isEmpty()) {
val blackList = brain.getMemory(CobblemonMemories.HIVE_BLACKLIST).orElse(emptyList())
for (blockPos in list) {
if (blackList.contains(blockPos)) continue
if (hasReachableAdjacentSide(world, blockPos)) {
closestHivePos = blockPos
break
}
}
if (closestHivePos == null) {
brain.eraseMemory(CobblemonMemories.HIVE_BLACKLIST)
closestHivePos = list.first()
}
}
if (closestHivePos != null) {
brain.setMemory(CobblemonMemories.HIVE_LOCATION, closestHivePos)
}
}
private fun isValidHive(state: BlockState): Boolean {
return isHiveBlock(state)
}
private fun isHiveBlock(state: BlockState): Boolean {
return state.`is`(Blocks.BEEHIVE) || state.`is`(Blocks.BEE_NEST)
}
private fun hasReachableAdjacentSide(world: ServerLevel, pos: BlockPos): Boolean {
for (dir in Direction.entries) {
val adjacentPos = pos.relative(dir)
if (world.isEmptyBlock(adjacentPos)) {
return true
}
}
return false
}
private fun findNearbyHivesWithSpace(entity: PokemonEntity): List<BlockPos> {
val blockPos = entity.blockPosition()
val poiManager = (entity.level() as ServerLevel).poiManager
val stream = poiManager.getInRange(
{ holder -> holder.`is`(PoiTypeTags.BEE_HOME) },
blockPos,
20,
PoiManager.Occupancy.ANY
)
return stream
.map(PoiRecord::getPos)
.filter { pos -> doesHiveHaveSpace(pos, entity.level()) }
.sorted { pos1, pos2 -> pos1.distSqr(blockPos).toInt() - pos2.distSqr(blockPos).toInt() }
.toList()
}
private fun doesHiveHaveSpace(hivePos: BlockPos, world: Level): Boolean {
val blockEntity: BlockEntity? = world.getBlockEntity(hivePos)
if (blockEntity is BeehiveBlockEntity) {
return !blockEntity.isFull
} else {
return false
}
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return BeeHiveSense(
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,84 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.Mob
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses if there is an entity this enties owner needs defending from
*
* @author Jack
* @since April 12th, 2026
*/
class DefendOwnerSense(
var cooldownTicks: Int = 10
) : Sense {
override var ticksUntilNextExecution = cooldownTicks
override val memories = setOf(CobblemonMemories.NEAREST_VISIBLE_ATTACKER, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is DefendOwnerSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val owner = entity.owner ?: return
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)?.let { visibleMobs ->
setNearestAttacker(entity, visibleMobs, owner, brain)
}
}
private fun setNearestAttacker(entity: PokemonEntity, visibleMobs: NearestVisibleLivingEntities, owner: LivingEntity, brain: BiggerBrain) {
val nearestAttacker = visibleMobs.findClosest { livingEntity ->
if (livingEntity is ServerPlayer) return@findClosest false
if (livingEntity.lastHurtMob == owner) return@findClosest true
if (livingEntity is Mob && livingEntity.target == owner) return@findClosest true
val mobAttackTarget = livingEntity.brain.getMemorySafely(MemoryModuleType.ATTACK_TARGET)
if (mobAttackTarget.isPresent && mobAttackTarget.get() == owner) return@findClosest true
false
}.orElse(null)
if (nearestAttacker != null) {
brain.setMemory(CobblemonMemories.NEAREST_VISIBLE_ATTACKER, nearestAttacker)
} else {
brain.eraseMemoryIfPresent(CobblemonMemories.NEAREST_VISIBLE_ATTACKER)
}
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("10".asExpression())
override fun getVariables(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext) =
DefendOwnerSense(cooldownTicks.resolveInt(behaviourConfigurationContext.runtime))
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Senses when the Pokémon is in a situation that would make it ready to sleep.
* Either by choice (nighttime) or by force (battle/spawning with sleep status)
*
* @author Hiroku
* @since March 23rd, 2024
*/
class DrowsySense(
var cooldownTicks: Int = 20
) : Sense {
override var ticksUntilNextExecution: Int = 20
override val memories = setOf(CobblemonMemories.POKEMON_DROWSY)
override fun merge(other: Sense): Boolean {
if (other is DrowsySense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is PokemonEntity) {
return
}
val world = entity.level()
val rest = entity.behaviour.resting
val isDrowsy = brain.getMemory(CobblemonMemories.POKEMON_DROWSY) ?: false
val hurtLately = brain.hasMemoryValue(MemoryModuleType.HURT_BY)
val shouldBeDrowsy = rest.canSleep && !hurtLately && (world.dayTime.toInt() % 24000) in rest.times && !brain.hasMemoryValue(MemoryModuleType.ANGRY_AT)
val forcedAsleep = entity.pokemon.status?.status == Statuses.SLEEP
if (entity.isBattling) {
if (!isDrowsy && forcedAsleep) {
brain.setMemory(CobblemonMemories.POKEMON_DROWSY, true)
} else if (isDrowsy && !forcedAsleep) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
}
} else {
if (!isDrowsy && shouldBeDrowsy && entity.random.nextFloat() < rest.drowsyChance) {
brain.setMemory(CobblemonMemories.POKEMON_DROWSY, true)
} else if (isDrowsy && !shouldBeDrowsy) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
} else if (isDrowsy && entity.random.nextFloat() < rest.rouseChance) {
brain.eraseMemory(CobblemonMemories.POKEMON_DROWSY)
}
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("20".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return DrowsySense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,190 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonItemComponents
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.block.entity.NestBlockEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.InteractionHand
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.entity.player.Player
class EggSense(
private var cooldownTicks: Int = 100,
private var scanRadius: Double = 20.0
) : Sense {
override var ticksUntilNextExecution: Int = 100
override val memories = setOf(
CobblemonMemories.PATERNAL_NEST_LOCATION,
CobblemonMemories.EGG_IN_NEST,
CobblemonMemories.EGG_LOCATION,
CobblemonMemories.EGG_THIEF,
CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK,
CobblemonMemories.EGG_SEARCH_COUNTDOWN,
MemoryModuleType.ATTACK_TARGET,
MemoryModuleType.ANGRY_AT,
MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES
)
override fun merge(other: Sense): Boolean {
if (other is EggSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.scanRadius = maxOf(this.scanRadius, other.scanRadius)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val level = entity.level() as? ServerLevel ?: return
val nestPos = brain.getMemory(CobblemonMemories.PATERNAL_NEST_LOCATION) ?: return
val blockEntity = level.getBlockEntity(nestPos)
if (blockEntity is NestBlockEntity) {
val nestItem = blockEntity.getItem()
// Egg is in nest
if (!nestItem.isEmpty && nestItem.item.asItem() == CobblemonItems.POKEMON_EGG.asItem()) {
brain.setMemory(CobblemonMemories.EGG_LOCATION, nestPos)
brain.setMemory(CobblemonMemories.EGG_IN_NEST, true)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
return
}
}
// Egg is gone from nest
brain.setMemory(CobblemonMemories.EGG_IN_NEST, false)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
// get item entities nearby that are Eggs
val nearbyEggItems = level.getEntitiesOfClass(ItemEntity::class.java, entity.boundingBox.inflate(scanRadius)) { itemEntity ->
val itemStack = itemEntity.item
if (itemStack.item.asItem() != CobblemonItems.POKEMON_EGG.asItem()) return@getEntitiesOfClass false
val eggComponent = itemStack.get(CobblemonItemComponents.EGG_DATA) ?: return@getEntitiesOfClass false
eggComponent.isParent(entity.pokemon.uuid)
}
if (nearbyEggItems.isNotEmpty()) {
// if the egg is on the ground lets stop being angry and grab it
if (brain.hasMemoryValue(MemoryModuleType.ATTACK_TARGET))
brain.eraseMemory(MemoryModuleType.ATTACK_TARGET)
if (brain.hasMemoryValue(MemoryModuleType.ANGRY_AT))
brain.eraseMemory(MemoryModuleType.ANGRY_AT)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
brain.setMemory(CobblemonMemories.EGG_LOCATION, nearbyEggItems[0].blockPosition())
brain.eraseMemory(CobblemonMemories.EGG_THIEF)
return
}
// see if we have any stored egg thieves in memory
val existingEggThief = brain.getMemory(CobblemonMemories.EGG_THIEF) as? Player
val lastSeenTick = brain.getMemory(CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK)
val currentTick = level.gameTime
// we got a thief here!
if (existingEggThief != null) {
// there the thief is!
if (isPlayerVisible(entity, existingEggThief)) {
brain.setMemory(CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK, currentTick)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
return
}
val lastSeen = lastSeenTick ?: currentTick
// lost track of thief for too long, giving up
if (currentTick - lastSeen > THIEF_LOST_SIGHT_TICKS) {
brain.eraseMemory(CobblemonMemories.EGG_THIEF)
brain.eraseMemory(CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK)
} else {
// dont see the thief
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
return
}
}
// when looking for the egg and it is seen in the hand of a nearby player mark them as the thief
val heldEggThief = findVisiblePlayerHoldingEgg(entity, brain)
if (heldEggThief != null) {
brain.setMemory(CobblemonMemories.EGG_THIEF, heldEggThief)
brain.setMemory(CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK, currentTick)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN)
} else {
// start search timer with no egg or player holding the egg in sight
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_THIEF)
brain.eraseMemory(CobblemonMemories.EGG_THIEF_LAST_SEEN_TICK)
if (!brain.hasMemoryValue(CobblemonMemories.EGG_SEARCH_COUNTDOWN)) {
brain.setMemory(CobblemonMemories.EGG_SEARCH_COUNTDOWN, true, EGG_SEARCH_TIME)
}
}
}
// todo we might want to have each mate report to the other if a thief is found
private fun isPlayerVisible(entity: LivingEntity, player: Player): Boolean {
return entity.hasLineOfSight(player) && !player.isInvisible
}
private fun findVisiblePlayerHoldingEgg(entity: PokemonEntity, brain: BiggerBrain): Player? {
val visible = brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES) ?: return null
return visible.findAll { it is Player && !it.isSpectator && !it.isCreative && isHoldingEggOf(it, entity) }
.filterIsInstance<Player>()
.firstOrNull()
}
// todo if we have pokemon that can steal eggs from nests we may want to make this work on PokemonEntity too not just players
private fun isHoldingEggOf(player: Player, entity: PokemonEntity): Boolean {
return listOf(InteractionHand.MAIN_HAND, InteractionHand.OFF_HAND).any { hand ->
val stack = player.getItemInHand(hand)
stack.item.asItem() == CobblemonItems.POKEMON_EGG.asItem() &&
stack.get(CobblemonItemComponents.EGG_DATA)?.isParent(entity.pokemon.uuid) == true
}
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("100".asExpression())
var scanRadius: ExpressionOrEntityVariable = Either.left("20.0".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks, scanRadius).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return EggSense(
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
scanRadius = scanRadius.resolveDouble(behaviourConfigurationContext.runtime)
)
}
}
companion object {
private const val EGG_SEARCH_TIME = 2400L
private const val THIEF_LOST_SIGHT_TICKS = 1200L
}
}
@@ -0,0 +1,134 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.distanceTo
import com.cobblemon.mod.common.util.getMemorySafely
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.core.Vec3i
import net.minecraft.server.level.ServerLevel
import net.minecraft.tags.BlockTags
import net.minecraft.tags.PoiTypeTags
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiRecord
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.DoublePlantBlock
import net.minecraft.world.level.block.entity.BeehiveBlockEntity
import net.minecraft.world.level.block.entity.BlockEntity
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf
class FlowerSense(
private var cooldownTicks: Int = SCAN_INTERVAL
) : Sense {
override var ticksUntilNextExecution: Int = cooldownTicks
override val memories = setOf(
CobblemonMemories.NEARBY_FLOWER,
CobblemonMemories.HAS_NECTAR,
)
override fun merge(other: Sense): Boolean {
if (other is FlowerSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
val brain = entity.brain
val world = entity.level()
// Check curr memory
val currPos = brain.getMemorySafely(CobblemonMemories.NEARBY_FLOWER).orElse(null)
if (currPos != null && isFlower(entity.level().getBlockState(currPos)) && entity.distanceTo(currPos) <= 32) {
return
}
val searchRadius = 5
val centerPos = entity.blockPosition()
var flowerPos: BlockPos? = null
var shortestDist = Double.MAX_VALUE
BlockPos.betweenClosedStream(
centerPos.offset(-searchRadius, -2, -searchRadius),
centerPos.offset(searchRadius, 2, searchRadius)
).forEach { pos ->
val state = world.getBlockState(pos)
if (isFlower(state)) {
val distance = pos.distSqr(Vec3i(centerPos.x, centerPos.y, centerPos.z))
if (distance < shortestDist) {
flowerPos = BlockPos(pos)
shortestDist = distance
}
}
}
if (flowerPos != null) {
brain.setMemory(CobblemonMemories.NEARBY_FLOWER, flowerPos)
} else {
brain.eraseMemory(CobblemonMemories.NEARBY_FLOWER)
}
}
private fun isFlower(state: BlockState): Boolean {
// Borrowed from Bee.class
if (state.hasProperty(BlockStateProperties.WATERLOGGED) && state.getValue(
BlockStateProperties.WATERLOGGED
) as Boolean
) {
return false
} else if (state.`is`(BlockTags.FLOWERS)) {
if (state.`is`(Blocks.SUNFLOWER)) {
return state.getValue(DoublePlantBlock.HALF) == DoubleBlockHalf.UPPER
} else {
return true
}
} else {
return false
}
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return FlowerSense(
cooldownTicks = cooldownTicks
)
}
}
companion object {
const val SCAN_INTERVAL = 40
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.biggerbrain.distraction.HurtDistraction
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
/**
* Maintains memory of the last entity that hurt this entity.
*
* @author Hiroku
* @since December 29th, 2025
*/
class HurtBySense(
var cooldownTicks: Int = 2
) : Sense {
var lastDamageSource: DamageSource? = null
override var ticksUntilNextExecution: Int = 1
override val memories = setOf(MemoryModuleType.HURT_BY, MemoryModuleType.HURT_BY_ENTITY)
override fun merge(other: Sense): Boolean {
if (other is HurtBySense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
val damageSource = entity.lastDamageSource
if (damageSource === lastDamageSource) {
ticksUntilNextExecution = cooldownTicks
return
}
if (damageSource != null) {
brain.setMemory(MemoryModuleType.HURT_BY, entity.lastDamageSource)
val attacker = damageSource.entity
if (attacker is LivingEntity) {
brain.setMemory(MemoryModuleType.HURT_BY_ENTITY, attacker)
}
} else {
brain.eraseMemoryIfPresent(MemoryModuleType.HURT_BY)
}
// so apparently it remembers the entity that hurt them even if it was forever ago? fair enough I guess. that's vanilla for you.
brain.getMemory(MemoryModuleType.HURT_BY_ENTITY)?.let { livingEntity ->
if (!livingEntity.isAlive || livingEntity.level() != entity.level()) {
brain.eraseMemory(MemoryModuleType.HURT_BY_ENTITY)
}
}
if (damageSource != null && lastDamageSource !== damageSource) {
lastDamageSource = damageSource
brain.distract(HurtDistraction(damageSource))
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return HurtBySense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,206 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.nest.WildNestType
import com.cobblemon.mod.common.api.nest.WildNestTypes
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.level.block.Blocks
import kotlin.jvm.optionals.getOrNull
class IdealNestPlacementSense(
private var cooldownTicks: Int = 100,
private var detectionRadius: Int = 10,
private var minNestDistance: Int = 10,
private var playerClearance: Int = 24
) : Sense {
override var ticksUntilNextExecution: Int = 100
override val memories = setOf(
CobblemonMemories.IDEAL_NEST_LOCATION,
CobblemonMemories.POTENTIAL_MATE
)
override fun merge(other: Sense): Boolean {
if (other is IdealNestPlacementSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.detectionRadius = maxOf(this.detectionRadius, other.detectionRadius)
this.minNestDistance = maxOf(this.minNestDistance, other.minNestDistance)
this.playerClearance = maxOf(this.playerClearance, other.playerClearance)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
// wild mons should be the only ones able to build nests
if (!entity.pokemon.isWild()) return
val world = entity.level() as? ServerLevel ?: return
val mate = brain.getMemory(CobblemonMemories.POTENTIAL_MATE) as? PokemonEntity
val combinedTypes = mate?.let { WildNestTypes.combinedTypes(entity, it) } ?: emptyList()
if (mate == null || combinedTypes.isEmpty()) {
debug(brain, "No mate or no combined nest types; clearing ideal nest memories.")
brain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
mate?.biggerBrain?.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
return
}
val storedNestPos = brain.getMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
if (storedNestPos != null) {
if (isValidNestPlacement(world, entity, mate, storedNestPos, combinedTypes)) {
debug(brain, "Stored ideal nest still valid at $storedNestPos.")
mate.biggerBrain.setMemory(CobblemonMemories.IDEAL_NEST_LOCATION, storedNestPos)
return
} else {
debug(brain, "Stored ideal nest invalid at $storedNestPos; clearing.")
brain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
mate.biggerBrain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
}
}
val entityPos = entity.blockPosition()
val validNestPosition = findValidNestPlacement(world, entity, mate, entityPos, combinedTypes)
if (validNestPosition != null) {
debug(brain, "Found ideal nest position at $validNestPosition.")
brain.setMemory(CobblemonMemories.IDEAL_NEST_LOCATION, validNestPosition)
mate.biggerBrain.setMemory(CobblemonMemories.IDEAL_NEST_LOCATION, validNestPosition)
} else {
debug(brain, "No valid ideal nest position found.")
brain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
mate.biggerBrain.eraseMemory(CobblemonMemories.IDEAL_NEST_LOCATION)
}
}
private fun findValidNestPlacement(world: ServerLevel, entity: PokemonEntity, mate: PokemonEntity?, entityPos: BlockPos, sharedTypes: List<WildNestType>): BlockPos? {
return BlockPos.betweenClosed(
entityPos.offset(-detectionRadius, -5, -detectionRadius),
entityPos.offset(detectionRadius, 5, detectionRadius)
).map { it.immutable() }.shuffled().firstOrNull { pos ->
val blockBelowState = world.getBlockState(pos)
val nestPos = pos.above()
val blockAbove = world.getBlockState(nestPos).block
val blockAbove2 = world.getBlockState(nestPos.above()).block
val placement = WildNestTypes.resolvePlacement(sharedTypes, blockBelowState, world.getFluidState(nestPos)) ?: return@firstOrNull false
if (!isWaterGroupCompatible(entity, mate, placement.waterlogged)) return@firstOrNull false
if (placement.waterlogged) {
if (!(blockAbove == Blocks.WATER && blockAbove2 == Blocks.WATER)) return@firstOrNull false
} else {
if (!(blockAbove == Blocks.AIR && blockAbove2 == Blocks.AIR)) return@firstOrNull false
}
if (isNearExistingNest(world, nestPos)) return@firstOrNull false
// wild mons kept making nests near players so we should make sure there are no players nearby lol
if (world.getNearestPlayer(nestPos.x + 0.5, nestPos.y.toDouble(), nestPos.z + 0.5, playerClearance.toDouble(), true) != null) return@firstOrNull false
if (!canPathfindToTarget(entity, nestPos)) return@firstOrNull false
return@firstOrNull true
}?.above()
}
private fun isValidNestPlacement(world: ServerLevel, entity: PokemonEntity, mate: PokemonEntity?, pos: BlockPos, sharedTypes: List<WildNestType>): Boolean {
val blockBelowState = world.getBlockState(pos.below())
val blockAbove = world.getBlockState(pos.above()).block
val blockAbove2 = world.getBlockState(pos.above(2)).block
val placement = WildNestTypes.resolvePlacement(sharedTypes, blockBelowState, world.getFluidState(pos)) ?: return false
if (!isWaterGroupCompatible(entity, mate, placement.waterlogged)) return false
if (placement.waterlogged) {
if (!(blockAbove == Blocks.WATER && blockAbove2 == Blocks.WATER)) return false
} else {
if (!(blockAbove == Blocks.AIR && blockAbove2 == Blocks.AIR)) return false
}
if (isNearExistingNest(world, pos)) return false
// not a valid spot if it is near a player
if (world.getNearestPlayer(pos.x + 0.5, pos.y.toDouble(), pos.z + 0.5, playerClearance.toDouble(), true) != null) return false
if (!canPathfindToTarget(entity, pos)) return false
return true
}
private fun canPathfindToTarget(entity: PathfinderMob, targetPos: BlockPos): Boolean {
val path = entity.navigation.createPath(targetPos, 0)
return path != null && path.distToTarget < 1.75f
}
private fun isNearExistingNest(world: ServerLevel, pos: BlockPos): Boolean {
return BlockPos.betweenClosed(
pos.offset(-minNestDistance, -minNestDistance, -minNestDistance),
pos.offset(minNestDistance, minNestDistance, minNestDistance)
).any { checkPos ->
world.getBlockEntity(checkPos) is com.cobblemon.mod.common.block.entity.NestBlockEntity
}
}
private fun isWaterGroupCompatible(
entity: PokemonEntity,
mate: PokemonEntity?,
isNestWaterlogged: Boolean
): Boolean {
val waterEggGroups = setOf("water_1", "water_2", "water_3")
val entityEggGroups = entity.pokemon.species.eggGroups.map { it.name.lowercase() }
val entityHasWater = entityEggGroups.any { it in waterEggGroups || it == "ditto" }
val entityOnlyWater = entityEggGroups.all { it in waterEggGroups }
val mateEggGroups = mate?.pokemon?.species?.eggGroups?.map { it.name.lowercase() } ?: emptyList()
val mateHasWater = mateEggGroups.any { it in waterEggGroups || it == "ditto" }
val mateOnlyWater = mateEggGroups.isNotEmpty() && mateEggGroups.all { it in waterEggGroups }
return if (isNestWaterlogged) {
entityHasWater && mateHasWater
} else {
!(entityOnlyWater || mateOnlyWater)
}
}
private fun debug(brain: BiggerBrain, message: String) {
brain.sendDebugMessage("[IdealNestPlacementSense] $message")
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("100".asExpression())
var detectionRadius: ExpressionOrEntityVariable = Either.left("10".asExpression())
var minNestDistance: ExpressionOrEntityVariable = Either.left("10".asExpression())
var playerClearance: ExpressionOrEntityVariable = Either.left("24".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks, detectionRadius, minNestDistance, playerClearance).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return IdealNestPlacementSense(
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
detectionRadius = detectionRadius.resolveInt(behaviourConfigurationContext.runtime),
minNestDistance = minNestDistance.resolveInt(behaviourConfigurationContext.runtime),
playerClearance = playerClearance.resolveInt(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonPoiTypes
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.net.messages.client.animation.PlayPosableAnimationPacket
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.core.Holder
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.village.poi.PoiManager
import net.minecraft.world.entity.ai.village.poi.PoiType
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.entity.JukeboxBlockEntity
/**
* Senses nearby jukeboxes that are currently playing music.
*
*/
class JukeboxSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories = setOf(MemoryModuleType.DANCING)
override fun merge(other: Sense): Boolean {
if (other is JukeboxSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (!brain.runtime.resolveBoolean(condition)) {
return
}
val world = entity.level()
val poiManager = (entity.level() as ServerLevel).poiManager
val jukeboxPositions = poiManager.findAll(
{ holder: Holder<PoiType> -> holder.`is`(CobblemonPoiTypes.JUKEBOX_KEY) },
{ true },
entity.blockPosition(),
10,
PoiManager.Occupancy.ANY
).toList()
val jukeboxPos = jukeboxPositions.firstOrNull() { blockPos ->
if (world.getBlockState(blockPos).block != Blocks.JUKEBOX) return@firstOrNull false
val blockEntity = world.getBlockEntity(blockPos)
if (blockEntity !is JukeboxBlockEntity) return@firstOrNull false
!blockEntity.theItem.isEmpty
}
brain.setMemory(MemoryModuleType.DANCING, jukeboxPos != null)
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return JukeboxSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
}
@@ -0,0 +1,126 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.breeding.CobblemonBreeding
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.phys.AABB
class MateSense(
private var cooldownTicks: Int = 1200,
private var detectionRadius: Double = 10.0
) : Sense {
override var ticksUntilNextExecution: Int = 1200
override val memories = setOf(
CobblemonMemories.POTENTIAL_MATE,
CobblemonMemories.MATE_SCAN_COOLDOWN,
CobblemonMemories.PATERNAL_NEST_LOCATION
)
override fun merge(other: Sense): Boolean {
if (other is MateSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.detectionRadius = maxOf(this.detectionRadius, other.detectionRadius)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
if (brain.getMemory(CobblemonMemories.PATERNAL_NEST_LOCATION) != null) {
return
}
if (brain.getMemory(CobblemonMemories.MATE_SCAN_COOLDOWN) == true) {
return
}
brain.eraseMemory(CobblemonMemories.POTENTIAL_MATE)
if (entity.pokemon.breedingCooldown != 0) return
val world = entity.level() as? ServerLevel ?: return
// it has been an issue that wild mons breed so much and pasture mons not enough so we should have a config for tweaking rates of both
val chance = if (entity.pokemon.isWild()) Cobblemon.config.wildBreedingChance else Cobblemon.config.pastureBreedingChance
if (entity.random.nextDouble() >= chance) {
brain.setMemory(CobblemonMemories.MATE_SCAN_COOLDOWN, true, MATE_SCAN_COOLDOWN)
return
}
val potentialMate = world.getEntitiesOfClass(
PokemonEntity::class.java,
AABB(entity.blockPosition()).inflate(detectionRadius)
) { nearbyEntity ->
nearbyEntity != entity && isValidMate(entity, nearbyEntity)
}.firstOrNull()
brain.setMemory(CobblemonMemories.MATE_SCAN_COOLDOWN, true, MATE_SCAN_COOLDOWN)
if (potentialMate != null) {
brain.setMemory(CobblemonMemories.POTENTIAL_MATE, potentialMate)
potentialMate.biggerBrain.setMemory(CobblemonMemories.POTENTIAL_MATE, entity)
potentialMate.biggerBrain.setMemory(CobblemonMemories.MATE_SCAN_COOLDOWN, true, MATE_SCAN_COOLDOWN)
} else {
brain.eraseMemory(CobblemonMemories.POTENTIAL_MATE)
}
}
private fun isValidMate(entity: PokemonEntity, mate: PokemonEntity): Boolean {
if (entity.isBattling || entity.isBattleClone() || (!entity.pokemon.isWild() && entity.tethering?.tetheringId == null)) return false
if (mate.pokemon.breedingCooldown != 0) return false
val canBreed = CobblemonBreeding.getMother(entity.pokemon, mate.pokemon, isSimulated = true) != null
if (!canBreed) return false
val isCompatible = CobblemonBreeding.checkCompatibility(entity.pokemon, mate.pokemon)
val bothWild = (entity.pokemon.isWild() && mate.pokemon.isWild())
val bothOwned = (!entity.pokemon.isWild() && !mate.pokemon.isWild())
val mateHasMate = mate.biggerBrain.getMemory(CobblemonMemories.POTENTIAL_MATE) != null
return !mateHasMate && isCompatible && (bothWild || bothOwned)
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("1200".asExpression())
var detectionRadius: ExpressionOrEntityVariable = Either.left("10.0".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks, detectionRadius).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return MateSense(
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
detectionRadius = detectionRadius.resolveDouble(behaviourConfigurationContext.runtime)
)
}
}
companion object {
private const val MATE_SCAN_COOLDOWN = 1200L
}
}
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.npc.NPCEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
/**
* A sense that checks if an NPC is currently in a battle. Maintains the NPC_BATTLING memory.
*
* @author Hiroku
* @since December 29th, 2025
*/
class NPCBattlingSense(
var cooldownTicks: Int = 10
) : Sense {
override var ticksUntilNextExecution: Int = 20
override val memories = setOf(CobblemonMemories.NPC_BATTLING)
override fun merge(other: Sense): Boolean {
if (other is NPCBattlingSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
if (entity !is NPCEntity) {
return // Surely they didn't put this on a non-NPC
}
val isBattling = entity.isInBattle()
if (isBattling) {
brain.setMemoryIfChanged(CobblemonMemories.NPC_BATTLING, value = true)
} else {
brain.eraseMemoryIfPresent(CobblemonMemories.NPC_BATTLING)
}
ticksUntilNextExecution = cooldownTicks
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("2".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return NPCBattlingSense(cooldownTicks = cooldownTicks)
}
}
}
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import java.util.function.Predicate
import java.util.function.ToDoubleFunction
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses nearby entities. Maintains the NEAREST_LIVING_ENTITIES and NEAREST_VISIBLE_LIVING_ENTITIES memories.
*
* @author Hiroku
* @since December 29th, 2025
*/
class NearbyEntitiesSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories = setOf(MemoryModuleType.NEAREST_LIVING_ENTITIES, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is NearbyEntitiesSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (!brain.runtime.resolveBoolean(condition)) {
return
}
val level = entity.level()
val aABB = entity.boundingBox.inflate(radiusXZ, radiusY, radiusXZ)
val list = level.getEntitiesOfClass(LivingEntity::class.java, aABB, Predicate { it !== entity && it!!.isAlive })
list.sortWith(Comparator.comparingDouble(ToDoubleFunction { it.distanceToSqr(entity) }))
brain.setMemory(MemoryModuleType.NEAREST_LIVING_ENTITIES, list)
brain.setMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES, NearestVisibleLivingEntities(entity, list))
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return NearbyEntitiesSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
}
@@ -0,0 +1,229 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.api.nest.WildNestType
import com.cobblemon.mod.common.api.nest.WildNestTypes
import com.cobblemon.mod.common.block.WildNestBlock
import com.cobblemon.mod.common.block.entity.NestBlockEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.mojang.datafixers.util.Either
import net.minecraft.core.BlockPos
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.PathfinderMob
import net.minecraft.world.level.block.entity.BlockEntity
class NestSense(
private var cooldownTicks: Int = 200,
private var radiusXZ: Int = 20,
private var radiusY: Int = 5
) : Sense {
override var ticksUntilNextExecution: Int = 200
override val memories = setOf(
CobblemonMemories.NEST_LOCATION,
CobblemonMemories.PATERNAL_NEST_LOCATION,
CobblemonMemories.EGG_IN_NEST,
CobblemonMemories.EGG_LOCATION,
CobblemonMemories.NEST_DESPAWN_IMMUNE_UNTIL_TICK
)
override fun merge(other: Sense): Boolean {
if (other is NestSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = maxOf(this.radiusXZ, other.radiusXZ)
this.radiusY = maxOf(this.radiusY, other.radiusY)
return true
}
return false
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity) return
val world = entity.level() as? ServerLevel ?: return
val paternalNestLocation = brain.getMemory(CobblemonMemories.PATERNAL_NEST_LOCATION)
// early memory check so we can end early
if (paternalNestLocation != null) {
// end early if the nest itself isnt loaded in
if (!world.isLoaded(paternalNestLocation)) {
return
}
// check to make sure there is a nest still at that spot
val blockAtLocation = world.getBlockEntity(paternalNestLocation)
if (blockAtLocation !is NestBlockEntity) { // nest is gone so we kill all nest and egg memories
brain.eraseMemory(CobblemonMemories.PATERNAL_NEST_LOCATION)
brain.eraseMemory(CobblemonMemories.EGG_IN_NEST)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
} else if (blockAtLocation.parents.first == entity.uuid || blockAtLocation.parents.second == entity.uuid) {
// is the pokemon one of the parents of this nest? Yes? Sick let's remember that. We might want to check memories beforehand though so we don't need to set memories each time? idk todo look into
brain.setMemory(CobblemonMemories.PATERNAL_NEST_LOCATION, paternalNestLocation)
brain.setMemory(CobblemonMemories.NEST_LOCATION, paternalNestLocation)
// does our nest have an egg todo we should maybe also check that not just any egg is in the nest but if it is trhe egg of the parents (check uuid of the egg components later)
if (blockAtLocation.getItem().isEmpty) {
brain.setMemory(CobblemonMemories.EGG_IN_NEST, false)
} else {
brain.setMemory(CobblemonMemories.EGG_IN_NEST, true)
}
return
} else { // no longer parents of the nest clear
brain.eraseMemory(CobblemonMemories.PATERNAL_NEST_LOCATION)
brain.setMemory(CobblemonMemories.EGG_IN_NEST, false)
brain.eraseMemory(CobblemonMemories.EGG_LOCATION)
}
}
val nearbyNest = findNearbyNest(entity, brain, world, entity.blockPosition())
if (nearbyNest != null) {
brain.setMemory(CobblemonMemories.NEST_LOCATION, nearbyNest)
} else {
brain.eraseMemory(CobblemonMemories.NEST_LOCATION)
}
}
private fun findNearbyNest(pokemonEntity: PokemonEntity, brain: BiggerBrain, world: ServerLevel, entityPos: BlockPos): BlockPos? {
return BlockPos.betweenClosed(
entityPos.offset(-radiusXZ, -radiusY, -radiusXZ),
entityPos.offset(radiusXZ, radiusY, radiusXZ)
).firstOrNull { pos ->
val blockEntity: BlockEntity? = world.getBlockEntity(pos)
if (blockEntity !is NestBlockEntity) return@firstOrNull false
if (pokemonEntity.isBattling || pokemonEntity.isBattleClone() || (!pokemonEntity.pokemon.isWild() && pokemonEntity.tethering?.tetheringId == null)) return@firstOrNull false
// we might need to check if a nest nearby was forgotten about
if (blockEntity.parents.first == pokemonEntity.uuid || blockEntity.parents.second == pokemonEntity.uuid) {
brain.setMemory(CobblemonMemories.PATERNAL_NEST_LOCATION, pos)
return@firstOrNull true
}
val nestBlockEntity = blockEntity
val allowedTypes = allowedNestTypes(pokemonEntity, brain)
val nestType = (nestBlockEntity.blockState.block as? WildNestBlock)?.type
// is the nest a valid type allowed by the mates
if (nestType == null || !isNestTypeAllowed(nestType, pokemonEntity, allowedTypes))
return@firstOrNull false
// can the mates get to the nest?
if (!canPathfindToTarget(pokemonEntity, nestBlockEntity.blockPos)) return@firstOrNull false
val isWildNest = nestBlockEntity.ownerUUID == null
val isPlayerNest = nestBlockEntity.ownerUUID != null
val isClaimed = nestBlockEntity.nestClaimedBy.first != null || nestBlockEntity.nestClaimedBy.second != null
val isEggless = nestBlockEntity.getItem(0).isEmpty
val isNestWaterlogged = nestBlockEntity.blockState.getOptionalValue(net.minecraft.world.level.block.state.properties.BlockStateProperties.WATERLOGGED).orElse(false)
val mate = brain.getMemory(CobblemonMemories.POTENTIAL_MATE) as? PokemonEntity
val nestClaimerOne = nestBlockEntity.nestClaimedBy.first?.let { world.getEntity(it) }
val nestClaimerTwo = nestBlockEntity.nestClaimedBy.second?.let { world.getEntity(it) }
val isClaimerOne = pokemonEntity.uuid == nestClaimerOne?.uuid
val isClaimerTwo = pokemonEntity.uuid == nestClaimerTwo?.uuid
val nestParentOneActive = nestBlockEntity.parents.first?.let { world.getEntity(it) }
val nestParentTwoActive = nestBlockEntity.parents.second?.let { world.getEntity(it) }
// skip any empty wild nests that are claimed
if (isWildNest && isEggless && ((nestParentOneActive != null || nestParentTwoActive != null) || (isClaimed && (nestClaimerOne != null && !isClaimerOne && nestClaimerTwo != null && !isClaimerTwo)))) {
return@firstOrNull false
}
// is this nest water group compatible? some of our nests can only be used by water egg grouup mons if they are water logged. reverse for land nests and water egg groups
if (!isWaterGroupCompatible(pokemonEntity, mate, isNestWaterlogged)) {
return@firstOrNull false
}
// pastured mons to only use free player nests and wild mons to use naturally made nests
return@firstOrNull when {
pokemonEntity.tethering?.tetheringId != null -> isPlayerNest && isEggless
else -> isWildNest && isEggless
}
}
}
private fun canPathfindToTarget(entity: PathfinderMob, targetPos: BlockPos): Boolean {
val path = entity.navigation.createPath(targetPos, 0)
return path != null && path.distToTarget < 1.75f
}
private fun isWaterGroupCompatible(
entity: PokemonEntity,
mate: PokemonEntity?,
isNestWaterlogged: Boolean
): Boolean {
val waterEggGroups = setOf("water_1", "water_2", "water_3")
val entityEggGroups = entity.pokemon.species.eggGroups.map { it.name.lowercase() }
val entityHasWater = entityEggGroups.any { it in waterEggGroups || it == "ditto" }
val entityOnlyWater = entityEggGroups.all { it in waterEggGroups }
val mateEggGroups = mate?.pokemon?.species?.eggGroups?.map { it.name.lowercase() } ?: emptyList()
val mateHasWater = mateEggGroups.any { it in waterEggGroups || it == "ditto" }
val mateOnlyWater = mateEggGroups.isNotEmpty() && mateEggGroups.all { it in waterEggGroups }
return if (isNestWaterlogged) {
entityHasWater && mateHasWater
} else {
!(entityOnlyWater || mateOnlyWater)
}
}
private fun allowedNestTypes(entity: PokemonEntity, brain: BiggerBrain): Set<WildNestType> {
val mate = brain.getMemory(CobblemonMemories.POTENTIAL_MATE) as? PokemonEntity
val types = if (mate != null) {
WildNestTypes.combinedTypes(entity, mate)
} else {
WildNestTypes.typesFor(entity.pokemon.species)
}
val mutable = types.toMutableSet()
if (!entity.pokemon.isWild() && mate != null && !mate.pokemon.isWild()) {
mutable.add(WildNestType.PLAYER)
mutable.add(WildNestType.KELP)
}
return mutable
}
private fun isNestTypeAllowed(
nestType: WildNestType,
entity: PokemonEntity,
allowedTypes: Set<WildNestType>
): Boolean {
if (nestType == WildNestType.PLAYER || nestType == WildNestType.KELP) {
return !entity.pokemon.isWild() && allowedTypes.contains(nestType)
}
return allowedTypes.contains(nestType)
}
class Config : SenseConfig {
var cooldownTicks: ExpressionOrEntityVariable = Either.left("200".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("20".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("5".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks, radiusXZ, radiusY).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return NestSense(
cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime),
radiusXZ = radiusXZ.resolveInt(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveInt(behaviourConfigurationContext.runtime)
)
}
}
}
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveInt
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.AgeableMob
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities
/**
* Senses when the Pokémon is near an adult of the same species. Maintains the NEAREST_VISIBLE_ADULT memory.
*
* @author broccoli
* @since May 15th, 2024
*/
class PokemonAdultSense(
var condition: Expression,
var cooldownTicks: Int = 100
) : Sense {
override var ticksUntilNextExecution: Int = 100
override val memories = setOf(MemoryModuleType.NEAREST_VISIBLE_ADULT, MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
override fun merge(other: Sense): Boolean {
if (other is PokemonAdultSense) {
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity || !brain.runtime.resolveBoolean(condition)) {
return
}
brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)?.let { visibleMobs ->
setNearestPokemonAdult(entity, visibleMobs, brain)
}
}
private fun setNearestPokemonAdult(entity: PokemonEntity, visibleMobs: NearestVisibleLivingEntities, brain: BiggerBrain) {
val nearestAdult = visibleMobs.findClosest { mob ->
targetIsValidForChild(entity, mob)
}.map { mob -> mob as AgeableMob }.orElse(null)
if (nearestAdult == null && brain.hasMemoryValue(MemoryModuleType.NEAREST_VISIBLE_ADULT)) {
brain.eraseMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT)
} else if (nearestAdult != null && brain.getMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT) != nearestAdult) {
brain.setMemory(MemoryModuleType.NEAREST_VISIBLE_ADULT, nearestAdult)
}
}
private fun targetIsValidForChild(child: PokemonEntity, entity: LivingEntity): Boolean {
val potentialParent = entity as? PokemonEntity ?: return false
val childSpecies = child.pokemon.species.resourceIdentifier
var preEvolution = potentialParent.pokemon.preEvolution
while (preEvolution != null) {
if (childSpecies == preEvolution.species.resourceIdentifier) {
return true
}
preEvolution = preEvolution.species.preEvolution
}
return false
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("40".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(cooldownTicks).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
val cooldownTicks = cooldownTicks.resolveInt(behaviourConfigurationContext.runtime)
return PokemonAdultSense(
condition = condition.asSimplifiedExpression(entity),
cooldownTicks = cooldownTicks
)
}
}
}
@@ -0,0 +1,130 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.ai.biggerbrain.sense
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.CobblemonMemories
import com.cobblemon.mod.common.api.ai.BehaviourConfigurationContext
import com.cobblemon.mod.common.api.ai.ExpressionOrEntityVariable
import com.cobblemon.mod.common.api.ai.asSimplifiedExpression
import com.cobblemon.mod.common.api.ai.asVariables
import com.cobblemon.mod.common.api.ai.biggerbrain.BiggerBrain
import com.cobblemon.mod.common.api.ai.config.sense.SenseConfig
import com.cobblemon.mod.common.api.ai.resolveDouble
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.ai.ObtainableItem
import com.cobblemon.mod.common.util.asExpression
import com.cobblemon.mod.common.util.findMatchingEntry
import com.cobblemon.mod.common.util.getMemorySafely
import com.cobblemon.mod.common.util.getObjectList
import com.cobblemon.mod.common.util.resolveBoolean
import com.mojang.datafixers.util.Either
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.ai.memory.MemoryModuleType
import net.minecraft.world.entity.item.ItemEntity
import net.minecraft.world.level.GameRules
import java.util.Optional
/**
* Senses nearby item entities. Returns the closest item that the Pokemon would desire to pickup.
*
* @author JazzMcNade
* @since February 15th, 2026
*/
class PokemonItemSense(
var condition: Expression,
var radiusXZ: Double = 16.0,
var radiusY: Double = 16.0,
var cooldownTicks: Int = 20 * 5
) : Sense {
override var ticksUntilNextExecution: Int = 50
override val memories =
setOf(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM)
override fun merge(other: Sense): Boolean {
if (other is PokemonItemSense) {
this.condition = other.condition
this.cooldownTicks = minOf(this.cooldownTicks, other.cooldownTicks)
this.radiusXZ = other.radiusXZ
this.radiusY = other.radiusY
return true
} else {
return false
}
}
override fun tick(entity: LivingEntity, brain: BiggerBrain) {
ticksUntilNextExecution = cooldownTicks
if (entity !is PokemonEntity || !brain.runtime.resolveBoolean(condition)) {
return
}
val world = entity.level()
if (!world.gameRules.getBoolean(GameRules.RULE_MOBGRIEFING) || !entity.pokemon.canDropHeldItem || entity.brain.getMemorySafely(
CobblemonMemories.DISABLE_WALK_TO_WANTED_ITEM
).orElse(false)
) {
// Mob griefing is disabled, the Pokemon cannot swap out its item, or it's exhausted from attempting to go to an unreachable item
// so don't bother to search
return
}
val pickupItems = entity.config.getObjectList<ObtainableItem>(PICKUP_ITEMS)
val heldItemValue =
pickupItems.findMatchingEntry(entity.registryAccess(), entity.pokemon.heldItem())?.pickupPriority ?: 0
if (heldItemValue >= (pickupItems.maxOfOrNull { it.pickupPriority } ?: 0)) {
// It's already holding the highest value item it can have, no need to look for better.
return
}
val list = world.getEntitiesOfClass(
ItemEntity::class.java,
entity.boundingBox.inflate(radiusXZ, radiusY, radiusXZ)
) {
(pickupItems.findMatchingEntry(entity.registryAccess(), it.item)?.pickupPriority ?: 0) > heldItemValue
&& entity.hasLineOfSight(it)
}
// Find the closest item to the entity
val nearestItemEntity = list.minByOrNull { it.distanceTo(entity) }
entity.getBrain()
.setMemory(MemoryModuleType.NEAREST_VISIBLE_WANTED_ITEM, Optional.ofNullable(nearestItemEntity))
}
class Config : SenseConfig {
var condition: ExpressionOrEntityVariable = Either.left("true".asExpression())
var radiusXZ: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var radiusY: ExpressionOrEntityVariable = Either.left("16.0".asExpression())
var cooldownTicks: ExpressionOrEntityVariable = Either.left("60".asExpression())
override fun getVariables(
entity: LivingEntity,
behaviourConfigurationContext: BehaviourConfigurationContext
) = listOf(
condition,
radiusXZ,
radiusY,
cooldownTicks
).asVariables()
override fun create(entity: LivingEntity, behaviourConfigurationContext: BehaviourConfigurationContext): Sense {
return PokemonItemSense(
condition = condition.asSimplifiedExpression(entity),
radiusXZ = radiusXZ.resolveDouble(behaviourConfigurationContext.runtime),
radiusY = radiusY.resolveDouble(behaviourConfigurationContext.runtime),
cooldownTicks = cooldownTicks.resolveDouble(behaviourConfigurationContext.runtime).toInt()
)
}
}
companion object {
const val PICKUP_ITEMS = "pickup_items"
}
}

Some files were not shown because too many files have changed in this diff Show More