veloren_common/terrain/sprite/
mod.rs

1//! Here's the deal.
2//!
3//! Blocks are always 4 bytes. The first byte is the [`BlockKind`]. For filled
4//! blocks, the remaining 3 sprites are the block colour. For unfilled sprites
5//! (air, water, etc.) the remaining 3 bytes correspond to sprite data. That's
6//! not a lot to work with! As a result, we're pulling every rabbit out of the
7//! bit-twiddling hat to squash as much information as possible into those 3
8//! bytes.
9//!
10//! Fundamentally, sprites are composed of one or more elements: the
11//! [`SpriteKind`], which tells us what the sprite *is*, and a list of
12//! attributes that define extra properties that the sprite has. Some examples
13//! of attributes might include:
14//!
15//! - the orientation of the sprite (with respect to the volume it sits within)
16//! - whether the sprite has snow cover on it
17//! - a 'variation seed' that allows frontends to pseudorandomly customise the
18//!   appearance of the sprite in a manner that's consistent across clients
19//! - Whether doors are open, closed, or permanently locked
20//! - The stage of growth of a plant
21//! - The kind of plant that sits in pots/planters/vessels
22//! - The colour of the sprite
23//! - The material of the sprite
24//!
25//! # Category
26//!
27//! The first of the three bytes is the sprite 'category'. As much as possible,
28//! we should try to have the properties of each sprite within a category be
29//! consistent with others in the category, to improve performance.
30//!
31//! Since a single byte is not enough to disambiguate the [`SpriteKind`] (we
32//! have more than 256 kinds, so there's not enough space), the category also
33//! corresponds to a 'kind mask': a bitmask that, when applied to the first two
34//! of the three bytes gives us the [`SpriteKind`].
35//!
36//! [`BlockKind`]: crate::terrain::block::BlockKind
37//! [`SpriteKind`]: crate::terrain::sprite::SpriteKind
38
39mod magic;
40//use inline_tweak::tweak_fn;
41pub use self::magic::{Attribute, AttributeError};
42use crate::{
43    attributes,
44    comp::{BuffData, BuffKind, item::ItemDefinitionIdOwned, tool::ToolKind},
45    effect::BuffEffect,
46    lottery::LootSpec,
47    make_case_elim,
48    resources::Secs,
49    sprites,
50    terrain::Block,
51};
52use common_i18n::Content;
53use hashbrown::HashMap;
54use lazy_static::lazy_static;
55use num_derive::FromPrimitive;
56use serde::{Deserialize, Serialize};
57use std::{
58    borrow::Cow,
59    convert::{Infallible, TryFrom},
60    fmt,
61};
62use strum::EnumIter;
63use vek::*;
64
65/// A sprite that can be deserialized with all its attributes.
66///
67/// Say we have created the sprites:
68/// ```ignore
69/// sprites! {
70///    Furniture = 0 has Ori, MirrorX {
71///       Chair,
72///       Table,
73///    }
74/// }
75/// ```
76/// And given we're deserializing from ron we could deserialize an array
77/// of `StructureSprite` that look like this:
78/// ```ignore
79/// [
80///    // This will be a `SpriteKind::Chair` with default attributes
81///    Chair(),
82///    // This will be a `SpriteKind::Chair` with the given attributes `Ori(2)` and `MirrorX(true)`.
83///    Chair(Ori(2), MirrorX(true)),
84///    // This will be a `SpriteKind::Table` with the given attribute `Ori(2)` and the rest of its
85///    // attributes set to default.
86///    Table(Ori(4)),
87/// ]
88/// ```
89#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize)]
90#[serde(transparent)]
91pub struct StructureSprite(StructureSpriteKind);
92
93impl StructureSprite {
94    /// Assigns this structure sprite to a block.
95    ///
96    /// Returns error if [`Block::try_with_sprite`] fails.
97    pub fn apply_to_block(self, block: Block) -> Result<Block, Block> {
98        self.0.apply_to_block(block)
99    }
100}
101
102sprites! {
103    Void = 0 {
104        Empty = 0,
105    },
106    // Generic collection of sprites, no attributes but anything goes
107    Misc = 1 {
108        Ember      = 0x00,
109        SmokeDummy = 0x01,
110        Bomb       = 0x02,
111        FireBlock  = 0x03, // FireBlock for Burning Buff
112        HotSurface = 0x04,
113        Stones2    = 0x05, // Same as `Stones` but not collectible
114        TrainSmoke = 0x06,
115    },
116    // Furniture. In the future, we might add an attribute to customise material
117    // TODO: Remove sizes and variants, represent with attributes
118    Furniture = 2 has Ori, MirrorX {
119        // Indoor
120        BookshelfArabic    = 0x0D,
121        WallTableArabic    = 0x0E,
122        TableArabicLarge   = 0x0F,
123        TableArabicSmall   = 0x10,
124        CupboardArabic     = 0x11,
125        OvenArabic         = 0x12,
126        CushionArabic      = 0x13,
127        CanapeArabic       = 0x14,
128        Shelf              = 0x15,
129        Planter            = 0x16,
130        BedMesa            = 0x18,
131        WallTableMesa      = 0x19,
132        MirrorMesa         = 0x1A,
133        WardrobeSingleMesa = 0x1B,
134        WardrobeDoubleMesa = 0x1C,
135        CupboardMesa       = 0x1D,
136        TableCoastalLarge  = 0x1E,
137        BenchCoastal       = 0x1F,
138        // Crafting
139        CraftingBench    = 0x20,
140        Forge            = 0x21,
141        Cauldron         = 0x22,
142        Anvil            = 0x23,
143        CookingPot       = 0x24,
144        SpinningWheel    = 0x25,
145        TanningRack      = 0x26,
146        Loom             = 0x27,
147        DismantlingBench = 0x28,
148        RepairBench      = 0x29,
149        // Uncollectable containers
150        Barrel            = 0x30,
151        CrateBlock        = 0x31,
152        // Wall
153        HangingBasket     = 0x50,
154        HangingSign       = 0x51,
155        ChristmasOrnament = 0x52,
156        ChristmasWreath   = 0x53,
157        WallLampWizard    = 0x54,
158        WallLamp          = 0x55,
159        WallLampSmall     = 0x56,
160        WallSconce        = 0x57,
161        DungeonWallDecor  = 0x58,
162        WallLampMesa      = 0x59,
163        // Outdoor
164        Tent          = 0x60,
165        Bedroll       = 0x61,
166        BedrollSnow   = 0x62,
167        BedrollPirate = 0x63,
168        Sign          = 0x64,
169        Helm          = 0x65,
170        // Misc
171        Scarecrow      = 0x70,
172        FountainArabic = 0x71,
173        Hearth         = 0x72,
174        ChestWoodDouble= 0x73,
175        LanternpostWoodUpper = 0x74,
176        LanternpostWoodBase = 0x75,
177        LampMetalBase = 0x76,
178        BlacksmithBellows = 0x77,
179        CarpenterTable = 0x78,
180        CarpenterCrateWoodS = 0x79,
181        CarpenterCrateWoodL = 0x7A,
182        CarpenterToolsWall = 0x7B,
183        CarpenterLogCutter = 0x7C,
184        BarrelWoodCoal = 0x7D,
185        BarrelWoodWater = 0x7E,
186        BasketWovenL = 0x7F,
187        BasketWovenM = 0x80,
188        BasketWovenS = 0x81,
189        BonfireMLit = 0x82,
190        BonfireMUnlit = 0x83,
191        BucketWoodM = 0x84,
192        MirrorWoodM = 0x85,
193        SackLeatherM = 0x86,
194        TrophyframeWoodBear = 0x87,
195        TrophyframeWoodDeer = 0x88,
196        JugClayM = 0x89,
197        LogsWoodBranchS = 0x8A,
198        DiningtableWoodCorner = 0x8B,
199        DiningtableWoodBody = 0x8C,
200        BenchWoodEnd = 0x8D,
201        BenchWoodMiddle = 0x8E,
202        LogsWoodCoreEnd = 0x8F,
203        LogsWoodCoreMiddle = 0x90,
204        LogsWoodBarkEnd = 0x91,
205        LogsWoodBarkMiddle = 0x92,
206        LogsWoodBranchEnd = 0x93,
207        LogsWoodBranchMiddle = 0x94,
208        SeatWoodBlueMiddle = 0x95,
209        SeatWoodBlueSide = 0x96,
210        RopeCoilM = 0x97,
211        BedWoodWoodlandHead = 0x99,
212        BedWoodWoodlandMiddle = 0x9A,
213        BedWoodWoodlandTail = 0x9B,
214        BenchWoodWoodlandGreen1 = 0x9C,
215        BenchWoodWoodlandGreen2 = 0x9D,
216        BenchWoodWoodlandGreen3 = 0x9E,
217        BenchWoodWoodland = 0xA0,
218        ChairWoodWoodland = 0xA1,
219        ChairWoodWoodland2 = 0xA2,
220        CoatrackMetalWoodland = 0xA3,
221        CoatrackWoodWoodland = 0xA4,
222        DrawerWoodWoodlandL1 = 0xA5,
223        DrawerWoodWoodlandL2 = 0xA6,
224        DrawerWoodWoodlandM1 = 0xA7,
225        DrawerWoodWoodlandM2 = 0xA8,
226        DrawerWoodWoodlandS = 0xA9,
227        HandCartWoodHead = 0xAA,
228        HandCartWoodMiddle = 0xAB,
229        HandCartWoodTail = 0xAC,
230        FlowerpotWoodWoodlandS = 0xAD,
231        DiningtableWoodWoodlandRound = 0xAE,
232        DiningtableWoodWoodlandSquare = 0xAF,
233        TableWoodFancyWoodlandCorner = 0xB0,
234        TableWoodFancyWoodlandBody = 0xB1,
235        WardrobedoubleWoodWoodland = 0xB2,
236        WardrobedoubleWoodWoodland2 = 0xB3,
237        WardrobesingleWoodWoodland = 0xB4,
238        WardrobesingleWoodWoodland2 = 0xB5,
239        BedCliffHead = 0xB6,
240        BedCliffMiddle = 0xB7,
241        BedCliffTail = 0xB8,
242        BedCoastalHead = 0xB9,
243        BedCoastalMiddle = 0xBA,
244        BedCoastalTail = 0xBB,
245        BedDesertHead = 0xBC,
246        BedDesertMiddle = 0xBD,
247        BedDesertTail = 0xBE,
248        BedSavannahHead = 0xBF,
249        BedSavannahMiddle = 0xC0,
250        BedSavannahTail = 0xC1,
251        Ladder = 0xC2,
252        BookshelfEnd = 0xC3,
253        BookshelfMiddle = 0xC4,
254        HandrailWoodWoodlandBase = 0xC5,
255        HandrailWoodWoodlandMiddle = 0xC6,
256        HandrailWoodWoodlandTop = 0xC7,
257        BroomWoodWoodlandBlue = 0xC8,
258        ShovelWoodWoodlandGreen = 0xC9,
259        PitchforkWoodWoodlandGreen = 0xCA,
260        RakeWoodWoodland = 0xCB,
261        FenceWoodGateWoodland = 0xCC,
262        Hay = 0xCD,
263    },
264    // Sprites representing plants that may grow over time (this does not include plant parts, like fruit).
265    Plant = 3 has Growth, Owned, SnowCovered, Collectable {
266        // Cacti
267        BarrelCactus    = 0x00,
268        RoundCactus     = 0x01,
269        ShortCactus     = 0x02,
270        MedFlatCactus   = 0x03,
271        ShortFlatCactus = 0x04,
272        LargeCactus     = 0x05,
273        TallCactus      = 0x06,
274        // Flowers
275        BlueFlower    = 0x10,
276        PinkFlower    = 0x11,
277        PurpleFlower  = 0x12,
278        RedFlower     = 0x13,
279        WhiteFlower   = 0x14,
280        YellowFlower  = 0x15,
281        Sunflower     = 0x16,
282        Moonbell      = 0x17,
283        Pyrebloom     = 0x18,
284        LushFlower    = 0x19,
285        LanternFlower = 0x1A,
286        // Grasses, ferns, and other 'wild' plants/fungi
287        // TODO: remove sizes, make part of the `Growth` attribute
288        LongGrass          = 0x20,
289        MediumGrass        = 0x21,
290        ShortGrass         = 0x22,
291        Fern               = 0x23,
292        LargeGrass         = 0x24,
293        Reed               = 0x25,
294        TaigaGrass         = 0x26,
295        GrassBlue          = 0x27,
296        SavannaGrass       = 0x28,
297        TallSavannaGrass   = 0x29,
298        RedSavannaGrass    = 0x2A,
299        SavannaBush        = 0x2B,
300        Welwitch           = 0x2C,
301        LeafyPlant         = 0x2D,
302        DeadBush           = 0x2E,
303        JungleFern         = 0x2F,
304        GrassBlueShort     = 0x30,
305        GrassBlueMedium    = 0x31,
306        GrassBlueLong      = 0x32,
307        CavernLillypadBlue = 0x33,
308        EnsnaringVines     = 0x34,
309        LillyPads          = 0x35,
310        JungleLeafyPlant   = 0x36,
311        JungleRedGrass     = 0x37,
312        LanternPlant       = 0x38,
313        SporeReed          = 0x39,
314        DeadPlant          = 0x3A,
315        // Crops, berries, and fungi
316        Corn          = 0x41,
317        WheatYellow   = 0x42,
318        WheatGreen    = 0x43, // TODO: Remove `WheatGreen`, make part of the `Growth` attribute
319        LingonBerry   = 0x44,
320        Blueberry     = 0x45,
321        Lettuce       = 0x46,
322        Pumpkin       = 0x47,
323        Carrot        = 0x48,
324        Tomato        = 0x49,
325        Radish        = 0x4A,
326        Turnip        = 0x4B,
327        Flax          = 0x4C,
328        Mushroom      = 0x4D,
329        CaveMushroom  = 0x4E,
330        Cotton        = 0x4F,
331        WildFlax      = 0x50,
332        SewerMushroom = 0x51,
333        LushMushroom  = 0x52,
334        RockyMushroom = 0x53,
335        GlowMushroom  = 0x54,
336        // Seaweeds, corals, and other underwater plants
337        StonyCoral       = 0x61,
338        SoftCoral        = 0x62,
339        SeaweedTemperate = 0x63,
340        SeaweedTropical  = 0x64,
341        GiantKelp        = 0x65,
342        BullKelp         = 0x66,
343        WavyAlgae        = 0x67,
344        SeaGrapes        = 0x68,
345        MermaidsFan      = 0x69,
346        SeaAnemone       = 0x6A,
347        Seagrass         = 0x6B,
348        RedAlgae         = 0x6C,
349        // Danglying ceiling plants/fungi
350        Liana                   = 0x71,
351        MycelBlue               = 0x72,
352        CeilingMushroom         = 0x73,
353        Mold                    = 0x74,
354        Root                    = 0x75,
355        CeilingLanternPlant     = 0x76,
356        CeilingLanternFlower    = 0x77,
357        CeilingJungleLeafyPlant = 0x78,
358    },
359    // Solid resources
360    // TODO: Remove small variants, make deposit size be an attribute
361    Resource = 4 has Owned, SnowCovered {
362        // Gems and ores
363        // Woods and twigs
364        Twigs     = 0x00,
365        Wood      = 0x01,
366        Bamboo    = 0x02,
367        Hardwood  = 0x03,
368        Ironwood  = 0x04,
369        Frostwood = 0x05,
370        Eldwood   = 0x06,
371        // Other
372        Apple       = 0x20,
373        Coconut     = 0x21,
374        Stones      = 0x22,
375        Seashells   = 0x23,
376        Beehive     = 0x24,
377        Bowl        = 0x25,
378        PotionMinor = 0x26,
379        //= 0x27,
380        VialEmpty   = 0x28,
381    },
382    MineableResource = 5 has Damage {
383        Amethyst      = 0x00,
384        Ruby          = 0x01,
385        Sapphire      = 0x02,
386        Emerald       = 0x03,
387        Topaz         = 0x04,
388        Diamond       = 0x05,
389        Bloodstone    = 0x06,
390        Coal          = 0x07,
391        Cobalt        = 0x08,
392        Copper        = 0x09,
393        Iron          = 0x0A,
394        Tin           = 0x0B,
395        Silver        = 0x0C,
396        Gold          = 0x0D,
397        Velorite      = 0x0E,
398        VeloriteFrag  = 0x0F,
399        Mud           = 0x10,
400        Grave         = 0x11,
401    },
402    // Structural elements including doors and building parts
403    Structural = 6 has Ori {
404        // Doors and keyholes
405        Door         = 0x00,
406        DoorDark     = 0x01,
407        DoorWide     = 0x02,
408        BoneKeyhole  = 0x03,
409        BoneKeyDoor  = 0x04,
410        Keyhole      = 0x05,
411        KeyDoor      = 0x06,
412        GlassKeyhole = 0x07,
413        KeyholeBars  = 0x08,
414        HaniwaKeyDoor = 0x09,
415        HaniwaKeyhole = 0x0A,
416        TerracottaKeyDoor = 0x0B,
417        TerracottaKeyhole = 0x0C,
418        SahaginKeyhole = 0x0D,
419        SahaginKeyDoor = 0x0E,
420        VampireKeyDoor = 0x0F,
421        VampireKeyhole = 0x10,
422        MyrmidonKeyDoor = 0x11,
423        MyrmidonKeyhole = 0x12,
424        MinotaurKeyhole = 0x13,
425
426        // Windows
427        Window1      = 0x14,
428        Window2      = 0x15,
429        Window3      = 0x16,
430        Window4      = 0x17,
431        WitchWindow  = 0x18,
432        WindowArabic = 0x19,
433        // Walls
434        GlassBarrier    = 0x20,
435        SeaDecorBlock   = 0x21,
436        CliffDecorBlock = 0x22,
437        MagicalBarrier  = 0x23,
438        OneWayWall      = 0x24,
439        // Gates and grates
440        SeaDecorWindowHor = 0x30,
441        SeaDecorWindowVer = 0x31,
442        DropGate          = 0x32,
443        DropGateBottom    = 0x33,
444        WoodBarricades    = 0x34,
445        // Misc
446        Rope          = 0x40,
447        SeaDecorChain = 0x41,
448        IronSpike     = 0x42,
449        DoorBars      = 0x43,
450        HaniwaTrap    = 0x44,
451        HaniwaTrapTriggered = 0x45,
452        TerracottaStatue = 0x46,
453        TerracottaBlock = 0x47,
454        MetalChain = 0x48,
455        Bell = 0x49,
456    },
457    // Decorative items, both natural and artificial
458    Decor = 7 has Ori {
459        // Natural
460        Bones          = 0x00,
461        IceCrystal     = 0x01,
462        GlowIceCrystal = 0x02,
463        CrystalHigh    = 0x03,
464        CrystalLow     = 0x04,
465        UnderwaterVent = 0x05,
466        SeaUrchin      = 0x06,
467        IceSpike       = 0x07,
468        Orb            = 0x08,
469        EnsnaringWeb   = 0x09,
470        DiamondLight   = 0x0A,
471
472        // Artificial
473        Gravestone        = 0x10,
474        Melon             = 0x11,
475        ForgeTools        = 0x12,
476        JugAndBowlArabic  = 0x13,
477        JugArabic         = 0x14,
478        DecorSetArabic    = 0x15,
479        SepareArabic      = 0x16,
480        Candle            = 0x17,
481        SmithingTable     = 0x18,
482        Forge0            = 0x19,
483        GearWheel0        = 0x1A,
484        Quench0           = 0x1B,
485        SeaDecorEmblem    = 0x1C,
486        SeaDecorPillar    = 0x1D,
487        MagicalSeal       = 0x1E,
488        JugAndCupsCoastal = 0x1F,
489    },
490    Lamp = 8 has Ori, LightEnabled {
491        // Standalone lights
492        Lantern         = 0x00,
493        StreetLamp      = 0x01,
494        StreetLampTall  = 0x02,
495        SeashellLantern = 0x03,
496        FireBowlGround  = 0x04,
497        MesaLantern     = 0x05,
498        LanternpostWoodLantern = 0x06,
499        LampMetalShinglesRed = 0x07,
500        LampTerracotta = 0x08,
501        LampMetalShinglesCyan = 0x09,
502        LanternAirshipWallBlackS = 0x0A,
503        LanternAirshipWallBrownS = 0x0B,
504        LanternAirshipWallChestnutS = 0x0C,
505        LanternAirshipWallRedS = 0x0D,
506        LanternAirshipGroundBlackS = 0x0E,
507        LanternAirshipGroundBrownS = 0x0F,
508        LanternAirshipGroundChestnutS = 0x10,
509        LanternAirshipGroundRedS = 0x11,
510    },
511    // These are all expected to return `Some` for `collectible_info`
512    //
513    // NOTE: Collectable attr currently unused, plan is to add collected models for at least some
514    // of these.
515    Container = 9 has Ori, Owned, Collectable {
516        Chest             = 0x00,
517        DungeonChest0     = 0x01,
518        DungeonChest1     = 0x02,
519        DungeonChest2     = 0x03,
520        DungeonChest3     = 0x04,
521        DungeonChest4     = 0x05,
522        DungeonChest5     = 0x06,
523        CoralChest        = 0x07,
524        HaniwaUrn         = 0x08,
525        TerracottaChest   = 0x09,
526        SahaginChest      = 0x0A,
527        CommonLockedChest = 0x0B,
528        ChestBuried       = 0x0C,
529        Crate             = 0x0D,
530        // SLOT           = 0x0E,
531        // SLOT           = 0x0F,
532        WitchChest        = 0x10,
533        PirateChest       = 0x11,
534    },
535    Modular = 10 has Ori, AdjacentType {
536        FenceWoodWoodland = 0x00,
537    }
538}
539
540attributes! {
541    Ori { bits: 3, err: Infallible, from: |bits| Ok(Self(bits as u8)), into: |Ori(x)| x as u16 },
542    MirrorX { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |MirrorX(x)| x as u16 },
543    MirrorY { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |MirrorY(x)| x as u16 },
544    MirrorZ { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |MirrorZ(x)| x as u16 },
545    Growth { bits: 4, err: Infallible, from: |bits| Ok(Self(bits as u8)), into: |Growth(x)| x as u16 },
546    LightEnabled { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |LightEnabled(x)| x as u16 },
547    Collectable { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |Collectable(x)| x as u16 },
548    Damage { bits: 3, err: Infallible, from: |bits| Ok(Self(bits as u8)), into: |Damage(x)| x as u16 },
549    Owned { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |Owned(x)| x as u16 },
550    AdjacentType { bits: 3, err: Infallible, from: |bits| Ok(Self(bits as u8)), into: |AdjacentType(x)| x as u16 },
551    SnowCovered { bits: 1, err: Infallible, from: |bits| Ok(Self(bits == 1)), into: |SnowCovered(x)| x as u16 },
552}
553
554// The orientation of the sprite, 0..16
555#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize)]
556pub struct Ori(pub u8);
557
558#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize)]
559pub struct MirrorX(pub bool);
560
561#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize)]
562pub struct MirrorY(pub bool);
563
564#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize)]
565pub struct MirrorZ(pub bool);
566
567// The growth of the plant, 0..16
568#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
569pub struct Growth(pub u8);
570
571impl Default for Growth {
572    fn default() -> Self { Self(15) }
573}
574
575// Whether a light has been toggled on or off.
576#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
577pub struct LightEnabled(pub bool);
578
579impl Default for LightEnabled {
580    fn default() -> Self { Self(true) }
581}
582
583#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
584pub struct Collectable(pub bool);
585
586impl Default for Collectable {
587    fn default() -> Self { Self(true) }
588}
589
590#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
591pub struct Owned(pub bool);
592
593/** Relative Neighbor Position:
594    an enum to determine the exact sprite for AdjacentType sprites
595    I - Straight - 0
596    L - Corner - 1
597    T - Junction - 2
598    X - Intersection - 3
599    End - single connection - 4
600**/
601
602#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Deserialize, FromPrimitive, Hash)]
603#[repr(u8)]
604pub enum RelativeNeighborPosition {
605    #[default]
606    I,
607    L,
608    T,
609    X,
610    End,
611}
612
613#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize)]
614#[serde(from = "RelativeNeighborPosition")]
615pub struct AdjacentType(pub u8);
616
617impl From<RelativeNeighborPosition> for AdjacentType {
618    fn from(value: RelativeNeighborPosition) -> Self { Self(value as u8) }
619}
620
621impl Default for AdjacentType {
622    fn default() -> Self { Self::from(RelativeNeighborPosition::I) }
623}
624
625// Damage of an ore
626#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, Deserialize)]
627pub struct Damage(pub u8);
628
629// Whether a sprite has snow on it
630#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Deserialize)]
631pub struct SnowCovered(pub bool);
632
633impl SpriteKind {
634    #[inline]
635    //#[tweak_fn]
636    pub fn solid_height(&self) -> Option<f32> {
637        // Beware: the height *must* be <= `MAX_HEIGHT` or the collision system will not
638        // properly detect it!
639        Some(match self {
640            SpriteKind::Bedroll => 0.3,
641            SpriteKind::BedrollSnow => 0.4,
642            SpriteKind::BedrollPirate => 0.3,
643            SpriteKind::Tomato => 1.65,
644            SpriteKind::BarrelCactus => 0.909,
645            SpriteKind::LargeCactus => 3.0,
646            SpriteKind::TallCactus => 2.63,
647            SpriteKind::Scarecrow => 3.0,
648            SpriteKind::Turnip => 0.36,
649            SpriteKind::Pumpkin => 0.81,
650            SpriteKind::Chest => 1.09,
651            SpriteKind::CommonLockedChest
652            | SpriteKind::DungeonChest0
653            | SpriteKind::DungeonChest1
654            | SpriteKind::DungeonChest2
655            | SpriteKind::DungeonChest3
656            | SpriteKind::DungeonChest4
657            | SpriteKind::DungeonChest5
658            | SpriteKind::CoralChest
659            | SpriteKind::HaniwaUrn
660            | SpriteKind::SahaginChest
661            | SpriteKind::TerracottaChest
662            | SpriteKind::WitchChest
663            | SpriteKind::PirateChest => 1.09,
664            SpriteKind::TerracottaStatue => 5.29,
665            SpriteKind::TerracottaBlock => 1.00,
666            // Fence is more than 1.0 to prevent auto block-hopping onto the fence.
667            SpriteKind::FenceWoodWoodland => 1.09,
668            SpriteKind::SeaDecorChain => 1.09,
669            SpriteKind::SeaDecorBlock => 1.00,
670            SpriteKind::SeaDecorWindowHor => 0.55,
671            SpriteKind::SeaDecorWindowVer => 1.09,
672            SpriteKind::SeaDecorPillar => 2.55,
673            SpriteKind::SeashellLantern => 2.09,
674            SpriteKind::MesaLantern => 1.3,
675            SpriteKind::Rope => 1.09,
676            SpriteKind::MetalChain => 1.09,
677            SpriteKind::StreetLamp => 2.65,
678            SpriteKind::Carrot => 0.18,
679            SpriteKind::Radish => 0.18,
680            SpriteKind::FireBowlGround => 0.55,
681            SpriteKind::BedMesa => 0.82,
682            SpriteKind::DungeonWallDecor => 1.0,
683            SpriteKind::Planter => 1.09,
684            SpriteKind::WardrobeSingleMesa => 2.0,
685            SpriteKind::WardrobeDoubleMesa => 2.0,
686            SpriteKind::MirrorMesa => 2.0,
687            SpriteKind::Mud => 0.36,
688            SpriteKind::ChestBuried => 0.91,
689            SpriteKind::StonyCoral => 1.4,
690            SpriteKind::CraftingBench => 1.18,
691            SpriteKind::Forge => 1.818,
692            SpriteKind::Cauldron => 1.27,
693            SpriteKind::SpinningWheel => 1.454,
694            SpriteKind::TanningRack => 1.363,
695            SpriteKind::Loom => 1.545,
696            SpriteKind::Anvil => 1.18,
697            SpriteKind::CookingPot => 1.091,
698            SpriteKind::DismantlingBench => 1.091,
699            SpriteKind::IceSpike => 1.0,
700            SpriteKind::RepairBench => 1.2,
701            SpriteKind::RoundCactus => 0.72,
702            SpriteKind::ShortCactus => 1.36,
703            SpriteKind::MedFlatCactus => 1.36,
704            SpriteKind::ShortFlatCactus => 0.91,
705            SpriteKind::Bell => 1.0,
706            // TODO: Find suitable heights.
707            SpriteKind::Apple
708            | SpriteKind::Beehive
709            | SpriteKind::Velorite
710            | SpriteKind::VeloriteFrag
711            | SpriteKind::Coconut
712            | SpriteKind::StreetLampTall
713            | SpriteKind::Window1
714            | SpriteKind::Window2
715            | SpriteKind::Window3
716            | SpriteKind::Window4
717            | SpriteKind::DropGate
718            | SpriteKind::WitchWindow
719            | SpriteKind::SeaUrchin
720            | SpriteKind::IronSpike
721            | SpriteKind::GlassBarrier
722            | SpriteKind::GlassKeyhole
723            | SpriteKind::Keyhole
724            | SpriteKind::KeyDoor
725            | SpriteKind::BoneKeyhole
726            | SpriteKind::BoneKeyDoor
727            | SpriteKind::HaniwaKeyhole
728            | SpriteKind::HaniwaKeyDoor
729            | SpriteKind::SahaginKeyhole
730            | SpriteKind::SahaginKeyDoor
731            | SpriteKind::VampireKeyhole
732            | SpriteKind::VampireKeyDoor
733            | SpriteKind::HaniwaTrap
734            | SpriteKind::HaniwaTrapTriggered
735            | SpriteKind::TerracottaKeyDoor
736            | SpriteKind::TerracottaKeyhole
737            | SpriteKind::MyrmidonKeyDoor
738            | SpriteKind::MyrmidonKeyhole
739            | SpriteKind::MinotaurKeyhole
740            | SpriteKind::Bomb
741            | SpriteKind::OneWayWall
742            | SpriteKind::DoorBars
743            | SpriteKind::KeyholeBars
744            | SpriteKind::WoodBarricades
745            | SpriteKind::DiamondLight => 1.0,
746            // TODO: Figure out if this should be solid or not.
747            SpriteKind::Shelf => 1.0,
748            SpriteKind::Lantern => 0.9,
749            SpriteKind::CrystalHigh | SpriteKind::CrystalLow => 1.5,
750            SpriteKind::Bloodstone
751            | SpriteKind::Coal
752            | SpriteKind::Cobalt
753            | SpriteKind::Copper
754            | SpriteKind::Iron
755            | SpriteKind::Tin
756            | SpriteKind::Silver
757            | SpriteKind::Gold => 0.6,
758            SpriteKind::EnsnaringVines
759            | SpriteKind::CavernLillypadBlue
760            | SpriteKind::EnsnaringWeb => 0.15,
761            SpriteKind::LillyPads => 0.1,
762            SpriteKind::WindowArabic | SpriteKind::BookshelfArabic => 1.9,
763            SpriteKind::DecorSetArabic => 2.6,
764            SpriteKind::SepareArabic => 2.2,
765            SpriteKind::CushionArabic => 0.4,
766            SpriteKind::JugArabic => 1.4,
767            SpriteKind::TableArabicSmall => 0.9,
768            SpriteKind::TableArabicLarge => 1.0,
769            SpriteKind::TableCoastalLarge => 1.0,
770            SpriteKind::BenchCoastal => 1.0,
771            SpriteKind::CanapeArabic => 1.2,
772            SpriteKind::CupboardArabic => 4.5,
773            SpriteKind::WallTableArabic => 2.3,
774            SpriteKind::JugAndBowlArabic => 1.4,
775            SpriteKind::JugAndCupsCoastal => 1.4,
776            SpriteKind::Melon => 0.7,
777            SpriteKind::OvenArabic => 3.2,
778            SpriteKind::FountainArabic => 2.4,
779            SpriteKind::Hearth => 2.3,
780            SpriteKind::ForgeTools => 2.8,
781            SpriteKind::CliffDecorBlock | SpriteKind::FireBlock => 1.0,
782            SpriteKind::Wood
783            | SpriteKind::Hardwood
784            | SpriteKind::Ironwood
785            | SpriteKind::Frostwood
786            | SpriteKind::Eldwood => 7.0 / 11.0,
787            SpriteKind::Bamboo => 9.0 / 11.0,
788            SpriteKind::MagicalBarrier => 3.0,
789            SpriteKind::MagicalSeal => 1.0,
790            SpriteKind::Helm => 1.909,
791            SpriteKind::Sign => 16.0 / 11.0,
792            SpriteKind::SmithingTable => 13.0 / 11.0,
793            SpriteKind::Forge0 => 17.0 / 11.0,
794            SpriteKind::GearWheel0 => 3.0 / 11.0,
795            SpriteKind::Quench0 => 8.0 / 11.0,
796            SpriteKind::HotSurface => 0.01,
797            SpriteKind::Barrel => 1.0,
798            SpriteKind::CrateBlock => 1.0,
799            SpriteKind::BarrelWoodWater | SpriteKind::BarrelWoodCoal => 1.545,
800            SpriteKind::LanternpostWoodLantern | SpriteKind::LanternpostWoodUpper => 2.000,
801            SpriteKind::LanternpostWoodBase => 3.000,
802            SpriteKind::LampMetalShinglesRed => 1.000,
803            SpriteKind::LampMetalShinglesCyan => 1.000,
804            SpriteKind::LampMetalBase => 2.818,
805            SpriteKind::LampTerracotta => 1.727,
806            SpriteKind::BlacksmithBellows => 0.545,
807            SpriteKind::CarpenterTable => 2.000,
808            SpriteKind::CarpenterCrateWoodS => 0.727,
809            SpriteKind::CarpenterCrateWoodL => 1.273,
810            SpriteKind::CarpenterLogCutter => 1.545,
811            SpriteKind::BasketWovenL | SpriteKind::JugClayM => 1.000,
812            SpriteKind::BasketWovenM => 0.909,
813            SpriteKind::BasketWovenS => 0.818,
814            SpriteKind::BonfireMLit | SpriteKind::BonfireMUnlit => 2.273,
815            SpriteKind::BucketWoodM | SpriteKind::SackLeatherM => 1.091,
816            SpriteKind::MirrorWoodM => 1.364,
817            SpriteKind::TrophyframeWoodBear => 1.455,
818            SpriteKind::TrophyframeWoodDeer => 1.727,
819            SpriteKind::ChestWoodDouble => 1.182,
820            SpriteKind::DiningtableWoodCorner => 1.273,
821            SpriteKind::DiningtableWoodBody => 1.273,
822            SpriteKind::BenchWoodEnd => 0.636,
823            SpriteKind::BenchWoodMiddle => 0.636,
824            SpriteKind::LogsWoodCoreEnd => 0.818,
825            SpriteKind::LogsWoodCoreMiddle => 0.818,
826            SpriteKind::LogsWoodBarkEnd => 1.091,
827            SpriteKind::LogsWoodBarkMiddle => 1.091,
828            SpriteKind::LogsWoodBranchEnd => 1.091,
829            SpriteKind::LogsWoodBranchMiddle => 1.091,
830            SpriteKind::LogsWoodBranchS => 1.091,
831            SpriteKind::SeatWoodBlueMiddle => 1.818,
832            SpriteKind::SeatWoodBlueSide => 1.818,
833            SpriteKind::LanternAirshipWallBlackS
834            | SpriteKind::LanternAirshipWallBrownS
835            | SpriteKind::LanternAirshipWallChestnutS
836            | SpriteKind::LanternAirshipWallRedS => 1.182,
837            SpriteKind::LanternAirshipGroundBlackS
838            | SpriteKind::LanternAirshipGroundBrownS
839            | SpriteKind::LanternAirshipGroundChestnutS
840            | SpriteKind::LanternAirshipGroundRedS => 0.909,
841            SpriteKind::RopeCoilM => 0.363,
842            SpriteKind::BedCliffHead => 0.636,
843            SpriteKind::BedCliffMiddle => 0.636,
844            SpriteKind::BedCliffTail => 0.636,
845            SpriteKind::BedCoastalHead => 0.636,
846            SpriteKind::BedCoastalMiddle => 0.636,
847            SpriteKind::BedCoastalTail => 0.636,
848            SpriteKind::BedDesertHead => 0.545,
849            SpriteKind::BedDesertMiddle => 0.545,
850            SpriteKind::BedDesertTail => 0.545,
851            SpriteKind::BedSavannahHead => 0.545,
852            SpriteKind::BedSavannahMiddle => 0.545,
853            SpriteKind::BedSavannahTail => 0.545,
854            SpriteKind::BedWoodWoodlandHead => 0.727,
855            SpriteKind::BedWoodWoodlandMiddle => 0.727,
856            SpriteKind::BedWoodWoodlandTail => 0.727,
857            SpriteKind::BookshelfEnd => 3.0,
858            SpriteKind::BookshelfMiddle => 3.0,
859            SpriteKind::BenchWoodWoodlandGreen1 => 1.545,
860            SpriteKind::BenchWoodWoodlandGreen2 => 1.545,
861            SpriteKind::BenchWoodWoodlandGreen3 => 1.545,
862            SpriteKind::BenchWoodWoodland => 1.545,
863            SpriteKind::ChairWoodWoodland => 1.636,
864            SpriteKind::ChairWoodWoodland2 => 1.727,
865            SpriteKind::CoatrackMetalWoodland => 2.364,
866            SpriteKind::CoatrackWoodWoodland => 2.364,
867            SpriteKind::Crate => 0.909,
868            SpriteKind::DrawerWoodWoodlandS => 1.000,
869            SpriteKind::DrawerWoodWoodlandM1 => 0.909,
870            SpriteKind::DrawerWoodWoodlandM2 => 0.909,
871            SpriteKind::DrawerWoodWoodlandL1 => 1.273,
872            SpriteKind::DrawerWoodWoodlandL2 => 1.273,
873            SpriteKind::DiningtableWoodWoodlandRound => 1.273,
874            SpriteKind::DiningtableWoodWoodlandSquare => 1.273,
875            SpriteKind::TableWoodFancyWoodlandCorner => 1.273,
876            SpriteKind::TableWoodFancyWoodlandBody => 1.273,
877            SpriteKind::WardrobesingleWoodWoodland => 2.364,
878            SpriteKind::WardrobesingleWoodWoodland2 => 2.364,
879            SpriteKind::WardrobedoubleWoodWoodland => 2.364,
880            SpriteKind::WardrobedoubleWoodWoodland2 => 2.364,
881            SpriteKind::FlowerpotWoodWoodlandS => 0.455,
882            SpriteKind::HandCartWoodHead => 1.091,
883            SpriteKind::HandCartWoodMiddle => 1.091,
884            SpriteKind::HandCartWoodTail => 1.091,
885            SpriteKind::HandrailWoodWoodlandBase | SpriteKind::HandrailWoodWoodlandMiddle => 1.727,
886            SpriteKind::HandrailWoodWoodlandTop => 1.181,
887            SpriteKind::Hay => 1.09,
888            _ => return None,
889        })
890    }
891
892    pub fn valid_collision_dir(
893        &self,
894        entity_aabb: Aabb<f32>,
895        block_aabb: Aabb<f32>,
896        move_dir: Vec3<f32>,
897        parent: &Block,
898    ) -> bool {
899        match self {
900            SpriteKind::OneWayWall => {
901                // Find the intrusion vector of the collision
902                let dir = entity_aabb.collision_vector_with_aabb(block_aabb);
903
904                // Determine an appropriate resolution vector (i.e: the minimum distance
905                // needed to push out of the block)
906                let max_axis = dir.map(|e| e.abs()).reduce_partial_min();
907                let resolve_dir = -dir.map(|e| {
908                    if e.abs().to_bits() == max_axis.to_bits() {
909                        e.signum()
910                    } else {
911                        0.0
912                    }
913                });
914
915                let is_moving_into = move_dir.dot(resolve_dir) <= 0.0;
916
917                is_moving_into
918                    && parent.get_attr().is_ok_and(|Ori(ori)| {
919                        Vec2::new(
920                            0.0,
921                            parent.get_attr::<MirrorY>().map_or(1.0, |m| match m.0 {
922                                true => -1.0,
923                                false => 1.0,
924                            }),
925                        )
926                        .rotated_z(std::f32::consts::PI * 0.25 * ori as f32)
927                        .with_z(0.0)
928                        .map2(resolve_dir, |e, r| (e - r).abs() < 0.1)
929                        .reduce_and()
930                    })
931            },
932            _ => true,
933        }
934    }
935
936    /// What loot table would collecting this sprite draw from, by default?
937    ///
938    /// NOTE: `Item::try_reclaim_from_block` is what you probably looking for
939    /// instead.
940    ///
941    /// `None` = block cannot be collected.
942    /// `Some(None)` = block can be collected, but does not give back an item.
943    /// `Some(Some(_))` = block can be collected and gives back an item.
944    #[inline]
945    pub fn default_loot_spec(&self) -> Option<Option<LootSpec<&'static str>>> {
946        let item = LootSpec::Item;
947        let table = LootSpec::LootTable;
948        Some(Some(match self {
949            SpriteKind::Apple => item("common.items.food.apple"),
950            SpriteKind::Mushroom => item("common.items.food.mushroom"),
951            SpriteKind::Velorite => item("common.items.mineral.ore.velorite"),
952            SpriteKind::VeloriteFrag => item("common.items.mineral.ore.veloritefrag"),
953            //SpriteKind::BlueFlower => item("common.items.flowers.blue"),
954            //SpriteKind::PinkFlower => item("common.items.flowers.pink"),
955            //SpriteKind::PurpleFlower => item("common.items.flowers.purple"),
956            SpriteKind::RedFlower => item("common.items.flowers.red"),
957            //SpriteKind::WhiteFlower => item("common.items.flowers.white"),
958            //SpriteKind::YellowFlower => item("common.items.flowers.yellow"),
959            SpriteKind::Sunflower => item("common.items.flowers.sunflower"),
960            //SpriteKind::LongGrass => item("common.items.grasses.long"),
961            //SpriteKind::MediumGrass => item("common.items.grasses.medium"),
962            //SpriteKind::ShortGrass => item("common.items.grasses.short"),
963            SpriteKind::Lettuce => item("common.items.food.lettuce"),
964            SpriteKind::Coconut => item("common.items.food.coconut"),
965            SpriteKind::Beehive => item("common.items.crafting_ing.honey"),
966            SpriteKind::Stones => item("common.items.crafting_ing.stones"),
967            SpriteKind::Twigs => item("common.items.crafting_ing.twigs"),
968            SpriteKind::VialEmpty => item("common.items.crafting_ing.empty_vial"),
969            SpriteKind::Bowl => item("common.items.crafting_ing.bowl"),
970            SpriteKind::PotionMinor => item("common.items.consumable.potion_minor"),
971            SpriteKind::Amethyst => item("common.items.mineral.gem.amethyst"),
972            SpriteKind::Ruby => item("common.items.mineral.gem.ruby"),
973            SpriteKind::Diamond => item("common.items.mineral.gem.diamond"),
974            SpriteKind::Sapphire => item("common.items.mineral.gem.sapphire"),
975            SpriteKind::Topaz => item("common.items.mineral.gem.topaz"),
976            SpriteKind::Emerald => item("common.items.mineral.gem.emerald"),
977            SpriteKind::Bloodstone => item("common.items.mineral.ore.bloodstone"),
978            SpriteKind::Coal => item("common.items.mineral.ore.coal"),
979            SpriteKind::Cobalt => item("common.items.mineral.ore.cobalt"),
980            SpriteKind::Copper => item("common.items.mineral.ore.copper"),
981            SpriteKind::Iron => item("common.items.mineral.ore.iron"),
982            SpriteKind::Tin => item("common.items.mineral.ore.tin"),
983            SpriteKind::Silver => item("common.items.mineral.ore.silver"),
984            SpriteKind::Gold => item("common.items.mineral.ore.gold"),
985            SpriteKind::Cotton => item("common.items.crafting_ing.cotton_boll"),
986            SpriteKind::Moonbell => item("common.items.flowers.moonbell"),
987            SpriteKind::Pyrebloom => item("common.items.flowers.pyrebloom"),
988            SpriteKind::WildFlax => item("common.items.flowers.wild_flax"),
989            SpriteKind::Seashells => item("common.items.crafting_ing.seashells"),
990            SpriteKind::RoundCactus => item("common.items.crafting_ing.cactus"),
991            SpriteKind::ShortFlatCactus => item("common.items.crafting_ing.cactus"),
992            SpriteKind::MedFlatCactus => item("common.items.crafting_ing.cactus"),
993            SpriteKind::Bomb => item("common.items.utility.bomb"),
994            SpriteKind::Chest => table("common.loot_tables.sprite.chest"),
995            SpriteKind::DungeonChest0 => table("common.loot_tables.dungeon.gnarling.chest"),
996            SpriteKind::DungeonChest1 => table("common.loot_tables.dungeon.adlet.chest"),
997            SpriteKind::DungeonChest2 => table("common.loot_tables.dungeon.sahagin.chest"),
998            SpriteKind::DungeonChest3 => table("common.loot_tables.dungeon.haniwa.chest"),
999            SpriteKind::DungeonChest4 => table("common.loot_tables.dungeon.myrmidon.chest"),
1000            SpriteKind::DungeonChest5 => table("common.loot_tables.dungeon.cultist.chest"),
1001            SpriteKind::CoralChest => table("common.loot_tables.dungeon.sea_chapel.chest_coral"),
1002            SpriteKind::HaniwaUrn => table("common.loot_tables.dungeon.haniwa.key"),
1003            SpriteKind::TerracottaChest => {
1004                table("common.loot_tables.dungeon.terracotta.chest_terracotta")
1005            },
1006            SpriteKind::SahaginChest => table("common.loot_tables.dungeon.sahagin.key_chest"),
1007            SpriteKind::CommonLockedChest => table("common.loot_tables.dungeon.sahagin.chest"),
1008            SpriteKind::ChestBuried => table("common.loot_tables.sprite.chest-buried"),
1009            SpriteKind::Crate => table("common.loot_tables.sprite.crate"),
1010            SpriteKind::Mud => table("common.loot_tables.sprite.mud"),
1011            SpriteKind::Grave => table("common.loot_tables.sprite.mud"),
1012            SpriteKind::Wood => item("common.items.log.wood"),
1013            SpriteKind::Bamboo => item("common.items.log.bamboo"),
1014            SpriteKind::Hardwood => item("common.items.log.hardwood"),
1015            SpriteKind::Ironwood => item("common.items.log.ironwood"),
1016            SpriteKind::Frostwood => item("common.items.log.frostwood"),
1017            SpriteKind::Eldwood => item("common.items.log.eldwood"),
1018            // TODO: why does this have a loot table?
1019            SpriteKind::MagicalBarrier => table("common.loot_tables.sprite.chest"),
1020            SpriteKind::WitchChest => table("common.loot_tables.spot.witch"),
1021            SpriteKind::PirateChest => table("common.loot_tables.spot.buccaneer"),
1022            SpriteKind::Keyhole
1023            | SpriteKind::BoneKeyhole
1024            | SpriteKind::HaniwaKeyhole
1025            | SpriteKind::VampireKeyhole
1026            | SpriteKind::GlassKeyhole
1027            | SpriteKind::KeyholeBars
1028            | SpriteKind::SahaginKeyhole
1029            | SpriteKind::TerracottaKeyhole
1030            | SpriteKind::MyrmidonKeyhole
1031            | SpriteKind::MinotaurKeyhole => {
1032                return Some(None);
1033            },
1034            _ => return None,
1035        }))
1036    }
1037
1038    /// Is this sprite *expected* to be picked up?
1039    ///
1040    /// Note, this will `Some(_)` even when the `Collectable` attr is `false`.
1041    ///
1042    /// * `None` means sprite can't be collected.
1043    /// * `Some(None)` means sprite can be collected without any mine tool.
1044    /// * `Some(Some(_))` means sprite can be collected but requires a tool.
1045    #[inline]
1046    pub fn collectible_info(&self) -> Option<Option<ToolKind>> {
1047        self.default_loot_spec().map(|_| self.mine_tool())
1048    }
1049
1050    /// Should the sprite behave like a container?
1051    ///
1052    /// That means:
1053    /// * The sprite is collectible (checked by test).
1054    /// * The sprite is not explodable.
1055    /// * `SpriteInteractKind::Chest` is used in the interaction character state
1056    ///   when collecting.
1057    /// * `should_drop_mystery` returns `true`.
1058    /// * Structure tests allows SpriteCfg.loot_table to be set for this sprite.
1059    ///
1060    /// If you just asking where you can collect this sprite without any tool,
1061    /// use [`Block::is_directly_collectible`].
1062    ///
1063    /// Implicit invariant of this method is that only sprites listed here
1064    /// are expected to use SpriteCfg.loot_table because that needs
1065    /// [`SpriteKind::should_drop_mystery`] to be `true` to avoid displaying the
1066    /// `default_loot_spec` items.
1067    #[inline]
1068    pub fn is_defined_as_container(&self) -> bool { self.category() == Category::Container }
1069
1070    /// Does this drop random items or potentially have a a custom loot_table in
1071    /// the SpriteCfg.
1072    ///
1073    /// This acts as a hint to avoid displaying the items from
1074    /// `Item::try_reclaim_from_block`.
1075    ///
1076    /// Some items may drop random items, yet aren't containers. So
1077    /// [`SpriteKind::is_defined_as_container()`] alone is insufficient for
1078    /// this.
1079    #[inline]
1080    pub fn should_drop_mystery(&self) -> bool {
1081        self.is_defined_as_container()
1082            || matches!(
1083                self.default_loot_spec(),
1084                Some(Some(LootSpec::LootTable { .. } | LootSpec::Lottery { .. }))
1085            )
1086    }
1087
1088    /// Get the position and direction to mount this sprite if any.
1089    #[inline]
1090    //#[tweak_fn]
1091    pub fn mount_offset(&self) -> Option<(Vec3<f32>, Vec3<f32>)> {
1092        match self {
1093            SpriteKind::ChairWoodWoodland
1094            | SpriteKind::ChairWoodWoodland2
1095            | SpriteKind::BenchWoodWoodlandGreen1
1096            | SpriteKind::BenchWoodWoodlandGreen2
1097            | SpriteKind::BenchWoodWoodlandGreen3
1098            | SpriteKind::BenchWoodWoodland
1099            | SpriteKind::BenchWoodEnd
1100            | SpriteKind::BenchWoodMiddle
1101            | SpriteKind::BenchCoastal => Some((Vec3::new(0.0, 0.0, 0.5), Vec3::unit_x())),
1102            SpriteKind::SeatWoodBlueMiddle | SpriteKind::SeatWoodBlueSide => {
1103                Some((Vec3::new(0.4, 0.0, 0.5), Vec3::unit_x()))
1104            },
1105            SpriteKind::Helm => Some((Vec3::new(0.0, -1.1, 0.0), Vec3::unit_y())),
1106            SpriteKind::BedWoodWoodlandHead
1107            | SpriteKind::BedCliffHead
1108            | SpriteKind::BedDesertHead
1109            | SpriteKind::BedCoastalHead
1110            | SpriteKind::BedSavannahHead => Some((Vec3::new(1.4, 0.0, 0.5), Vec3::unit_x())),
1111            SpriteKind::BedMesa => Some((Vec3::new(0.0, 0.0, 0.6), -Vec3::unit_y())),
1112            SpriteKind::BedrollSnow | SpriteKind::BedrollPirate => {
1113                Some((Vec3::new(0.0, 0.0, 0.1), -Vec3::unit_x()))
1114            },
1115            SpriteKind::Bedroll => Some((Vec3::new(0.0, 0.0, 0.1), Vec3::unit_y())),
1116            _ => None,
1117        }
1118    }
1119
1120    pub fn is_bed(&self) -> bool {
1121        matches!(
1122            self,
1123            SpriteKind::BedWoodWoodlandHead
1124                | SpriteKind::BedMesa
1125                | SpriteKind::BedCliffHead
1126                | SpriteKind::BedCoastalHead
1127                | SpriteKind::BedDesertHead
1128                | SpriteKind::BedSavannahHead
1129                | SpriteKind::Bedroll
1130                | SpriteKind::BedrollSnow
1131                | SpriteKind::BedrollPirate
1132        )
1133    }
1134
1135    #[inline]
1136    pub fn is_mountable(&self) -> bool { self.mount_offset().is_some() }
1137
1138    /// Get the buff provided by the block (currently used for mounting)
1139    #[inline]
1140    pub fn mount_buffs(&self) -> Option<Vec<BuffEffect>> {
1141        match self {
1142            sprite if sprite.is_bed() => Some(vec![BuffEffect {
1143                kind: BuffKind::RestingHeal,
1144                data: BuffData::new(0.02, Some(Secs(1.0))),
1145                cat_ids: Vec::new(),
1146            }]),
1147            _ => None,
1148        }
1149    }
1150
1151    #[inline]
1152    pub fn is_controller(&self) -> bool { matches!(self, SpriteKind::Helm) }
1153
1154    #[inline]
1155    pub fn is_door(&self) -> bool {
1156        matches!(
1157            self,
1158            SpriteKind::Door | SpriteKind::DoorWide | SpriteKind::DoorDark
1159        )
1160    }
1161
1162    /// Which tool (if any) is needed to collect this sprite?
1163    #[inline]
1164    pub fn mine_tool(&self) -> Option<ToolKind> {
1165        match self {
1166            SpriteKind::Velorite
1167            | SpriteKind::VeloriteFrag
1168            // Gems
1169            | SpriteKind::Amethyst
1170            | SpriteKind::Ruby
1171            | SpriteKind::Diamond
1172            | SpriteKind::Sapphire
1173            | SpriteKind::Emerald
1174            | SpriteKind::Topaz
1175            | SpriteKind::Bloodstone
1176            | SpriteKind::Coal
1177            | SpriteKind::Cobalt
1178            | SpriteKind::Copper
1179            | SpriteKind::Iron
1180            | SpriteKind::Tin
1181            | SpriteKind::Silver
1182            | SpriteKind::Gold => Some(ToolKind::Pick),
1183            SpriteKind::Grave | SpriteKind::Mud => Some(ToolKind::Shovel),
1184            _ => None,
1185        }
1186    }
1187
1188    pub fn required_mine_damage(&self) -> Option<u8> {
1189        Some(match self {
1190            SpriteKind::Gold => 6,
1191            SpriteKind::Silver => 6,
1192            SpriteKind::Bloodstone => 6,
1193            SpriteKind::Cobalt => 6,
1194            SpriteKind::Coal => 4,
1195            SpriteKind::Iron => 4,
1196            SpriteKind::Copper => 3,
1197            SpriteKind::Tin => 3,
1198            SpriteKind::Amethyst => 3,
1199            SpriteKind::Ruby => 3,
1200            SpriteKind::Sapphire => 3,
1201            SpriteKind::Emerald => 3,
1202            SpriteKind::Topaz => 3,
1203            SpriteKind::Diamond => 3,
1204            SpriteKind::Velorite => 3,
1205            SpriteKind::VeloriteFrag => 2,
1206            _ => return None,
1207        })
1208    }
1209
1210    /// Defines how much damage it takes for a mined resource to possibly
1211    /// make an extra drop.
1212    pub fn mine_drop_interval(&self) -> u8 {
1213        match self {
1214            SpriteKind::Gold => 3,
1215            SpriteKind::Silver => 3,
1216            SpriteKind::Bloodstone => 3,
1217            SpriteKind::Cobalt => 3,
1218            SpriteKind::Coal => 2,
1219            SpriteKind::Iron => 2,
1220            SpriteKind::Copper => 1,
1221            SpriteKind::Tin => 1,
1222            SpriteKind::Emerald => 3,
1223            SpriteKind::Sapphire => 3,
1224            SpriteKind::Amethyst => 3,
1225            SpriteKind::Topaz => 3,
1226            SpriteKind::Diamond => 3,
1227            SpriteKind::Ruby => 3,
1228            SpriteKind::Velorite => 3,
1229            SpriteKind::VeloriteFrag => 2,
1230            _ => 1,
1231        }
1232    }
1233
1234    /// Requires this item in the inventory to harvest, uses item_definition_id
1235    // TODO: Do we want to consolidate this with mine_tool at all? Main differences
1236    // are that mine tool requires item to be an equippable tool, be equipped, and
1237    // does not consume item while required_item requires that the item be in the
1238    // inventory and will consume the item on collecting the sprite.
1239    pub fn unlock_condition(self, cfg: Option<&SpriteCfg>) -> Option<Cow<'_, UnlockKind>> {
1240        let kind = if let Some(unlock) = cfg.and_then(|cfg| cfg.unlock.as_ref()) {
1241            Cow::Borrowed(unlock)
1242        } else {
1243            Cow::Owned(match self {
1244                SpriteKind::CommonLockedChest => {
1245                    UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(String::from(
1246                        "common.items.utility.lockpick.lockpick_copper",
1247                    )))
1248                },
1249                SpriteKind::SahaginKeyhole => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1250                    String::from("common.items.keys.sahagin_key"),
1251                )),
1252                SpriteKind::BoneKeyhole => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1253                    String::from("common.items.keys.bone_key"),
1254                )),
1255                SpriteKind::HaniwaKeyhole => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1256                    String::from("common.items.keys.haniwa_key"),
1257                )),
1258                SpriteKind::VampireKeyhole => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1259                    String::from("common.items.keys.vampire_key"),
1260                )),
1261                SpriteKind::GlassKeyhole => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1262                    String::from("common.items.keys.glass_key"),
1263                )),
1264                SpriteKind::TerracottaChest => UnlockKind::Consumes(
1265                    ItemDefinitionIdOwned::Simple(String::from(
1266                        "common.items.keys.terracotta_key_chest",
1267                    ))
1268                    .to_owned(),
1269                ),
1270                SpriteKind::TerracottaKeyhole => UnlockKind::Consumes(
1271                    ItemDefinitionIdOwned::Simple(String::from(
1272                        "common.items.keys.terracotta_key_door",
1273                    ))
1274                    .to_owned(),
1275                ),
1276                SpriteKind::MyrmidonKeyhole => UnlockKind::Consumes(
1277                    ItemDefinitionIdOwned::Simple(String::from("common.items.keys.myrmidon_key"))
1278                        .to_owned(),
1279                ),
1280                SpriteKind::MinotaurKeyhole => UnlockKind::Consumes(
1281                    ItemDefinitionIdOwned::Simple(String::from("common.items.keys.minotaur_key"))
1282                        .to_owned(),
1283                ),
1284                SpriteKind::WitchChest => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1285                    String::from("common.items.utility.lockpick.lockpick_cobalt"),
1286                )),
1287                SpriteKind::PirateChest => UnlockKind::Consumes(ItemDefinitionIdOwned::Simple(
1288                    String::from("common.items.utility.lockpick.lockpick_iron"),
1289                )),
1290                _ => return None,
1291            })
1292        };
1293        Some(kind)
1294    }
1295
1296    /// Get the [`Content`] that this sprite is labelled with.
1297    pub fn content(&self, cfg: Option<SpriteCfg>) -> Option<Content> {
1298        cfg.and_then(|cfg| cfg.content)
1299    }
1300
1301    // TODO: phase out use of this method in favour of `sprite.has_attr::<Ori>()`
1302    #[inline]
1303    pub fn has_ori(&self) -> bool { self.category().has_attr::<Ori>() }
1304}
1305
1306impl fmt::Display for SpriteKind {
1307    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) }
1308}
1309
1310use strum::IntoEnumIterator;
1311
1312lazy_static! {
1313    pub static ref SPRITE_KINDS: HashMap<String, SpriteKind> =
1314        SpriteKind::iter().map(|sk| (sk.to_string(), sk)).collect();
1315}
1316
1317impl<'a> TryFrom<&'a str> for SpriteKind {
1318    type Error = ();
1319
1320    #[inline]
1321    fn try_from(s: &'a str) -> Result<Self, Self::Error> { SPRITE_KINDS.get(s).copied().ok_or(()) }
1322}
1323
1324// TODO: Free and Requires are currently unused.
1325#[derive(Clone, Debug, Serialize, Deserialize)]
1326pub enum UnlockKind {
1327    /// The sprite can be freely unlocked without any conditions
1328    Free,
1329    /// The sprite requires that the opening character has a given item in their
1330    /// inventory
1331    Requires(ItemDefinitionIdOwned),
1332    /// The sprite will consume the given item from the opening character's
1333    /// inventory
1334    Consumes(ItemDefinitionIdOwned),
1335}
1336
1337#[derive(Default, Clone, Debug, Serialize, Deserialize)]
1338pub struct SpriteCfg {
1339    /// Signifies that this sprite needs an item to be unlocked.
1340    pub unlock: Option<UnlockKind>,
1341    /// Signifies a text associated with this sprite.
1342    /// This also allows (but not requires) internationalization.
1343    ///
1344    /// Notice boards are an example of sprite that uses this.
1345    pub content: Option<Content>,
1346    /// Signifies a loot table associated with this sprite. The string referes
1347    /// to the loot table asset identifier.
1348    ///
1349    /// Chests are an example of sprite that can use this. For simple sprites
1350    /// like flowers using [`SpriteKind::default_loot_spec`] method is
1351    /// recommended instead.
1352    ///
1353    /// If you place a custom loot table on a sprite, make sure it's listed in
1354    /// [`SpriteKind::is_defined_as_container`], which should be enforced in
1355    /// tests, if possible.
1356    ///
1357    ///`collectible_info` must be `Some` for a sprite to be collectible.
1358    /// Adding a loot table to other sprites will not enable collecting
1359    /// them. `is_defined_as_container` is necessary to avoid displaying
1360    /// items from the default loot table (and all containers are included in
1361    /// `collectible_info`).
1362    ///
1363    /// NOTE: this is sent to the clients, we may potentionally strip this info
1364    /// on sending.
1365    pub loot_table: Option<String>,
1366}
1367
1368#[cfg(test)]
1369mod tests {
1370    use super::*;
1371
1372    #[test]
1373    fn sprite_containers_are_collectible() {
1374        for sprite in SpriteKind::all() {
1375            if sprite.is_defined_as_container() {
1376                assert!(sprite.collectible_info().is_some());
1377            }
1378        }
1379    }
1380
1381    #[test]
1382    fn sprite_conv_kind() {
1383        for sprite in SpriteKind::all() {
1384            let block = Block::air(*sprite);
1385            assert_eq!(block.sprite_category(), Some(sprite.category()));
1386            assert_eq!(block.get_sprite(), Some(*sprite));
1387        }
1388    }
1389
1390    #[test]
1391    fn sprite_attr() {
1392        for category in Category::all() {
1393            if category.has_attr::<Ori>() {
1394                for sprite in category.all_sprites() {
1395                    for i in 0..4 {
1396                        let block = Block::air(*sprite).with_attr(Ori(i)).unwrap();
1397                        assert_eq!(block.get_attr::<Ori>().unwrap(), Ori(i));
1398                        assert_eq!(block.get_sprite(), Some(*sprite));
1399                    }
1400                }
1401            }
1402            if category.has_attr::<Growth>() {
1403                for sprite in category.all_sprites() {
1404                    for i in 0..16 {
1405                        let block = Block::air(*sprite).with_attr(Growth(i)).unwrap();
1406                        assert_eq!(block.get_attr::<Growth>().unwrap(), Growth(i));
1407                        assert_eq!(block.get_sprite(), Some(*sprite));
1408                    }
1409                }
1410            }
1411        }
1412    }
1413}