Modern Apps git

← Modern-Apps.git

voxels: add farming with plantable crops that grow on farmland

Commit
ca4c72edb7084a5c0c7fab78c0bdcce4ebac444a
Author
Vayun Mathur <[email protected]>
When
2026-08-05 18:21 UTC (4 months ago)
Parents
b98ed27

Diff

games/voxels/src/main/assets/block/carrots_stage3.png
diff --git a/games/voxels/src/main/assets/block/carrots_stage3.png b/games/voxels/src/main/assets/block/carrots_stage3.pngnew file mode 100644index 0000000000..eb65b44299Binary files /dev/null and b/games/voxels/src/main/assets/block/carrots_stage3.png differ
games/voxels/src/main/assets/block/melon_stem_stage7.png
diff --git a/games/voxels/src/main/assets/block/melon_stem_stage7.png b/games/voxels/src/main/assets/block/melon_stem_stage7.pngnew file mode 100644index 0000000000..b1797d08e4Binary files /dev/null and b/games/voxels/src/main/assets/block/melon_stem_stage7.png differ
games/voxels/src/main/assets/block/wheat.png
diff --git a/games/voxels/src/main/assets/block/wheat.png b/games/voxels/src/main/assets/block/wheat.pngnew file mode 100644index 0000000000..2502546fcfBinary files /dev/null and b/games/voxels/src/main/assets/block/wheat.png differ
games/voxels/src/main/assets/block/wheat_seeds.png
diff --git a/games/voxels/src/main/assets/block/wheat_seeds.png b/games/voxels/src/main/assets/block/wheat_seeds.pngnew file mode 100644index 0000000000..38caa5fd26Binary files /dev/null and b/games/voxels/src/main/assets/block/wheat_seeds.png differ
games/voxels/src/main/assets/block/wheat_stage7_top.png
diff --git a/games/voxels/src/main/assets/block/wheat_stage7_top.png b/games/voxels/src/main/assets/block/wheat_stage7_top.pngnew file mode 100644index 0000000000..f1ee5677aaBinary files /dev/null and b/games/voxels/src/main/assets/block/wheat_stage7_top.png differ
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.ktindex b49efe337c..c4e81162c1 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt@@ -119,6 +119,7 @@ val blockNames = mapOf(     199 to "Adamant Helmet", 200 to "Adamant Chestplate", 201 to "Adamant Leggings", 202 to "Adamant Boots",     // Matcha's building set: slabs and stairs, cut on a stonecutter.     119 to "Wool", 120 to "Suspicious Sand", 252 to "Shears", 253 to "Fishing Rod", 254 to "Raw Fish", 255 to "Brush",+    121 to "Wheat Crop", 122 to "Carrot Crop", 123 to "Melon Crop", 250 to "Wheat Seeds", 251 to "Wheat",     102 to "Stone Slab", 103 to "Stone Stairs", 104 to "Cobble Slab", 105 to "Cobble Stairs",     106 to "Plank Slab", 107 to "Plank Stairs", 108 to "Brick Slab", 109 to "Brick Stairs",     110 to "Sandstone Slab", 111 to "Sandstone Stairs",@@ -167,6 +168,8 @@ val blockIconFile = mapOf(     218 to "blessing_apollo.png", 219 to "blessing_artemis.png", 220 to "blessing_warding.png",     119 to "wool.png", 120 to "suspicious_sand.png", 252 to "shears.png", 253 to "fishing_rod.png",     254 to "raw_fish.png", 255 to "brush.png",+    121 to "wheat_crop.png", 122 to "carrot_crop.png", 123 to "melon_crop.png",+    250 to "wheat_seeds.png", 251 to "wheat.png",     221 to "blessing_paris.png",     245 to "blessing_athena.png", 246 to "blessing_sekhmet.png", 247 to "blessing_camazotz.png",     248 to "blessing_tangaroa.png", 249 to "blessing_anubis.png",@@ -207,7 +210,8 @@ val blockIconFile = mapOf(  // Creative catalog, split into tabs. val catalogNatural = listOf(3, 2, 40, 46, 60, 39, 41, 71, 1, 6, 38, 36, 37, 14, 16, 17, 15, 45, 79, 75, 70,-    4, 5, 26, 28, 29, 31, 47, 48, 50, 51, 80, 11, 42, 43, 44, 32, 84, 85, 13, 120)+    4, 5, 26, 28, 29, 31, 47, 48, 50, 51, 80, 11, 42, 43, 44, 32, 84, 85, 13, 120,+    121, 122, 123) val catalogOres = listOf(18, 19, 20, 21, 22, 90, 91, 92, 97, 98, 23, 24, 25, 93, 94, 95, 99, 100, 101, 73) val catalogOcean = listOf(61, 62, 63, 64, 65, 66, 67, 68, 69) val catalogItems = listOf(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,@@ -215,7 +219,7 @@ val catalogItems = listOf(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,     154, 155, 156, 157, 158, 159, 187, 189, 190, 191,     192, 193, 194, 195, 196,     222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235,-    236, 237, 238, 254)+    236, 237, 238, 254, 250, 251) val catalogBlessings = listOf(160, 161, 162, 203, 204, 205, 206, 207, 208, 209, 210, 211,     212, 213, 214, 215, 216, 217, 218, 219, 220, 221,     245, 246, 247, 248, 249)
games/voxels/src/main/rust/shaders/atlas.bin
diff --git a/games/voxels/src/main/rust/shaders/atlas.bin b/games/voxels/src/main/rust/shaders/atlas.binindex 80be716704..e6be99e877 100644Binary files a/games/voxels/src/main/rust/shaders/atlas.bin and b/games/voxels/src/main/rust/shaders/atlas.bin differ
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 9b5f9e4544..c670313ee6 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -67,6 +67,7 @@ pub struct EngineState {     pub ambience: crate::ambience::Ambience,     prev_walk: f32,     pub fishing: crate::fishing::Fishing,+    farm_cd: f32, }  // One furnace job at a time, owned by the world rather than by a specific furnace block: the player@@ -257,6 +258,7 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool {         ambience: crate::ambience::Ambience::default(),         prev_walk: 0.0,         fishing: crate::fishing::Fishing::default(),+        farm_cd: 0.0,     });     INIT_DONE.store(true, Ordering::SeqCst);     true@@ -681,6 +683,7 @@ pub fn tick_and_render() {         tick_weather(state, dt, player_pos);         tick_ambience(state, dt, player_pos);         tick_fishing(state, dt, player_pos);+        tick_farmland(state, dt, player_pos);         let (mut entity_verts, mut entity_indices) = build_entity_mesh(&state.mobs);         {             let right = state.player.right();@@ -1488,6 +1491,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {         if id != 0 {             // Stone/ore only drops when mined with a pickaxe; soft blocks always drop.             let drops = !Block::from_id(id).needs_pickaxe() || item::is_pickaxe(sel);+            let meta_before = state.chunks.get_meta_world(x, y, z);             state.chunks.set_block_world(x, y, z, 0);             // Leaves occasionally give up an apple. Rolled against the world RNG rather than the             // block position, so one lucky coordinate can't be replanted into an apple farm.@@ -1496,7 +1500,11 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {                 *r ^= *r << 13; *r ^= *r >> 17; *r ^= *r << 5;                 if *r % 20 == 0 { state.inventory.add_block(130); }             }-            if drops {+            let crop = Block::from_id(id);+            if crop.is_crop() {+                harvest_crop(state, crop, meta_before);+                state.inventory.broken += 1;+            } else if drops {                 // Eros doubles what an ore gives up.                 let n = if state.player.blessed(Passive::Fortune) && is_ore(id) { 2 } else { 1 };                 for _ in 0..n { state.inventory.add_block(id); }@@ -1678,6 +1686,59 @@ fn slayer_mult(player: &Player, kind: MobKind) -> f32 {     let horror = matches!(kind, MobKind::Creeper | MobKind::Shulker | MobKind::Ghast);     if (is_undead(kind) && player.blessed(Passive::SmiteUndead)) || (horror && player.blessed(Passive::BaneOfHorrors)) { 2.0 } else { 1.0 } }+/// Seconds between growth passes, and how many random spots each pass checks. Sampling beats+/// scanning: a full sweep of the loaded world every tick would dwarf everything else the engine does.+const FARM_INTERVAL: f32 = 2.0;+const FARM_SAMPLES: usize = 40;+const FARM_RANGE: i32 = 24;++fn tick_farmland(state: &mut EngineState, dt: f32, player_pos: Vec3) {+    if state.dim != 0 { return; }+    state.farm_cd -= dt;+    if state.farm_cd > 0.0 { return; }+    state.farm_cd = FARM_INTERVAL;++    let (px, py, pz) = (player_pos.x.floor() as i32, player_pos.y.floor() as i32, player_pos.z.floor() as i32);+    let mut r = state.spawn_rng;+    let mut next = |s: &mut u32| { *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5; *s };+    let mut grown: Vec<(i32, i32)> = Vec::new();+    for _ in 0..FARM_SAMPLES {+        let a = next(&mut r);+        let x = px + (a % (FARM_RANGE as u32 * 2 + 1)) as i32 - FARM_RANGE;+        let b = next(&mut r);+        let z = pz + (b % (FARM_RANGE as u32 * 2 + 1)) as i32 - FARM_RANGE;+        let c = next(&mut r);+        let y = py + (c % 9) as i32 - 4;++        let id = state.chunks.get_block_world(x, y, z);+        if !Block::from_id(id).is_crop() { continue; }+        let meta = state.chunks.get_meta_world(x, y, z);+        let stage = crate::world::block::crop_stage(meta);+        if stage >= crate::world::block::CROP_RIPE { continue; }+        // Crops only grow on tended ground; break the farmland and the field stalls.+        if state.chunks.get_block_world(x, y - 1, z) != Block::Farmland as u8 { continue; }+        state.chunks.set_block_meta_world(x, y, z, id, crate::world::block::crop_meta(stage + 1));+        grown.push((x, z));+    }+    state.spawn_rng = r;+    for (x, z) in grown { mark_neighbors_dirty(state, x, z); }+}++/// A ripe crop pays out; an unripe one only returns the seed that was put in.+fn harvest_crop(state: &mut EngineState, crop: Block, meta: u8) {+    let seed = crop.crop_seed();+    if crate::world::block::crop_stage(meta) < crate::world::block::CROP_RIPE {+        state.inventory.add_block(seed);+        return;+    }+    let produce = crop.crop_yield();+    // Eros is a harvest blessing as much as a mining one.+    let n = if state.player.blessed(Passive::Fortune) { 5 } else { 3 };+    for _ in 0..n { state.inventory.add_block(produce); }+    // And the seed back, so a field is self-sustaining once it's planted.+    if seed != produce { state.inventory.add_block(seed); }+}+ /// What a dig site gives up. Matcha's archaeology yields pottery sherds, which this game doesn't /// model, so the pool is the small treasures a buried cache would plausibly hold. pub fn buried_find(roll: f32) -> u8 {@@ -1785,8 +1846,22 @@ fn placement_meta(block: Block, hit: &crate::raycast::HitResult, origin: Vec3, d }  fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {-    // Items (food, estus, materials) are never placeable as blocks.     let sel = state.inventory.selected_block();+    // Seeds are items, so planting has to be handled before the is_item bail-out below.+    if let Some(crop) = Block::crop_from_seed(sel) {+        if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) {+            let (x, y, z) = hit.pos;+            let (tx, ty, tz) = (x + hit.normal.0, y + hit.normal.1, z + hit.normal.2);+            let on_farmland = state.chunks.get_block_world(x, y, z) == Block::Farmland as u8 && hit.normal.1 == 1;+            if on_farmland && state.chunks.get_block_world(tx, ty, tz) == 0 && state.inventory.consume_selected().is_some() {+                state.chunks.set_block_meta_world(tx, ty, tz, crop as u8, crate::world::block::crop_meta(0));+                mark_neighbors_dirty(state, tx, tz);+                return true;+            }+        }+        return false;+    }+    // Items (food, estus, materials) are never placeable as blocks.     if sel == 0 || crate::item::is_item(sel) { return false; }     let block = Block::from_id(sel);     let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) else { return false; };
games/voxels/src/main/rust/src/inventory.rs
diff --git a/games/voxels/src/main/rust/src/inventory.rs b/games/voxels/src/main/rust/src/inventory.rsindex 8a49e2c135..ac20544609 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -24,11 +24,13 @@ pub struct Inventory { // (in1_id, in1_count, in2_id, in2_count, out_id, out_count). in2_id == 0 means a single ingredient. // Item ids 154+ are materials/tools (see item.rs). Ore -> material conversions live in SMELTING // instead, since those need a furnace, fuel and time.-pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 94] = [+pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 96] = [     (154, 1, 157, 1, 186, 1), // iron + coal -> flint & steel     (154, 2, 0, 0, 252, 1),   // iron            -> shears     (159, 3, 137, 2, 253, 1), // sticks + leather -> fishing rod     (159, 1, 236, 1, 255, 1), // stick + copper   -> archaeologist's brush+    (251, 3, 0, 0, 131, 1),   // wheat            -> bread+    (Block::HayBlock as u8, 1, 0, 0, 250, 4), // hay bale -> wheat seeds     (187, 1, Block::Glass as u8, 5, Block::Beacon as u8, 1), // nether star + glass -> beacon     (138, 2, 0, 0, 189, 3), // gunpowder -> firework rockets     (Block::Snow as u8, 1, 0, 0, 190, 4), // snow -> snowballs
games/voxels/src/main/rust/src/world/block.rs
diff --git a/games/voxels/src/main/rust/src/world/block.rs b/games/voxels/src/main/rust/src/world/block.rsindex 84b054c013..4d04076c6a 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -133,9 +133,21 @@ pub enum Block {     Wool = 119,     /// Buried finds. Brushing it yields loot and leaves plain sand behind; mining it just gives sand.     SuspiciousSand = 120,+    // Crops. Growth stage lives in the free meta bits, so each crop costs one block id rather than+    // one per stage; see CROP_STAGE_SHIFT below.+    WheatCrop = 121,+    CarrotCrop = 122,+    MelonCrop = 123, } -pub const MAX_BLOCK_ID: u8 = 120;+pub const MAX_BLOCK_ID: u8 = 123;++/// Growth stage occupies meta bits 3-4 (bits 0-2 are facing and top-half, used by slabs and stairs).+pub const CROP_STAGE_SHIFT: u8 = 3;+pub const CROP_STAGE_MASK: u8 = 0b1_1000;+pub const CROP_RIPE: u8 = 3;+pub fn crop_stage(meta: u8) -> u8 { (meta & CROP_STAGE_MASK) >> CROP_STAGE_SHIFT }+pub fn crop_meta(stage: u8) -> u8 { (stage.min(CROP_RIPE) << CROP_STAGE_SHIFT) & CROP_STAGE_MASK }  /// The geometry a block occupies within its cell. #[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -180,14 +192,28 @@ impl Block {     }     pub fn id(self) -> u8 { self as u8 }     pub fn is_air(self) -> bool { matches!(self, Self::Air) }-    pub fn is_solid(self) -> bool { !matches!(self, Self::Air | Self::Water | Self::Glass | Self::Lava | Self::NetherPortal | Self::EndPortal) }+    pub fn is_solid(self) -> bool { !matches!(self, Self::Air | Self::Water | Self::Glass | Self::Lava | Self::NetherPortal | Self::EndPortal) && !self.is_crop() }     pub fn is_transparent(self) -> bool {         // Slabs and stairs leave part of their cell empty, so they can never hide a neighbour's         // face wholesale. `occludes_face` decides the per-direction cases.         self.shape() != Shape::Cube             || matches!(self, Self::Air | Self::Glass | Self::Leaves | Self::Water | Self::BirchLeaves | Self::SpruceLeaves | Self::DarkOakLeaves | Self::AzaleaLeaves | Self::Lava | Self::NetherPortal | Self::EndPortal)+            || self.is_crop()     }     pub fn is_opaque(self) -> bool { !self.is_transparent() }+    /// Crops grow on farmland and are harvested rather than mined.+    pub fn is_crop(self) -> bool { matches!(self, Self::WheatCrop | Self::CarrotCrop | Self::MelonCrop) }+    /// The seed that plants this crop, and what a ripe one yields.+    pub fn crop_seed(self) -> u8 {+        match self { Self::WheatCrop => 250, Self::CarrotCrop => 135, Self::MelonCrop => 136, _ => 0 }+    }+    pub fn crop_yield(self) -> u8 {+        match self { Self::WheatCrop => 251, Self::CarrotCrop => 135, Self::MelonCrop => 136, _ => 0 }+    }+    /// The crop a given seed plants, if any.+    pub fn crop_from_seed(seed: u8) -> Option<Self> {+        match seed { 250 => Some(Self::WheatCrop), 135 => Some(Self::CarrotCrop), 136 => Some(Self::MelonCrop), _ => None }+    }      /// Does this block stop light? Distinct from `is_opaque`, which asks whether a neighbour's face     /// can be culled. A slab fills only half its cell so it can never hide a face, but it is still@@ -420,6 +446,9 @@ impl Block {             Self::Stonecutter => 141,             Self::Wool => 143,             Self::SuspiciousSand => 144,+            Self::WheatCrop => 145,+            Self::CarrotCrop => 146,+            Self::MelonCrop => 147,             // Slabs and stairs are textured entirely from their parent material.             Self::StoneSlab | Self::StoneStairs => Self::Stone.tile_top(),             Self::CobbleSlab | Self::CobbleStairs => Self::Cobble.tile_top(),@@ -629,6 +658,41 @@ mod tests {         assert!(Block::StoneSlab.blocks_light());         assert!(Block::StoneStairs.blocks_light());         assert!(Block::PlankSlab.blocks_light());+    }++    // Growth stage shares a meta byte with slab/stair facing, so the two must not tread on each other.+    #[test]+    fn crop_stage_survives_the_meta_it_shares() {+        for stage in 0..=CROP_RIPE {+            let m = crop_meta(stage);+            assert_eq!(crop_stage(m), stage, "stage {stage} didn't round-trip");+            assert_eq!(m & META_FACING, 0, "stage {stage} bled into the facing bits");+            assert_eq!(m & META_TOP, 0, "stage {stage} bled into the top-half bit");+        }+        // Over-ripe input clamps rather than wrapping to stage 0.+        assert_eq!(crop_stage(crop_meta(200)), CROP_RIPE);+        // And reading a slab's meta as a crop stage can't produce a ripe crop by accident.+        assert_eq!(crop_stage(META_TOP | FACE_WEST), 0);+    }++    // A crop has to be walkable, unlit and self-consistent about what it plants and yields.+    #[test]+    fn crops_are_walkable_and_plantable() {+        let mut seen = 0;+        for id in 0..=MAX_BLOCK_ID {+            let b = Block::from_id(id);+            if !b.is_crop() { continue; }+            seen += 1;+            assert!(!b.is_solid(), "{id} blocks the field it grows in");+            assert!(!b.blocks_light(), "{id} casts a shadow");+            assert!(b.is_transparent());+            let seed = b.crop_seed();+            assert!(seed != 0 && b.crop_yield() != 0, "{id} has no seed or no yield");+            assert_eq!(Block::crop_from_seed(seed), Some(b), "{id} can't be planted from its own seed");+        }+        assert_eq!(seen, 3, "expected three crops");+        assert_eq!(Block::crop_from_seed(0), None);+        assert_eq!(Block::crop_from_seed(Block::Stone as u8), None);          // Glass is the mirror image: it fills the cell but lets light straight through.         assert!(!Block::Glass.blocks_light());
scripts/voxels/build_atlas.py
diff --git a/scripts/voxels/build_atlas.py b/scripts/voxels/build_atlas.pyindex 2d80ec642b..99e28e26be 100644--- a/scripts/voxels/build_atlas.py+++ b/scripts/voxels/build_atlas.py@@ -30,6 +30,9 @@ NEW_H = NEW_ROWS * TILE # atlas untouched; new blocks start at 64. NEW_TILES = {     144: "suspicious_sand_0.png",+    145: "wheat_stage7_top.png",+    146: "carrots_stage3.png",+    147: "melon_stem_stage7.png",     64: "red_sand.png",     65: "red_sandstone.png",     66: "red_sandstone_top.png",@@ -138,6 +141,8 @@ COPY_ICONS = {     "shears.png": ("item", "shears.png"),     "raw_fish.png": ("item", "catfish.png"),     "brush.png": ("item", "archaeologists_brush.png"),+    "wheat.png": ("item", "wheat.png"),+    "wheat_seeds.png": ("item", "wheat_seeds.png"),     "quicksilver.png": ("item", "prismarine_shard.png"),     # The blessing pantheon. Items only: a blessing is never placed as a block, so no atlas tile.     **{f"blessing_{n}.png": ("item", f"blessing_{n}.png") for n in (@@ -195,6 +200,9 @@ PROC_ICON = {     141: "stonecutter.png",     143: "wool.png",     144: "suspicious_sand.png",+    145: "wheat_crop.png",+    146: "carrot_crop.png",+    147: "melon_crop.png", }