Skip to content

t1k:unity:dots-core:farming

FieldValue
Moduledots-core
Version3.56.1
Effortmedium
Tools—
/t1k:unity:dots-core:farming

Package: com.the1studio.dots-farming — namespace DOTSFarming.* (Tiles, Growth, Fertilizer, Harvest) Related skills: t1k-unity-dots-core-ecs (API) · t1k-unity-dots-combat-modifiers (fertilizer routes through the 4-scope pipeline) · t1k-unity-dots-core-architecture (new-library-package checklist)

  • Implementing farm-tile layers, plant growth, watering, or weed spawning
  • Building a fertilizer pipeline with grade-based growth/evaporation/weed-rate/durability multipliers
  • Implementing crop regrowth (finite vs. infinite) or producer fruiting cycles
  • Emitting harvest yields as pending world-entity spawns (never a currency delta)
  • Using FarmTile, PlantedCrop, TileWater, TileFertilizer, ProducerCycle, ReadyToHarvest, or PendingHarvestSpawn
  • Deciding which task a farm tile offers a worker (FarmTileWorkCandidate), or applying a claimed task to it (FarmTileTaskExecutor)
  • Deciding whether a creature is found on a tile (CreatureSpawnSystem) and raising a journal discovery signal
  • Building a fishing minigame on water tiles — candidate queueing, per-agent cast state, baked species catalogs, catch grading, or a fish journal (DOTSFarming.Fishing)
ComponentTypePurpose
FarmTileIComponentDataint2 Coord (simulate on XZ), TileLayer Layer, bool IsWaterTile, bool IsPond
TileLayerenum (byte)Empty → Farm → Floor → Building, fixed stack order
PlantedCropIComponentDataPresent only while planted. GrowthAmount/GrowthTimeSec (linear accumulator), RegrowthsLeft, InfiniteRegrow, IsWeed
TileWaterIComponentDatafloat SecondsRemaining — always present on a FarmTile; <= 0 = dry
TileFertilizerIComponentDataFertilizerGrade Grade, int UsesRemaining — present only while fertilized
ProducerCycleIComponentDataPresence IS the producer discriminator (no bool field). ProduceTimeSec, CycleElapsed, ProducedCount, ProduceAmount (cycle cap, not a yield)
ReadyToHarvestIComponentData, IEnableableComponentMaturity signal — always present, disabled, on any PlantedCrop entity (see Gotchas)
HarvestRequestedIComponentData, IEnableableComponentPlayer-input seam — distinct from maturity; enabling this + ReadyToHarvest triggers HarvestYieldSystem
HarvestCompletedTagIComponentData, IEnableableComponentSingle-frame handoff from HarvestYieldSystem to RegrowthSystem
HarvestYieldConfig / ProducerYieldConfigIComponentDataPer-entity item-id + quantity-range caches, stamped at planting time (this package does not stamp them — whichever wave implements planting owns that)
PendingHarvestSpawnIBufferElementData (cap 4)ItemId, Quantity, HarvestSlot Slot, float3 Origin — one pending world-entity spawn, never a currency delta
FarmingSimConfigIComponentData (singleton)WeedGrowthMultiplier (0.5), WeedSpawnChancePerTick (0.00075), MinProducesBeforeRegrow (3)
WeedContentEntryIBufferElementData (cap 4), optional singletonPlantId, GrowthTimeSec, MainItemId, MainQuantityMin/Max — one ambient-weed species. WeedSpawnSystem picks one entry deterministically per spawning tile. Absent, or present-but-empty, is the zero value — see Gotchas
SystemGroupRole
TileLayerSystemSimulationSystemGroupLayer leaves Farm → destroys PlantedCrop/TileFertilizer/ProducerCycle/ReadyToHarvest via ECB (Manager.LayerToDestroy)
PlantGrowthSystemSimulationSystemGroup[WithDisabled(typeof(ReadyToHarvest))] job; watering is a hard gate; growth is a plain linear accumulator
WaterEvaporationSystemSimulationSystemGroupSecondsRemaining -= dt * fertilizerEvaporation
WeedSpawnSystemSimulationSystemGroupPer-tile-per-tick roll on empty Farm tiles; adds PlantedCrop + ReadyToHarvest (disabled) together. Stamps content from the optional WeedContentEntry singleton buffer when baked, else the placeholder sentinel — see Gotchas
FertilizerApplySystemSimulationSystemGroupProcesses FertilizerApplyRequest: validates tile layer via PlacementLegalityTable, consumes one item from the requester’s stock, writes TileFertilizer. Two alternative stock sources — see below
FertilizerDurabilitySystemSimulationSystemGroupDecrements UsesRemaining; removes TileFertilizer at 0
HarvestYieldSystemSimulationSystemGroupGated on ReadyToHarvest AND HarvestRequested both enabled; rolls yields into PendingHarvestSpawn
RegrowthSystemSimulationSystemGroup, [UpdateAfter(HarvestYieldSystem)]Consumes HarvestCompletedTag; 3-way split — infinite / finite-regrow / final-harvest teardown
ProducerCycleSystemSimulationSystemGroupRepeating fruit clock, independent of GrowthTimeSec; emits exactly 1 item per completed cycle
CreatureSpawnSystemSimulationSystemGroupDOTSFarming.Wildlife. Per-tile-per-tick eligibility roll against every baked CreatureDefinition; raises CollectionDiscoverRequest on the journal singleton. Owns the spawn decision only — ambient creature motion/visuals are a separate, unbuilt concern

