1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use super::{
    armor,
    tool::{self, AbilityMap, AbilitySpec, Hands, Tool},
    DurabilityMultiplier, Item, ItemBase, ItemDef, ItemDesc, ItemKind, ItemTag, Material, Quality,
    ToolKind,
};
use crate::{
    assets::{self, Asset, AssetExt, AssetHandle},
    recipe,
};
use common_base::dev_panic;
use hashbrown::HashMap;
use lazy_static::lazy_static;
use rand::{prelude::SliceRandom, Rng};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, sync::Arc};

// Macro instead of constant to work with concat! macro.
// DO NOT CHANGE. THIS PREFIX AFFECTS PERSISTENCE AND IF CHANGED A MIGRATION
// MUST BE PERFORMED.
#[macro_export]
macro_rules! modular_item_id_prefix {
    () => {
        "veloren.core.pseudo_items.modular."
    };
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MaterialStatManifest {
    tool_stats: HashMap<String, tool::Stats>,
    armor_stats: HashMap<String, armor::Stats>,
}

impl MaterialStatManifest {
    pub fn load() -> AssetHandle<Self> { Self::load_expect("common.material_stats_manifest") }

    pub fn armor_stats(&self, key: &str) -> Option<armor::Stats> {
        self.armor_stats.get(key).copied()
    }

    #[doc(hidden)]
    /// needed for tests to load it without actual assets
    pub fn with_empty() -> Self {
        Self {
            tool_stats: HashMap::default(),
            armor_stats: HashMap::default(),
        }
    }
}

// This could be a Compound that also loads the keys, but the RecipeBook
// Compound impl already does that, so checking for existence here is redundant.
impl Asset for MaterialStatManifest {
    type Loader = assets::RonLoader;

    const EXTENSION: &'static str = "ron";
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum ModularBase {
    Tool,
}

impl ModularBase {
    // DO NOT CHANGE. THIS IS A PERSISTENCE RELATED FUNCTION. MUST MATCH THE
    // FUNCTION BELOW.
    pub fn pseudo_item_id(&self) -> &str {
        match self {
            ModularBase::Tool => concat!(modular_item_id_prefix!(), "tool"),
        }
    }

    // DO NOT CHANGE. THIS IS A PERSISTENCE RELATED FUNCTION. MUST MATCH THE
    // FUNCTION ABOVE.
    pub fn load_from_pseudo_id(id: &str) -> Self {
        match id {
            concat!(modular_item_id_prefix!(), "tool") => ModularBase::Tool,
            _ => panic!("Attempted to load a non existent pseudo item: {}", id),
        }
    }

    fn resolve_hands(components: &[Item]) -> Hands {
        // Checks if weapon has components that restrict hands to two. Restrictions to
        // one hand or no restrictions default to one-handed weapon.
        // Note: Hand restriction here will never conflict on components
        // TODO: Maybe look into adding an assert at some point?
        let hand_restriction = components.iter().find_map(|comp| match &*comp.kind() {
            ItemKind::ModularComponent(mc) => match mc {
                ModularComponent::ToolPrimaryComponent {
                    hand_restriction, ..
                }
                | ModularComponent::ToolSecondaryComponent {
                    hand_restriction, ..
                } => *hand_restriction,
            },
            _ => None,
        });
        // In the event of no hand restrictions on the components, default to one handed
        hand_restriction.unwrap_or(Hands::One)
    }

    #[inline(never)]
    pub(super) fn kind(
        &self,
        components: &[Item],
        msm: &MaterialStatManifest,
        durability_multiplier: DurabilityMultiplier,
    ) -> Cow<ItemKind> {
        let toolkind = components
            .iter()
            .find_map(|comp| match &*comp.kind() {
                ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent {
                    toolkind,
                    ..
                }) => Some(*toolkind),
                _ => None,
            })
            .unwrap_or(ToolKind::Empty);

        let stats: tool::Stats = components
            .iter()
            .filter_map(|comp| {
                if let ItemKind::ModularComponent(mod_comp) = &*comp.kind() {
                    mod_comp.tool_stats(comp.components(), msm)
                } else {
                    None
                }
            })
            .fold(tool::Stats::one(), |a, b| a * b)
            * durability_multiplier;

        match self {
            ModularBase::Tool => Cow::Owned(ItemKind::Tool(Tool::new(
                toolkind,
                Self::resolve_hands(components),
                stats,
            ))),
        }
    }

    /// Modular weapons are named as "{Material} {Weapon}" where {Weapon} is
    /// from the damage component used and {Material} is from the material
    /// the damage component is created from.
    pub fn generate_name(&self, components: &[Item]) -> Cow<str> {
        match self {
            ModularBase::Tool => {
                let name = components
                    .iter()
                    .find_map(|comp| match &*comp.kind() {
                        ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent {
                            weapon_name,
                            ..
                        }) => {
                            let material_name = comp
                                .components()
                                .iter()
                                .find_map(|mat| match mat.kind() {
                                    #[allow(deprecated)]
                                    Cow::Owned(ItemKind::Ingredient { descriptor, .. }) => {
                                        Some(Cow::Owned(descriptor))
                                    },
                                    #[allow(deprecated)]
                                    Cow::Borrowed(ItemKind::Ingredient { descriptor, .. }) => {
                                        Some(Cow::Borrowed(descriptor.as_str()))
                                    },
                                    _ => None,
                                })
                                .unwrap_or_else(|| "Modular".into());
                            Some(format!(
                                "{} {}",
                                material_name,
                                weapon_name.resolve_name(Self::resolve_hands(components))
                            ))
                        },
                        _ => None,
                    })
                    .unwrap_or_else(|| "Modular Weapon".to_owned());
                Cow::Owned(name)
            },
        }
    }

    pub fn compute_quality(&self, components: &[Item]) -> Quality {
        components
            .iter()
            .fold(Quality::MIN, |a, b| a.max(b.quality()))
    }

    pub fn ability_spec(&self, components: &[Item]) -> Option<Cow<AbilitySpec>> {
        match self {
            ModularBase::Tool => components.iter().find_map(|comp| match &*comp.kind() {
                ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent {
                    toolkind,
                    ..
                }) => Some(Cow::Owned(AbilitySpec::Tool(*toolkind))),
                _ => None,
            }),
        }
    }

    pub fn generate_tags(&self, components: &[Item]) -> Vec<ItemTag> {
        match self {
            ModularBase::Tool => {
                if let Some(comp) = components.iter().find(|comp| {
                    matches!(
                        &*comp.kind(),
                        ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent { .. })
                    )
                }) {
                    if let Some(material) =
                        comp.components()
                            .iter()
                            .find_map(|comp| match &*comp.kind() {
                                ItemKind::Ingredient { .. } => {
                                    comp.tags().into_iter().find_map(|tag| match tag {
                                        ItemTag::Material(material) => Some(material),
                                        _ => None,
                                    })
                                },
                                _ => None,
                            })
                    {
                        vec![
                            ItemTag::Material(material),
                            ItemTag::SalvageInto(material, 1),
                        ]
                    } else {
                        Vec::new()
                    }
                } else {
                    Vec::new()
                }
            },
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum ModularComponent {
    ToolPrimaryComponent {
        toolkind: ToolKind,
        stats: tool::Stats,
        hand_restriction: Option<Hands>,
        weapon_name: WeaponName,
    },
    ToolSecondaryComponent {
        toolkind: ToolKind,
        stats: tool::Stats,
        hand_restriction: Option<Hands>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum WeaponName {
    Universal(String),
    HandednessDependent {
        one_handed: String,
        two_handed: String,
    },
}

impl WeaponName {
    fn resolve_name(&self, handedness: Hands) -> &str {
        match self {
            Self::Universal(name) => name,
            Self::HandednessDependent {
                one_handed: name1,
                two_handed: name2,
            } => match handedness {
                Hands::One => name1,
                Hands::Two => name2,
            },
        }
    }
}

impl ModularComponent {
    pub fn tool_stats(
        &self,
        components: &[Item],
        msm: &MaterialStatManifest,
    ) -> Option<tool::Stats> {
        match self {
            Self::ToolPrimaryComponent { stats, .. } => {
                let average_material_mult = components
                    .iter()
                    .filter_map(|comp| {
                        comp.item_definition_id()
                            .itemdef_id()
                            .and_then(|id| msm.tool_stats.get(id))
                            .copied()
                            .zip(Some(1))
                    })
                    .reduce(|(stats_a, count_a), (stats_b, count_b)| {
                        (stats_a + stats_b, count_a + count_b)
                    })
                    .map_or_else(tool::Stats::one, |(stats_sum, count)| {
                        stats_sum / (count as f32)
                    });

                Some(*stats * average_material_mult)
            },
            Self::ToolSecondaryComponent { stats, .. } => Some(*stats),
        }
    }

    pub fn toolkind(&self) -> Option<ToolKind> {
        match self {
            Self::ToolPrimaryComponent { toolkind, .. }
            | Self::ToolSecondaryComponent { toolkind, .. } => Some(*toolkind),
        }
    }
}

const SUPPORTED_TOOLKINDS: [ToolKind; 6] = [
    ToolKind::Sword,
    ToolKind::Axe,
    ToolKind::Hammer,
    ToolKind::Bow,
    ToolKind::Staff,
    ToolKind::Sceptre,
];

type PrimaryComponentPool = HashMap<(ToolKind, String), Vec<(Item, Option<Hands>)>>;
type SecondaryComponentPool = HashMap<ToolKind, Vec<(Arc<ItemDef>, Option<Hands>)>>;

lazy_static! {
    pub static ref PRIMARY_COMPONENT_POOL: PrimaryComponentPool = {
        let mut component_pool = HashMap::new();

        // Load recipe book
        // (done to check that material is valid for a particular component)
        use crate::recipe::ComponentKey;
        let recipes = recipe::default_component_recipe_book().read();
        let ability_map = &AbilityMap::load().read();
        let msm = &MaterialStatManifest::load().read();

        recipes.iter().for_each(
            |(
                ComponentKey {
                    toolkind, material, ..
                },
                recipe,
            )| {
                let component = recipe.item_output(ability_map, msm);
                let hand_restriction =
                    if let ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent {
                        hand_restriction,
                        ..
                    }) = &*component.kind()
                    {
                        *hand_restriction
                    } else {
                        return;
                    };
                let entry: &mut Vec<_> = component_pool
                    .entry((*toolkind, String::from(material)))
                    .or_default();
                entry.push((component, hand_restriction));
            },
        );

        component_pool
    };

    static ref SECONDARY_COMPONENT_POOL: SecondaryComponentPool = {
        let mut component_pool = HashMap::new();

        const ASSET_PREFIX: &str = "common.items.modular.weapon.secondary";

        for toolkind in SUPPORTED_TOOLKINDS {
            let directory = format!("{}.{}", ASSET_PREFIX, toolkind.identifier_name());
            if let Ok(items) = Item::new_from_asset_glob(&directory) {
                items
                    .into_iter()
                    .filter_map(|comp| Some(comp.item_definition_id().itemdef_id()?.to_owned()))
                    .filter_map(|id| Arc::<ItemDef>::load_cloned(&id).ok())
                    .for_each(|comp_def| {
                        if let ItemKind::ModularComponent(
                            ModularComponent::ToolSecondaryComponent {
                                hand_restriction, ..
                            },
                        ) = comp_def.kind
                        {
                            let entry: &mut Vec<_> = component_pool.entry(toolkind).or_default();
                            entry.push((Arc::clone(&comp_def), hand_restriction));
                        }
                    });
            }
        }

        component_pool
    };
}

#[derive(Debug)]
pub enum ModularWeaponCreationError {
    MaterialNotFound,
    PrimaryComponentNotFound,
    SecondaryComponentNotFound,
}

/// Check if hand restrictions are compatible.
///
/// If at least on of them is omitted, check is passed.
pub fn compatible_handedness(a: Option<Hands>, b: Option<Hands>) -> bool {
    match (a, b) {
        (Some(a), Some(b)) => a == b,
        _ => true,
    }
}

/// Generate all primary components for specific tool and material.
///
/// Read [random_weapon_primary_component] for more.
pub fn generate_weapon_primary_components(
    tool: ToolKind,
    material: Material,
    hand_restriction: Option<Hands>,
) -> Result<Vec<(Item, Option<Hands>)>, ModularWeaponCreationError> {
    if let Some(material_id) = material.asset_identifier() {
        // Loads default ability map and material stat manifest for later use
        let ability_map = &AbilityMap::load().read();
        let msm = &MaterialStatManifest::load().read();

        Ok(PRIMARY_COMPONENT_POOL
            .get(&(tool, material_id.to_owned()))
            .into_iter()
            .flatten()
            .filter(|(_comp, hand)| compatible_handedness(hand_restriction, *hand))
            .map(|(c, h)| (c.duplicate(ability_map, msm), hand_restriction.or(*h)))
            .collect())
    } else {
        Err(ModularWeaponCreationError::MaterialNotFound)
    }
}

/// Creates a random modular weapon primary component when provided with a
/// toolkind, material, and optionally the handedness
///
/// NOTE: The component produced is not necessarily restricted to that
/// handedness, but rather is able to produce a weapon of that handedness
/// depending on what secondary component is used
///
/// Returns the compatible handednesses that can be used with provided
/// restriction and generated component (useful for cases where no restriction
/// was passed in, but generated component has a restriction)
pub fn random_weapon_primary_component(
    tool: ToolKind,
    material: Material,
    hand_restriction: Option<Hands>,
    mut rng: &mut impl Rng,
) -> Result<(Item, Option<Hands>), ModularWeaponCreationError> {
    let result = {
        if let Some(material_id) = material.asset_identifier() {
            // Loads default ability map and material stat manifest for later use
            let ability_map = &AbilityMap::load().read();
            let msm = &MaterialStatManifest::load().read();

            let primary_components = PRIMARY_COMPONENT_POOL
                .get(&(tool, material_id.to_owned()))
                .into_iter()
                .flatten()
                .filter(|(_comp, hand)| compatible_handedness(hand_restriction, *hand))
                .collect::<Vec<_>>();

            let (comp, hand) = primary_components
                .choose(&mut rng)
                .ok_or(ModularWeaponCreationError::PrimaryComponentNotFound)?;
            let comp = comp.duplicate(ability_map, msm);
            Ok((comp, hand_restriction.or(*hand)))
        } else {
            Err(ModularWeaponCreationError::MaterialNotFound)
        }
    };

    if let Err(err) = &result {
        let error_str = format!(
            "Failed to synthesize a primary component for a modular {tool:?} made of {material:?} \
             that had a hand restriction of {hand_restriction:?}. Error: {err:?}"
        );
        dev_panic!(error_str)
    }
    result
}

pub fn generate_weapons(
    tool: ToolKind,
    material: Material,
    hand_restriction: Option<Hands>,
) -> Result<Vec<Item>, ModularWeaponCreationError> {
    // Loads default ability map and material stat manifest for later use
    let ability_map = &AbilityMap::load().read();
    let msm = &MaterialStatManifest::load().read();

    let primaries = generate_weapon_primary_components(tool, material, hand_restriction)?;
    let mut weapons = Vec::new();

    for (comp, comp_hand) in primaries {
        let secondaries = SECONDARY_COMPONENT_POOL
            .get(&tool)
            .into_iter()
            .flatten()
            .filter(|(_def, hand)| compatible_handedness(hand_restriction, *hand))
            .filter(|(_def, hand)| compatible_handedness(comp_hand, *hand));

        for (def, _hand) in secondaries {
            let secondary = Item::new_from_item_base(
                ItemBase::Simple(Arc::clone(def)),
                Vec::new(),
                ability_map,
                msm,
            );
            let it = Item::new_from_item_base(
                ItemBase::Modular(ModularBase::Tool),
                vec![comp.duplicate(ability_map, msm), secondary],
                ability_map,
                msm,
            );
            weapons.push(it);
        }
    }

    Ok(weapons)
}

/// Creates a random modular weapon when provided with a toolkind, material, and
/// optionally the handedness
pub fn random_weapon(
    tool: ToolKind,
    material: Material,
    hand_restriction: Option<Hands>,
    mut rng: &mut impl Rng,
) -> Result<Item, ModularWeaponCreationError> {
    let result = {
        // Loads default ability map and material stat manifest for later use
        let ability_map = &AbilityMap::load().read();
        let msm = &MaterialStatManifest::load().read();

        let (primary_component, hand_restriction) =
            random_weapon_primary_component(tool, material, hand_restriction, rng)?;

        let secondary_components = SECONDARY_COMPONENT_POOL
            .get(&tool)
            .into_iter()
            .flatten()
            .filter(|(_def, hand)| compatible_handedness(hand_restriction, *hand))
            .collect::<Vec<_>>();

        let secondary_component = {
            let def = &secondary_components
                .choose(&mut rng)
                .ok_or(ModularWeaponCreationError::SecondaryComponentNotFound)?
                .0;

            Item::new_from_item_base(
                ItemBase::Simple(Arc::clone(def)),
                Vec::new(),
                ability_map,
                msm,
            )
        };

        // Create modular weapon
        Ok(Item::new_from_item_base(
            ItemBase::Modular(ModularBase::Tool),
            vec![primary_component, secondary_component],
            ability_map,
            msm,
        ))
    };
    if let Err(err) = &result {
        let error_str = format!(
            "Failed to synthesize a modular {tool:?} made of {material:?} that had a hand \
             restriction of {hand_restriction:?}. Error: {err:?}"
        );
        dev_panic!(error_str)
    }
    result
}

pub fn modify_name<'a>(item_name: &'a str, item: &'a Item) -> Cow<'a, str> {
    if let ItemKind::ModularComponent(_) = &*item.kind() {
        if let Some(material_name) = item
            .components()
            .iter()
            .find_map(|comp| match &*comp.kind() {
                #[allow(deprecated)]
                ItemKind::Ingredient { descriptor, .. } => Some(descriptor.to_owned()),
                _ => None,
            })
        {
            Cow::Owned(format!("{} {}", material_name, item_name))
        } else {
            Cow::Borrowed(item_name)
        }
    } else {
        Cow::Borrowed(item_name)
    }
}

/// This is used as a key to uniquely identify the modular weapon in asset
/// manifests in voxygen (Main component, material, hands)
pub type ModularWeaponKey = (String, String, Hands);

pub fn weapon_to_key(mod_weap: impl ItemDesc) -> ModularWeaponKey {
    let hands = if let ItemKind::Tool(tool) = &*mod_weap.kind() {
        tool.hands
    } else {
        Hands::One
    };

    match mod_weap
        .components()
        .iter()
        .find_map(|comp| match &*comp.kind() {
            ItemKind::ModularComponent(ModularComponent::ToolPrimaryComponent { .. }) => {
                let component_id = comp.item_definition_id().itemdef_id()?.to_owned();
                let material_id = comp.components().iter().find_map(|mat| match &*mat.kind() {
                    ItemKind::Ingredient { .. } => {
                        Some(mat.item_definition_id().itemdef_id()?.to_owned())
                    },
                    _ => None,
                });
                Some((component_id, material_id))
            },
            _ => None,
        }) {
        Some((component_id, Some(material_id))) => (component_id, material_id, hands),
        Some((component_id, None)) => (component_id, String::new(), hands),
        None => (String::new(), String::new(), hands),
    }
}

/// This is used as a key to uniquely identify the modular weapon in asset
/// manifests in voxygen (Main component, material)
pub type ModularWeaponComponentKey = (String, String);

pub enum ModularWeaponComponentKeyError {
    MaterialNotFound,
}

pub fn weapon_component_to_key(
    item_def_id: &str,
    components: &[Item],
) -> Result<ModularWeaponComponentKey, ModularWeaponComponentKeyError> {
    match components.iter().find_map(|mat| match &*mat.kind() {
        ItemKind::Ingredient { .. } => Some(mat.item_definition_id().itemdef_id()?.to_owned()),
        _ => None,
    }) {
        Some(material_id) => Ok((item_def_id.to_owned(), material_id)),
        None => Err(ModularWeaponComponentKeyError::MaterialNotFound),
    }
}