veloren_common/terrain/
block.rs

1use super::{
2    SpriteKind,
3    sprite::{self, RelativeNeighborPosition},
4};
5use crate::{
6    comp::{fluid_dynamics::LiquidKind, tool::ToolKind},
7    consts::FRIC_GROUND,
8    effect::BuffEffect,
9    make_case_elim, rtsim,
10    vol::FilledVox,
11};
12use num_derive::FromPrimitive;
13use num_traits::FromPrimitive;
14use serde::{Deserialize, Serialize};
15use std::ops::Deref;
16use strum::{Display, EnumIter, EnumString};
17use vek::*;
18
19make_case_elim!(
20    block_kind,
21    #[derive(
22        Copy,
23        Clone,
24        Debug,
25        Hash,
26        Eq,
27        PartialEq,
28        Serialize,
29        Deserialize,
30        FromPrimitive,
31        EnumString,
32        EnumIter,
33        Display,
34    )]
35    #[repr(u8)]
36    pub enum BlockKind {
37        Air = 0x00, // Air counts as a fluid
38        Water = 0x01,
39        // 0x02 <= x < 0x10 are reserved for other fluids. These are 2^n aligned to allow bitwise
40        // checking of common conditions. For example, `is_fluid` is just `block_kind &
41        // 0x0F == 0` (this is a very common operation used in meshing that could do with
42        // being *very* fast).
43        Rock = 0x10,
44        WeakRock = 0x11, // Explodable
45        Lava = 0x12,     // TODO: Reevaluate whether this should be in the rock section
46        GlowingRock = 0x13,
47        GlowingWeakRock = 0x14,
48        // 0x12 <= x < 0x20 is reserved for future rocks
49        Grass = 0x20, // Note: *not* the same as grass sprites
50        Snow = 0x21,
51        // Snow to use with sites, to not attract snowfall particles
52        ArtSnow = 0x22,
53        // 0x21 <= x < 0x30 is reserved for future grasses
54        Earth = 0x30,
55        Sand = 0x31,
56        // 0x32 <= x < 0x40 is reserved for future earths/muds/gravels/sands/etc.
57        Wood = 0x40,
58        Leaves = 0x41,
59        GlowingMushroom = 0x42,
60        Ice = 0x43,
61        ArtLeaves = 0x44,
62        // 0x43 <= x < 0x50 is reserved for future tree parts
63        // Covers all other cases (we sometimes have bizarrely coloured misc blocks, and also we
64        // often want to experiment with new kinds of block without allocating them a
65        // dedicated block kind.
66        Misc = 0xFE,
67    }
68);
69
70impl BlockKind {
71    #[inline]
72    pub const fn is_air(&self) -> bool { matches!(self, BlockKind::Air) }
73
74    /// Determine whether the block kind is a gas or a liquid. This does not
75    /// consider any sprites that may occupy the block (the definition of
76    /// fluid is 'a substance that deforms to fit containers')
77    #[inline]
78    pub const fn is_fluid(&self) -> bool { *self as u8 & 0xF0 == 0x00 }
79
80    #[inline]
81    pub const fn is_liquid(&self) -> bool { self.is_fluid() && !self.is_air() }
82
83    #[inline]
84    pub const fn liquid_kind(&self) -> Option<LiquidKind> {
85        Some(match self {
86            BlockKind::Water => LiquidKind::Water,
87            BlockKind::Lava => LiquidKind::Lava,
88            _ => return None,
89        })
90    }
91
92    /// Determine whether the block is filled (i.e: fully solid). Right now,
93    /// this is the opposite of being a fluid.
94    #[inline]
95    pub const fn is_filled(&self) -> bool { !self.is_fluid() }
96
97    /// Determine whether the block has an RGB color stored in the attribute
98    /// fields.
99    #[inline]
100    pub const fn has_color(&self) -> bool { self.is_filled() }
101
102    /// Determine whether the block is 'terrain-like'. This definition is
103    /// arbitrary, but includes things like rocks, soils, sands, grass, and
104    /// other blocks that might be expected to the landscape. Plant matter and
105    /// snow are *not* included.
106    #[inline]
107    pub const fn is_terrain(&self) -> bool {
108        matches!(
109            self,
110            BlockKind::Rock
111                | BlockKind::WeakRock
112                | BlockKind::GlowingRock
113                | BlockKind::GlowingWeakRock
114                | BlockKind::Grass
115                | BlockKind::Earth
116                | BlockKind::Sand
117        )
118    }
119}
120
121/// # Format
122///
123/// ```ignore
124/// BBBBBBBB CCCCCCCC AAAAAIII IIIIIIII
125/// ```
126/// - `0..8`  : BlockKind
127/// - `8..16` : Category
128/// - `16..N` : Attributes (many fields)
129/// - `N..32` : Sprite ID
130///
131/// `N` is per-category. You can match on the category byte to find the length
132/// of the ID field.
133///
134/// Attributes are also per-category. Each category specifies its own list of
135/// attribute fields.
136///
137/// Why is the sprite ID at the end? Simply put, it makes masking faster and
138/// easier, which is important because extracting the `SpriteKind` is a more
139/// commonly performed operation than extracting attributes.
140#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
141pub struct Block {
142    kind: BlockKind,
143    data: [u8; 3],
144}
145
146impl FilledVox for Block {
147    fn default_non_filled() -> Self { Block::air(SpriteKind::Empty) }
148
149    fn is_filled(&self) -> bool { self.kind.is_filled() }
150}
151
152impl Deref for Block {
153    type Target = BlockKind;
154
155    fn deref(&self) -> &Self::Target { &self.kind }
156}
157
158impl Block {
159    pub const MAX_HEIGHT: f32 = 3.0;
160
161    /* Constructors */
162
163    #[inline]
164    pub const fn from_raw(kind: BlockKind, data: [u8; 3]) -> Self { Self { kind, data } }
165
166    // TODO: Rename to `filled`, make caller guarantees stronger
167    #[inline]
168    #[track_caller]
169    pub const fn new(kind: BlockKind, color: Rgb<u8>) -> Self {
170        if kind.is_filled() {
171            Self::from_raw(kind, [color.r, color.g, color.b])
172        } else {
173            // Works because `SpriteKind::Empty` has no attributes
174            let data = (SpriteKind::Empty as u32).to_be_bytes();
175            Self::from_raw(kind, [data[1], data[2], data[3]])
176        }
177    }
178
179    // Only valid if `block_kind` is unfilled, so this is just a private utility
180    // method
181    #[inline]
182    pub fn unfilled(kind: BlockKind, sprite: SpriteKind) -> Self {
183        #[cfg(debug_assertions)]
184        assert!(!kind.is_filled());
185
186        Self::from_raw(kind, sprite.to_initial_bytes())
187    }
188
189    #[inline]
190    pub fn air(sprite: SpriteKind) -> Self { Self::unfilled(BlockKind::Air, sprite) }
191
192    #[inline]
193    pub const fn empty() -> Self {
194        // Works because `SpriteKind::Empty` has no attributes
195        let data = (SpriteKind::Empty as u32).to_be_bytes();
196        Self::from_raw(BlockKind::Air, [data[1], data[2], data[3]])
197    }
198
199    #[inline]
200    pub fn water(sprite: SpriteKind) -> Self { Self::unfilled(BlockKind::Water, sprite) }
201
202    /* Sprite decoding */
203
204    #[inline(always)]
205    pub const fn get_sprite(&self) -> Option<SpriteKind> {
206        if !self.kind.is_filled() {
207            SpriteKind::from_block(*self)
208        } else {
209            None
210        }
211    }
212
213    #[inline(always)]
214    pub(super) const fn sprite_category_byte(&self) -> u8 { self.data[0] }
215
216    #[inline(always)]
217    pub const fn sprite_category(&self) -> Option<sprite::Category> {
218        if self.kind.is_filled() {
219            None
220        } else {
221            sprite::Category::from_block(*self)
222        }
223    }
224
225    /// Build this block with the given sprite attribute set.
226    #[inline]
227    pub fn with_attr<A: sprite::Attribute>(
228        mut self,
229        attr: A,
230    ) -> Result<Self, sprite::AttributeError<core::convert::Infallible>> {
231        self.set_attr(attr)?;
232        Ok(self)
233    }
234
235    /// Set the given attribute of this block's sprite.
236    #[inline]
237    pub fn set_attr<A: sprite::Attribute>(
238        &mut self,
239        attr: A,
240    ) -> Result<(), sprite::AttributeError<core::convert::Infallible>> {
241        match self.sprite_category() {
242            Some(category) => category.write_attr(self, attr),
243            None => Err(sprite::AttributeError::NotPresent),
244        }
245    }
246
247    /// Get the given attribute of this block's sprite.
248    #[inline]
249    pub fn get_attr<A: sprite::Attribute>(&self) -> Result<A, sprite::AttributeError<A::Error>> {
250        match self.sprite_category() {
251            Some(category) => category.read_attr(*self),
252            None => Err(sprite::AttributeError::NotPresent),
253        }
254    }
255
256    pub fn sprite_z_rot(&self) -> Option<f32> {
257        self.get_attr::<sprite::Ori>()
258            .ok()
259            .map(|ori| std::f32::consts::PI * 0.25 * ori.0 as f32)
260    }
261
262    pub fn sprite_mirror_vec(&self) -> Vec3<f32> {
263        Vec3::new(
264            self.get_attr::<sprite::MirrorX>().map(|m| m.0),
265            self.get_attr::<sprite::MirrorY>().map(|m| m.0),
266            self.get_attr::<sprite::MirrorZ>().map(|m| m.0),
267        )
268        .map(|b| match b.unwrap_or(false) {
269            true => -1.0,
270            false => 1.0,
271        })
272    }
273
274    #[inline(always)]
275    pub(super) const fn data(&self) -> [u8; 3] { self.data }
276
277    #[inline(always)]
278    pub(super) const fn with_data(mut self, data: [u8; 3]) -> Self {
279        self.data = data;
280        self
281    }
282
283    #[inline(always)]
284    pub(super) const fn to_be_u32(self) -> u32 {
285        u32::from_be_bytes([self.kind as u8, self.data[0], self.data[1], self.data[2]])
286    }
287
288    #[inline]
289    pub fn get_color(&self) -> Option<Rgb<u8>> {
290        if self.has_color() {
291            Some(self.data.into())
292        } else {
293            None
294        }
295    }
296
297    /// Returns the rtsim resource, if any, that this block corresponds to. If
298    /// you want the scarcity of a block to change with rtsim's resource
299    /// depletion tracking, you can do so by editing this function.
300    // TODO: Return type should be `Option<&'static [(rtsim::TerrainResource, f32)]>` to allow
301    // fractional quantities and multiple resources per sprite
302    #[inline]
303    pub fn get_rtsim_resource(&self) -> Option<rtsim::TerrainResource> {
304        match self.get_sprite()? {
305            SpriteKind::Stones | SpriteKind::Stones2 => Some(rtsim::TerrainResource::Stone),
306            SpriteKind::Twigs
307            | SpriteKind::Wood
308            | SpriteKind::Bamboo
309            | SpriteKind::Hardwood
310            | SpriteKind::Ironwood
311            | SpriteKind::Frostwood
312            | SpriteKind::Eldwood => Some(rtsim::TerrainResource::Wood),
313            SpriteKind::Amethyst
314            | SpriteKind::Ruby
315            | SpriteKind::Sapphire
316            | SpriteKind::Emerald
317            | SpriteKind::Topaz
318            | SpriteKind::Diamond
319            | SpriteKind::CrystalHigh
320            | SpriteKind::CrystalLow
321            | SpriteKind::Lodestone => Some(rtsim::TerrainResource::Gem),
322            SpriteKind::Bloodstone
323            | SpriteKind::Coal
324            | SpriteKind::Cobalt
325            | SpriteKind::Copper
326            | SpriteKind::Iron
327            | SpriteKind::Tin
328            | SpriteKind::Silver
329            | SpriteKind::Gold => Some(rtsim::TerrainResource::Ore),
330            SpriteKind::LongGrass
331            | SpriteKind::MediumGrass
332            | SpriteKind::ShortGrass
333            | SpriteKind::LargeGrass
334            | SpriteKind::GrassBlue
335            | SpriteKind::SavannaGrass
336            | SpriteKind::TallSavannaGrass
337            | SpriteKind::RedSavannaGrass
338            | SpriteKind::JungleRedGrass
339            | SpriteKind::Fern => Some(rtsim::TerrainResource::Grass),
340            SpriteKind::BlueFlower
341            | SpriteKind::PinkFlower
342            | SpriteKind::PurpleFlower
343            | SpriteKind::RedFlower
344            | SpriteKind::WhiteFlower
345            | SpriteKind::YellowFlower
346            | SpriteKind::Sunflower
347            | SpriteKind::Moonbell
348            | SpriteKind::Pyrebloom => Some(rtsim::TerrainResource::Flower),
349            SpriteKind::Reed
350            | SpriteKind::Flax
351            | SpriteKind::WildFlax
352            | SpriteKind::Cotton
353            | SpriteKind::Corn
354            | SpriteKind::WheatYellow
355            | SpriteKind::WheatGreen => Some(rtsim::TerrainResource::Plant),
356            SpriteKind::Apple
357            | SpriteKind::Pumpkin
358            | SpriteKind::Beehive // TODO: Not a fruit, but kind of acts like one
359            | SpriteKind::Coconut => Some(rtsim::TerrainResource::Fruit),
360            SpriteKind::Lettuce
361            | SpriteKind::Carrot
362            | SpriteKind::Tomato
363            | SpriteKind::Radish
364            | SpriteKind::Turnip => Some(rtsim::TerrainResource::Vegetable),
365            SpriteKind::Mushroom
366            | SpriteKind::CaveMushroom
367            | SpriteKind::CeilingMushroom
368            | SpriteKind::RockyMushroom
369            | SpriteKind::LushMushroom
370            | SpriteKind::GlowMushroom => Some(rtsim::TerrainResource::Mushroom),
371            // Catch all for other things that give items, but aren't specified above.
372            s if s.default_loot_spec().is_some_and(|inner| inner.is_some()) => Some(rtsim::TerrainResource::Loot),
373            _ => None,
374        }
375        // Don't count collected sprites.
376        // TODO: we may want to have rtsim still spawn these sprites when depleted by spawning them
377        // in the "collected" state, see `into_collected` for sprites that would need this.
378        .filter(|_|  matches!(self.get_attr(), Ok(sprite::Collectable(true)) | Err(_)))
379    }
380
381    #[inline]
382    pub fn get_glow(&self) -> Option<u8> {
383        let glow_level = match self.kind() {
384            BlockKind::Lava => 24,
385            BlockKind::GlowingRock | BlockKind::GlowingWeakRock => 10,
386            BlockKind::GlowingMushroom => 20,
387            _ => match self.get_sprite()? {
388                SpriteKind::StreetLamp | SpriteKind::StreetLampTall | SpriteKind::BonfireMLit => 24,
389                SpriteKind::Ember | SpriteKind::FireBlock => 20,
390                SpriteKind::WallLamp
391                | SpriteKind::WallLampSmall
392                | SpriteKind::WallLampWizard
393                | SpriteKind::WallLampMesa
394                | SpriteKind::WallSconce
395                | SpriteKind::FireBowlGround
396                | SpriteKind::MesaLantern
397                | SpriteKind::LampTerracotta
398                | SpriteKind::ChristmasOrnament
399                | SpriteKind::CliffDecorBlock
400                | SpriteKind::Orb
401                | SpriteKind::Candle => 16,
402                SpriteKind::DiamondLight => 30,
403                SpriteKind::VeloriteFrag
404                | SpriteKind::GrassBlueShort
405                | SpriteKind::GrassBlueMedium
406                | SpriteKind::GrassBlueLong
407                | SpriteKind::CavernLillypadBlue
408                | SpriteKind::MycelBlue
409                | SpriteKind::Mold
410                | SpriteKind::CeilingMushroom => 6,
411                SpriteKind::CaveMushroom
412                | SpriteKind::GlowMushroom
413                | SpriteKind::CookingPot
414                | SpriteKind::CrystalHigh
415                | SpriteKind::LanternFlower
416                | SpriteKind::CeilingLanternFlower
417                | SpriteKind::LanternPlant
418                | SpriteKind::CeilingLanternPlant
419                | SpriteKind::CrystalLow => 10,
420                SpriteKind::SewerMushroom => 16,
421                SpriteKind::Lodestone => 3,
422                SpriteKind::Lantern
423                | SpriteKind::LanternpostWoodLantern
424                | SpriteKind::LanternAirshipWallBlackS
425                | SpriteKind::LanternAirshipWallBrownS
426                | SpriteKind::LanternAirshipWallChestnutS
427                | SpriteKind::LanternAirshipWallRedS
428                | SpriteKind::LanternAirshipGroundBlackS
429                | SpriteKind::LanternAirshipGroundBrownS
430                | SpriteKind::LanternAirshipGroundChestnutS
431                | SpriteKind::LanternAirshipGroundRedS
432                | SpriteKind::LampMetalShinglesCyan
433                | SpriteKind::LampMetalShinglesRed => 24,
434                SpriteKind::Velorite | SpriteKind::TerracottaStatue => 8,
435                SpriteKind::SeashellLantern | SpriteKind::GlowIceCrystal => 16,
436                SpriteKind::SeaDecorEmblem => 12,
437                SpriteKind::SeaDecorBlock
438                | SpriteKind::HaniwaKeyDoor
439                | SpriteKind::VampireKeyDoor => 10,
440                _ => return None,
441            },
442        };
443
444        if self
445            .get_attr::<sprite::LightEnabled>()
446            .map_or(true, |l| l.0)
447        {
448            Some(glow_level)
449        } else {
450            None
451        }
452    }
453
454    // minimum block, attenuation
455    #[inline]
456    pub fn get_max_sunlight(&self) -> (u8, f32) {
457        match self.kind() {
458            BlockKind::Water => (0, 0.4),
459            BlockKind::Leaves => (9, 255.0),
460            BlockKind::ArtLeaves => (9, 255.0),
461            BlockKind::Wood => (6, 2.0),
462            BlockKind::Snow => (6, 2.0),
463            BlockKind::ArtSnow => (6, 2.0),
464            BlockKind::Ice => (4, 2.0),
465            _ if self.is_opaque() => (0, 255.0),
466            _ => (0, 0.0),
467        }
468    }
469
470    // Filled blocks or sprites
471    #[inline]
472    pub fn is_solid(&self) -> bool {
473        self.get_sprite()
474            .map(|s| s.solid_height().is_some())
475            .unwrap_or(!matches!(self.kind, BlockKind::Lava))
476    }
477
478    pub fn valid_collision_dir(
479        &self,
480        entity_aabb: Aabb<f32>,
481        block_aabb: Aabb<f32>,
482        move_dir: Vec3<f32>,
483    ) -> bool {
484        self.get_sprite().is_none_or(|sprite| {
485            sprite.valid_collision_dir(entity_aabb, block_aabb, move_dir, self)
486        })
487    }
488
489    /// Can this block be exploded? If so, what 'power' is required to do so?
490    /// Note that we don't really define what 'power' is. Consider the units
491    /// arbitrary and only important when compared to one-another.
492    #[inline]
493    pub fn explode_power(&self) -> Option<f32> {
494        // Explodable means that the terrain sprite will get removed anyway,
495        // so all is good for empty fluids.
496        match self.kind() {
497            BlockKind::Leaves => Some(0.25),
498            BlockKind::ArtLeaves => Some(0.25),
499            BlockKind::Grass => Some(0.5),
500            BlockKind::WeakRock => Some(0.75),
501            BlockKind::Snow => Some(0.1),
502            BlockKind::Ice => Some(0.5),
503            BlockKind::Wood => Some(4.5),
504            BlockKind::Lava => None,
505            _ => self.get_sprite().and_then(|sprite| match sprite {
506                sprite if sprite.is_defined_as_container() => None,
507                SpriteKind::Keyhole
508                | SpriteKind::KeyDoor
509                | SpriteKind::BoneKeyhole
510                | SpriteKind::BoneKeyDoor
511                | SpriteKind::OneWayWall
512                | SpriteKind::KeyholeBars
513                | SpriteKind::DoorBars => None,
514                SpriteKind::Anvil
515                | SpriteKind::Cauldron
516                | SpriteKind::CookingPot
517                | SpriteKind::CraftingBench
518                | SpriteKind::Forge
519                | SpriteKind::Loom
520                | SpriteKind::SpinningWheel
521                | SpriteKind::DismantlingBench
522                | SpriteKind::RepairBench
523                | SpriteKind::TanningRack
524                | SpriteKind::Chest
525                | SpriteKind::DungeonChest0
526                | SpriteKind::DungeonChest1
527                | SpriteKind::DungeonChest2
528                | SpriteKind::DungeonChest3
529                | SpriteKind::DungeonChest4
530                | SpriteKind::DungeonChest5
531                | SpriteKind::CoralChest
532                | SpriteKind::HaniwaUrn
533                | SpriteKind::HaniwaKeyDoor
534                | SpriteKind::HaniwaKeyhole
535                | SpriteKind::VampireKeyDoor
536                | SpriteKind::VampireKeyhole
537                | SpriteKind::MyrmidonKeyDoor
538                | SpriteKind::MyrmidonKeyhole
539                | SpriteKind::MinotaurKeyhole
540                | SpriteKind::HaniwaTrap
541                | SpriteKind::HaniwaTrapTriggered
542                | SpriteKind::ChestBuried
543                | SpriteKind::CommonLockedChest
544                | SpriteKind::TerracottaChest
545                | SpriteKind::SahaginChest
546                | SpriteKind::SeaDecorBlock
547                | SpriteKind::SeaDecorChain
548                | SpriteKind::SeaDecorWindowHor
549                | SpriteKind::SeaDecorWindowVer
550                | SpriteKind::WitchWindow
551                | SpriteKind::Rope
552                | SpriteKind::MetalChain
553                | SpriteKind::IronSpike
554                | SpriteKind::HotSurface
555                | SpriteKind::FireBlock
556                | SpriteKind::GlassBarrier
557                | SpriteKind::GlassKeyhole
558                | SpriteKind::SahaginKeyhole
559                | SpriteKind::SahaginKeyDoor
560                | SpriteKind::TerracottaKeyDoor
561                | SpriteKind::TerracottaKeyhole
562                | SpriteKind::TerracottaStatue
563                | SpriteKind::TerracottaBlock => None,
564                SpriteKind::EnsnaringVines
565                | SpriteKind::EnsnaringWeb
566                | SpriteKind::SeaUrchin
567                | SpriteKind::IceSpike
568                | SpriteKind::DiamondLight => Some(0.1),
569                _ => Some(0.25),
570            }),
571        }
572    }
573
574    /// Whether the block containes a sprite that is collectible.
575    ///
576    /// Note, this is based on [`SpriteKind::collectible_info`] and accounts for
577    /// if the [`Collectable`][`sprite::Collectable`] sprite attr is `false`.
578    #[inline]
579    pub fn is_collectible(&self) -> bool {
580        self.get_sprite()
581            .is_some_and(|s| s.collectible_info().is_some())
582            && matches!(self.get_attr(), Ok(sprite::Collectable(true)) | Err(_))
583    }
584
585    /// Can this sprite be picked up to yield an item without a tool?
586    ///
587    /// Note, this is based on [`SpriteKind::collectible_info`] and accounts for
588    /// if the [`Collectable`][`sprite::Collectable`] sprite attr is `false`.
589    #[inline]
590    pub fn is_directly_collectible(&self) -> bool {
591        // NOTE: This doesn't require `SpriteCfg` because `SpriteCfg::loot_table` is
592        // only expected to be set for `collectible_info.is_some()` sprites!
593        self.get_sprite()
594            .is_some_and(|s| s.collectible_info() == Some(None))
595            && matches!(self.get_attr(), Ok(sprite::Collectable(true)) | Err(_))
596    }
597
598    #[inline]
599    pub fn is_mountable(&self) -> bool { self.mount_offset().is_some() }
600
601    /// Get the position and direction to mount this block if any.
602    pub fn mount_offset(&self) -> Option<(Vec3<f32>, Vec3<f32>)> {
603        self.get_sprite().and_then(|sprite| sprite.mount_offset())
604    }
605
606    pub fn mount_buffs(&self) -> Option<Vec<BuffEffect>> {
607        self.get_sprite().and_then(|sprite| sprite.mount_buffs())
608    }
609
610    pub fn is_controller(&self) -> bool {
611        self.get_sprite()
612            .is_some_and(|sprite| sprite.is_controller())
613    }
614
615    #[inline]
616    pub fn is_bonkable(&self) -> bool {
617        match self.get_sprite() {
618            Some(
619                SpriteKind::Apple | SpriteKind::Beehive | SpriteKind::Coconut | SpriteKind::Bomb,
620            ) => self.is_solid(),
621            _ => false,
622        }
623    }
624
625    #[inline]
626    pub fn is_owned(&self) -> bool {
627        self.get_attr::<sprite::Owned>()
628            .is_ok_and(|sprite::Owned(b)| b)
629    }
630
631    /// The tool required to mine this block. For blocks that cannot be mined,
632    /// `None` is returned.
633    #[inline]
634    pub fn mine_tool(&self) -> Option<ToolKind> {
635        match self.kind() {
636            BlockKind::WeakRock | BlockKind::Ice | BlockKind::GlowingWeakRock => {
637                Some(ToolKind::Pick)
638            },
639            _ => self.get_sprite().and_then(|s| s.mine_tool()),
640        }
641    }
642
643    #[inline]
644    pub fn is_opaque(&self) -> bool {
645        match self.get_sprite() {
646            Some(
647                SpriteKind::Keyhole
648                | SpriteKind::KeyDoor
649                | SpriteKind::KeyholeBars
650                | SpriteKind::DoorBars,
651            ) => true,
652            Some(_) => false,
653            None => self.kind().is_filled(),
654        }
655    }
656
657    #[inline]
658    pub fn solid_height(&self) -> f32 {
659        self.get_sprite()
660            .map(|s| s.solid_height().unwrap_or(0.0))
661            .unwrap_or(1.0)
662    }
663
664    /// Get the friction constant used to calculate surface friction when
665    /// walking/climbing. Currently has no units.
666    #[inline]
667    pub fn get_friction(&self) -> f32 {
668        match self.kind() {
669            BlockKind::Ice => FRIC_GROUND * 0.1,
670            _ => FRIC_GROUND,
671        }
672    }
673
674    /// Get the traction permitted by this block as a proportion of the friction
675    /// applied.
676    ///
677    /// 1.0 = default, 0.0 = completely inhibits movement, > 1.0 = potential for
678    /// infinite acceleration (in a vacuum).
679    #[inline]
680    pub fn get_traction(&self) -> f32 {
681        match self.kind() {
682            BlockKind::Snow | BlockKind::ArtSnow => 0.8,
683            _ => 1.0,
684        }
685    }
686
687    /// Apply a light toggle to this block, if possible
688    pub fn with_toggle_light(self, enable: bool) -> Option<Self> {
689        self.with_attr(sprite::LightEnabled(enable)).ok()
690    }
691
692    #[inline]
693    pub fn kind(&self) -> BlockKind { self.kind }
694
695    /// If possible, copy the sprite/color data of the other block.
696    #[inline]
697    #[must_use]
698    pub fn with_data_of(mut self, other: Block) -> Self {
699        if self.is_filled() == other.is_filled() {
700            self = self.with_data(other.data());
701        }
702        self
703    }
704
705    /// If this block is a fluid, replace its sprite.
706    #[inline]
707    #[must_use]
708    pub fn with_sprite(self, sprite: SpriteKind) -> Self {
709        match self.try_with_sprite(sprite) {
710            Ok(b) => b,
711            Err(b) => b,
712        }
713    }
714
715    /// If this block is a fluid, replace its sprite.
716    ///
717    /// Returns block in `Err` if the sprite was not replaced.
718    #[inline]
719    pub fn try_with_sprite(self, sprite: SpriteKind) -> Result<Self, Self> {
720        if self.is_filled() {
721            Err(self)
722        } else {
723            Ok(Self::unfilled(self.kind, sprite))
724        }
725    }
726
727    /// If this block can have orientation, give it a new orientation.
728    #[inline]
729    #[must_use]
730    pub fn with_ori(self, ori: u8) -> Option<Self> { self.with_attr(sprite::Ori(ori)).ok() }
731
732    /// If this block can have adjacent sprites, give it its AdjacentType
733    #[inline]
734    #[must_use]
735    pub fn with_adjacent_type(self, adj: RelativeNeighborPosition) -> Option<Self> {
736        self.with_attr(sprite::AdjacentType(adj as u8)).ok()
737    }
738
739    /// Remove the terrain sprite or solid aspects of a block
740    #[inline]
741    #[must_use]
742    pub fn into_vacant(self) -> Self {
743        if self.is_fluid() {
744            Block::unfilled(self.kind(), SpriteKind::Empty)
745        } else {
746            // FIXME: Figure out if there's some sensible way to determine what medium to
747            // replace a filled block with if it's removed.
748            Block::air(SpriteKind::Empty)
749        }
750    }
751
752    /// Apply the effect of collecting the sprite in this block.
753    ///
754    /// This sets the `Collectable` attribute to `false` for some sprites like
755    /// `Lettuce`. Other sprites will simply be removed via
756    /// [`into_vacant`][Self::into_vacant].
757    #[inline]
758    #[must_use]
759    pub fn into_collected(self) -> Self {
760        match self.get_sprite() {
761            Some(SpriteKind::Lettuce) => self.with_attr(sprite::Collectable(false)).expect(
762                "Setting collectable will not fail since this sprite has Collectable attribute",
763            ),
764            _ => self.into_vacant(),
765        }
766    }
767
768    /// Attempt to convert a [`u32`] to a block
769    #[inline]
770    #[must_use]
771    pub fn from_u32(x: u32) -> Option<Self> {
772        let [bk, r, g, b] = x.to_le_bytes();
773        let block = Self {
774            kind: BlockKind::from_u8(bk)?,
775            data: [r, g, b],
776        };
777
778        (block.kind.is_filled() || SpriteKind::from_block(block).is_some()).then_some(block)
779    }
780
781    #[inline]
782    pub fn to_u32(self) -> u32 {
783        u32::from_le_bytes([self.kind as u8, self.data[0], self.data[1], self.data[2]])
784    }
785}
786
787const _: () = assert!(core::mem::size_of::<BlockKind>() == 1);
788const _: () = assert!(core::mem::size_of::<Block>() == 4);