Watering is a hard gate (not a multiplier, with a permanent-water exemption for rice), planting sets PlantedCrop + a disabled ReadyToHarvest in the same transition, and regrowth is a 3-way split (infinite / seed-saved / replant) gated on the PRE-decrement RegrowthsLeft value. Offline catch-up owns the genre-specific half of the chain (how much elapsed time is worth, and whether it is worth showing the player) — MinClaimableSeconds gates only the claim MODAL, never whether growth/production/worker output apply; a non-claimable window self-retires by clearing Pending/AwaitingClaim without zeroing the delivered totals or touching Evaluated.

Verbatim source citations (Manager.cs:6719, Manager.cs:18551), full code, the complete offline-catch-up state-field reasoning, and FertilizerApplySystem’s two alternative stock sources (DOTSInventory.InventorySlot vs. DOTSEconomy.Storage.StoredItem, and why InventorySlot takes precedence by query construction, not pass ordering): references/patterns-and-catchup.md.

Worker task execution (DOTSFarming.Workers, DOTSFarming.Tiles)

Section titled “Worker task execution (DOTSFarming.Workers, DOTSFarming.Tiles)”

Farming supplies both halves of the tile side of the generic work queue (DOTSAI.WorkQueue — see t1k-unity-dots-ai-core): which task a tile offers, and what that task does to the tile. Both are plain static classes, deliberately callable from a player-tap path and an autonomous-worker path alike.

FarmTileWorkCandidate.ComputeKind — the state→verb authority

Section titled “FarmTileWorkCandidate.ComputeKind — the state→verb authority”

Single source of truth for “which WorkTaskKind, if any, does this FarmTile currently offer”. Shared by FarmTileCandidateBootstrapSystem (initial tag) and FarmTileCandidateRefreshSystem (every re-evaluation), and public so a player’s contextual tap resolves through the same authority instead of re-deriving the mapping.

WorkTaskKind ComputeKind(in FarmTile tile, bool hasCrop, in PlantedCrop crop,
bool readyToHarvest, in TileWater water);

The precedence order is load-bearing, and every step of it is a deliberate tie-break:

#ConditionResultWhy this order
1tile.IsWaterTileNoneCeded entirely to DOTSFarming.Fishing.FishingCandidateTagSystem. WorkCandidateTag has a single Kind field, so two producers tagging one tile means whichever ran first wins and the other’s tile sits forever mis-queued
2tile.Layer != FarmNoneFloor/building — not farmable
3!hasCropPlant
4readyToHarvestHarvestChecked BEFORE IsWeed — a mature weed is genuinely harvestable (weeds route through CropPlanting.Plant, so they carry a real HarvestYieldConfig) and yields whatever WeedSpawnSystem stamped: a real WeedContentEntry species if the consumer baked one, else the placeholder sentinel — see Gotchas
5crop.IsWeedWeedWins over the water gate — an immature dry weed satisfies both predicates; pulling it beats nurturing it
6water.SecondsRemaining > 0fNone / WaterAlready watered ⇒ nothing to do; otherwise Water

Nothing plants a crop on a water tile today, so step 1 costs nothing — but it is the flagged seam for whoever adds water-crop planting. See Fishing below for the producer it cedes to.

FarmTileTaskExecutor — the mutation primitive

Section titled “FarmTileTaskExecutor — the mutation primitive”

What Plant/Water/Harvest/Weed actually do to a tile. All four route through the same CropPlanting primitives a player tap uses, so autonomous execution and player input can never diverge in what happens — only in how the caller resolves content and when it fires.

MethodBehaviour
TryPlant(em, tile, in spec)false no-op if PlantedCrop already present; else CropPlanting.Plant
ApplyWater(em, tile, waterUnits, secondsPerUnit)Sets TileWater.SecondsRemaining = waterUnits * secondsPerUnit. Silently no-ops on a tile with no TileWater (defensive)
TryRequestHarvest(em, tile)Enables HarvestRequested; false if ReadyToHarvest is absent or disabled (reassigned mid-claim, regrow reset in flight)
PullWeed(em, tile)CropPlanting.ClearCrop — removes the full component set, never a hand-picked subset. Safe on a crop-less tile

Content resolution (which species, how many water units) stays out of this class — the caller resolves CropPlantingSpec from whatever content blob the consuming game authors.

WorkerFarmingConfig — the unsupervised-worker fallback

Section titled “WorkerFarmingConfig — the unsupervised-worker fallback”

A player’s Plant tap carries an explicit PlantIndex chosen in UI; a roaming worker claiming a Plant candidate has no such context, so it needs a species to fall back on. DefaultPlantIndex is that fallback, and WorkerFarmingConfig.Default sets it to 0 — an arbitrary-but-plausible pick, not a principled one. There is no isDefault/isStarter column in the content data justifying row 0 over any other low-tier plant. Any real consumer should author this singleton and override it.

Added as the producer for WorkTaskKind.Fishing — before this, Fishing was an enum value in DOTSCore.Workers.WorkTaskKind with nothing populating its queue. Lifted from TinyTerraces with its F1/F10 rationale intact.

“Fishable” is the SAME predicate as “growable water tile”

Section titled ““Fishable” is the SAME predicate as “growable water tile””

IsWaterTile && !IsPond. Not a new concept — PlantGrowthSystem, WeedSpawnSystem, AnimalFoodSpawnSystem and CreatureSpawnUtility.RequiresWaterTile all gate on it identically. Do not invent a second water predicate for fishing.

TypeKindPurpose
FishingCandidateTagSystemISystem, WorkerSystemGroup OrderFirst = true, [UpdateBefore(WorkCandidateRefreshSystem)]Tags every growable water tile with WorkCandidateTag { Kind = Fishing } + WorkQueueMembership + WorkTarget + enabled WorkCandidateDirty
FishTileEvaluatedIComponentData (tag)Added to every tile the system visits, fishable or not — this is what bounds the query (see below)
FishingCastStateIComponentDataPer-agent while AgentAssignment.Kind == Fishing. ElapsedSeconds, FailedAttempts, and its own Unity.Mathematics.Random stream so casts are deterministic per agent with no contested RNG singleton
FishCreelStorageTagIComponentData (tag)Marks the singleton entity caught fish are deposited into as DOTSEconomy.Storage.StoredItem — normally the world’s one PrimaryStorageTag entity, so fish sell through the existing storage/wallet machinery
FishJournalCatalogTagIComponentData (tag)Marks the singleton a consumer seeds with one DOTSProgression.Collection.CollectionEntry per catalog row (CollectionKind.Fish)
FishDefinitionBlobstruct (blob-safe)One baked species row: Id, ItemId (FixedString64Bytes), Rarity (relative weight), LevelReq, AreaType (baked as int), MinCm/AvgCm/MaxCm
FishCatchResultstructOne resolved cast: FishIndex (index into the caller’s catalog), SizeCm, Grade. FishCatchResult.None (FishIndex = -1) is the empty-catch sentinel
FishGradeenum (byte)F D C B A S — six equal buckets over a normalised [0,1] position (DOTSCore.TriangularSampler.NormalisedPosition)
AreaType[Flags] enum (byte)None / Pond / River. A bitmask, not a single value — a species can belong to more than one area’s pool
FishAreaMembershipTablesealed classGeneric id/name → AreaType lookup built from consumer-authored Row(id, name, area) list. For(displayName) / ForId(fishId), both returning AreaType.None on a miss
FishCollectionGradeMappingstaticToCollectionGrade(FishGrade) → DOTSProgression.Collection.CollectionGrade, via an explicit switch, never a (CollectionGrade)(byte) cast

The library holds the SHAPE; the species roster is consumer content

Section titled “The library holds the SHAPE; the species roster is consumer content”

FishAreaMembershipTable deliberately ships no rows. Naming real species in a shared package is the exact naming-charter violation the split avoids (rules/library-quality-mandate-unity.md). The worked reference consumer is TinyTerraces.Fishing.FishingAreaMembership, which keeps its authored 22-row table and its unchanged public For/ForId API by constructing one instance of the library table and delegating to it. Mirror that pattern — do not push a roster upstream.

The same split applies to AreaType: Pond/River is the generic shape, but which values a game uses, how many areas exist, and what they are called is consumer content.

Full detail: references/hard-rules.md. Read it before acting on this topic.

Full detail: references/hard-rules-farming.md. Read it before acting on this topic.

Normative rules kept inline:

  • ReadyToHarvest is ALWAYS-PRESENT (disabled), exactly like TileWater. PlantGrowthSystem is gated [WithDisabled(typeof(ReadyToHarvest))]. Any code path that adds PlantedCrop to an entity (a planting system, WeedSpawnSystem, a test fixture) MUST also add ReadyToHarvest disabled in the same ECB transition. Miss it and the query matches zero entities — no exception, no warning, just silent zero growth that reads exactly like a system bug.
DirectionPackageDetail
Depends onDOTSCore, DOTSCore.World, DOTSCore.TimeECB, SystemAPI, deterministic RNG helpers
Depends onDOTSModifiers.RuntimeFertilizer pipeline routes through the 4-scope modifier system rather than inlining multipliers
Depends onDOTSEconomy.Runtime (DOTSEconomy.Storage)FertilizerApplySystem accepts a StoredItem buffer as an alternative stock source and debits it via StorageUtility. Pre-existing asmdef reference — no new dependency.
Consumed by (forward seam)W3 carry-lifecycleDrains PendingHarvestSpawn; farming never touches a wallet/currency component
Depends onDOTSCore.Time (offline chain)OfflineCatchUp / OfflineElapsedSeconds supply the elapsed window; DOTSFarming.CatchUp decides what it is worth. See t1k-unity-dots-core-time
Consumed byDemo/game claim screenReads OfflineClaimState; raises OfflineClaimAckRequest. The library ships no UI
FeedsDOTSAI.WorkQueueFarmTileWorkCandidate.ComputeKind supplies WorkCandidateTag.Kind; FarmTileTaskExecutor applies the claimed task. See t1k-unity-dots-ai-core
FeedsDOTSAI.WorkQueue (fishing)FishingCandidateTagSystem is the producer for WorkTaskKind.Fishing — the only thing populating WorkQueueSet.FishingQueue
Depends onDOTSProgression.Collection (fishing)FishCollectionGradeMapping bridges FishGrade → CollectionGrade; FishJournalCatalogTag marks the seed entity. Same journal singleton CreatureSpawnSystem shares (row above)
Depends onDOTSEconomy.Runtime, DOTSCore.Workers (fishing)Caught fish deposit as DOTSEconomy.Storage.StoredItem; FishingCastState keys off AgentAssignment.Kind
FeedsDOTSProgression.CollectionCreatureSpawnSystem appends CollectionDiscoverRequest; CollectionRecordSystem is the sole drainer AND the sole writer of CollectionEntry. Both buffers live on the same journal singleton entity, shared with Fishing