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
/*
 * minecraft-json: processing Minecraft JSON data
 * Copyright (C) 2021  Xie Ruifeng
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

//! Custom advancements in data packs of a Minecraft world store the advancement
//! data for that world as separate JSON files.
//!
//! ```
//! # use maplit::btreemap;
//! # use minecraft_json::assert_equiv_pretty;
//! # use minecraft_json::minecraft::data::advancement::{Advancement, Display, Icon, Frame, Criterion};
//! # use minecraft_json::minecraft::text::{TextComponent, TextComponentTags};
//! assert_equiv_pretty!(r#"{
//!   "display": {
//!     "icon": {
//!       "item": "minecraft:red_bed"
//!     },
//!     "title": {
//!       "translate": "advancements.adventure.sleep_in_bed.title"
//!     },
//!     "description": {
//!       "translate": "advancements.adventure.sleep_in_bed.description"
//!     }
//!   },
//!   "parent": "minecraft:adventure/root",
//!   "criteria": {
//!     "slept_in_bed": {
//!       "trigger": "minecraft:slept_in_bed",
//!       "conditions": {}
//!     }
//!   },
//!   "requirements": [
//!     [
//!       "slept_in_bed"
//!     ]
//!   ]
//! }"#, Advancement {
//!     parent: Some("minecraft:adventure/root".to_string()),
//!     display: Some(Box::new(Display {
//!         icon: Some(Icon {
//!             item: "minecraft:red_bed".to_string(),
//!             nbt: None,
//!         }),
//!         title: TextComponent::Translated {
//!             translate: "advancements.adventure.sleep_in_bed.title".to_string(),
//!             with: Vec::new(),
//!             properties: TextComponentTags::default(),
//!         },
//!         description: TextComponent::Translated {
//!             translate: "advancements.adventure.sleep_in_bed.description".to_string(),
//!             with: Vec::new(),
//!             properties: TextComponentTags::default(),
//!         },
//!         frame: Frame::default(),
//!         background: None,
//!         show_toast: true,
//!         announce_to_chat: true,
//!         hidden: false,
//!     })),
//!     criteria: btreemap!{
//!         "slept_in_bed".to_string() => Criterion::SleptInBed {
//!             location: None,
//!             player: None,
//!         },
//!     },
//!     requirements: vec![vec!["slept_in_bed".to_string()]],
//!     rewards: None,
//! });
//! ```

use std::collections::BTreeMap;
use derivative::Derivative;
use serde::{Serialize, Deserialize};
use crate::defaults;
use crate::minecraft::text::TextComponent;
use crate::minecraft::data::conditions::{Location, Item, PredicatesOrEntity, Entity};

/// An advancement JSON file.
#[derive(Eq, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct Advancement {
    /// The optional display data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display: Option<Box<Display>>,
    /// The optional parent advancement directory of this advancement. If this field is absent,
    /// this advancement is a root advancement. Circular references cause a loading failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
    /// The required criteria that have to be met.
    ///
    /// - Key: A name given to the criterion (can be any string, must be unique).
    /// - Value:
    ///   - `trigger`: The trigger and conditions for this advancement; specifies what the game
    ///     should check for the advancement.
    ///   - `conditions`: All the conditions that need to be met when the trigger gets activated.
    pub criteria: BTreeMap<String, Criterion>,
    /// An optional list of requirements (all the `<criteriaNames>`). If all criteria are required,
    /// this may be omitted. With multiple criteria: requirements contains a list of lists with
    /// criteria (all criteria need to be mentioned). If all of the lists each have any criteria
    /// met, the advancement is complete. (basically AND grouping of OR groups)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requirements: Vec<Vec<String>>,
    /// An optional object representing the rewards provided when this advancement is obtained.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rewards: Option<Rewards>,
}

/// Display data for an [`Advancement`].
#[derive(Eq, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct Display {
    /// The data for the icon.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<Icon>,
    /// The title for this advancement.
    pub title: TextComponent,
    /// The optional type of frame for the icon.
    #[serde(default, skip_serializing_if = "defaults::is_default")]
    pub frame: Frame,
    /// The optional directory for the background to use in this advancement tab
    /// (used only for the root advancement).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background: Option<String>,
    /// The description of the advancement.
    pub description: TextComponent,
    /// Whether or not to show the toast pop up after completing this advancement.
    /// Defaults to `true`.
    #[serde(default = "defaults::r#true", skip_serializing_if = "defaults::is_true")]
    pub show_toast: bool,
    /// Whether or not to announce in the chat when this advancement has been completed.
    /// Defaults to `true`.
    #[serde(default = "defaults::r#true", skip_serializing_if = "defaults::is_true")]
    pub announce_to_chat: bool,
    /// Whether or not to hide this advancement and all its children from the advancement
    /// screen until this advancement have been completed. Has no effect on root advancements
    /// themselves, but still affects all their children. Defaults to `false`.
    #[serde(default, skip_serializing_if = "defaults::is_false")]
    pub hidden: bool,
}

/// An item (with NBT data) as icon.
#[derive(Eq, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct Icon {
    /// The item id.
    pub item: String,
    /// The nbt data of the item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nbt: Option<String>,
}

/// Type of frame for the icon.
#[derive(Eq, PartialEq, Debug)]
#[derive(Derivative, Serialize, Deserialize)]
#[derivative(Default)]
#[serde(rename_all = "snake_case")]
pub enum Frame {
    /// A tile with a more fancy spiked border as it is used for the kill all mobs advancement.
    Challenge,
    /// A tile with a rounded border as it is used for the full beacon advancement.
    Goal,
    /// A normal tile (default).
    #[derivative(Default)]
    Task,
}

/// Strongly-typed `trigger` and `conditions` for a criterion.
///
/// TODO: add all triggers here.
#[derive(Eq, PartialEq, Debug)]
#[derive(Derivative, Serialize, Deserialize)]
#[serde(tag = "trigger", content = "conditions")]
#[non_exhaustive]
pub enum Criterion {
    /// Triggers when the player breaks a bee nest or beehive.
    ///
    /// ```
    /// # use minecraft_json::assert_equiv_pretty;
    /// # use minecraft_json::minecraft::data::conditions::Item;
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// assert_equiv_pretty!(r#"{
    ///   "trigger": "minecraft:bee_nest_destroyed",
    ///   "conditions": {
    ///     "block": "minecraft:beehive",
    ///     "item": {
    ///       "items": [
    ///         "minecraft:wooden_axe"
    ///       ]
    ///     },
    ///     "num_bees_inside": 3
    ///   }
    /// }"#, Criterion::BeeNestDestroyed {
    ///     block: Some("minecraft:beehive".to_string()),
    ///     item: Some(Box::new(Item {
    ///         items: vec!["minecraft:wooden_axe".to_string()],
    ///         ..Item::default()
    ///     })),
    ///     num_bees_inside: Some(3),
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:bee_nest_destroyed")]
    BeeNestDestroyed {
        /// The block that was destroyed. Accepts block IDs.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        block: Option<String>,
        /// The item used to break the block. See also [`Item`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        item: Option<Box<Item>>,
        /// The number of bees that were inside the bee nest/beehive before it was broken.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        num_bees_inside: Option<isize>,
        /// The player that would get the advancement. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
    /// Triggers after the player breeds 2 animals.
    ///
    /// ```
    /// # use maplit::btreemap;
    /// # use minecraft_json::assert_equiv_pretty_protected;
    /// # use minecraft_json::minecraft::data::conditions::{Item, Entity, Location, Effect};
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// # use minecraft_json::minecraft::common::{Ranged, Either};
    /// assert_equiv_pretty_protected!(r#"{
    ///   "trigger": "minecraft:bred_animals",
    ///   "conditions": {
    ///     "child": {
    ///       "type": "minecraft:mule"
    ///     },
    ///     "parent": {
    ///       "location": {
    ///         "biome": "minecraft:beach"
    ///       }
    ///     },
    ///     "partner": {
    ///       "effects": {
    ///         "minecraft:speed": {
    ///           "amplifier": {
    ///             "min": 2
    ///           }
    ///         }
    ///       }
    ///     }
    ///   }
    /// }"#, Criterion::BredAnimals {
    ///     child: Some(Either::Right(Box::new(Entity {
    ///         r#type: Some("minecraft:mule".to_string()),
    ///         ..Entity::default()
    ///     }))),
    ///     parent: Some(Either::Right(Box::new(Entity {
    ///         location: Some(Box::new(Location {
    ///             biome: Some("minecraft:beach".to_string()),
    ///             ..Location::default()
    ///         })),
    ///         ..Entity::default()
    ///     }))),
    ///     partner: Some(Either::Right(Box::new(Entity {
    ///         effects: btreemap! {
    ///             "minecraft:speed".to_string() => Effect {
    ///                 amplifier: Some(Ranged::Range {
    ///                     min: Some(2),
    ///                     max: None,
    ///                 }),
    ///                 ..Effect::default()
    ///             },
    ///         },
    ///         ..Entity::default()
    ///     }))),
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:bred_animals")]
    BredAnimals {
        /// The child that results from the breeding. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        child: Option<PredicatesOrEntity>,
        /// The parent. May also be a list of predicates that must pass in order for the trigger
        /// to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent: Option<PredicatesOrEntity>,
        /// The partner. (The entity the parent was bred with) May also be a list of predicates
        /// that must pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        partner: Option<PredicatesOrEntity>,
        /// The player that would get the advancement. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
    /// Triggers after the player takes any item out of a brewing stand.
    ///
    /// ```
    /// # use minecraft_json::assert_equiv_pretty;
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// assert_equiv_pretty!(r#"{
    ///   "trigger": "minecraft:brewed_potion",
    ///   "conditions": {
    ///     "potion": "minecraft:strong_swiftness"
    ///   }
    /// }"#, Criterion::BrewedPotion {
    ///     potion: Some("minecraft:strong_swiftness".to_string()),
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:brewed_potion")]
    BrewedPotion {
        /// A brewed potion ID.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        potion: Option<String>,
        /// The player that would get the advancement. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
    /// Triggers after the player travels between two dimensions.
    ///
    /// ```
    /// # use minecraft_json::assert_equiv_pretty;
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// assert_equiv_pretty!(r#"{
    ///   "trigger": "minecraft:changed_dimension",
    ///   "conditions": {
    ///     "from": "minecraft:the_end",
    ///     "to": "minecraft:overworld"
    ///   }
    /// }"#, Criterion::ChangedDimension {
    ///     from: Some("minecraft:the_end".to_string()),
    ///     to: Some("minecraft:overworld".to_string()),
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:changed_dimension")]
    ChangedDimension {
        /// The dimension the entity traveled from. Accepts these 3 values.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        from: Option<String>,
        /// The dimension the entity traveled to. Same accepted values as above.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        to: Option<String>,
        /// The player that would get the advancement. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
    /// Triggers after the player successfully uses the Channeling enchantment on an entity.
    ///
    /// ```
    /// # use minecraft_json::assert_equiv_pretty;
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// use minecraft_json::minecraft::data::conditions::Entity;
    /// assert_equiv_pretty!(r#"{
    ///   "trigger": "minecraft:channeled_lightning",
    ///   "conditions": {
    ///     "victims": [
    ///       {
    ///         "nbt": "{SkeletonTrap: true}",
    ///         "type": "minecraft:skeleton_horse"
    ///       }
    ///     ]
    ///   }
    /// }"#, Criterion::ChanneledLightning {
    ///     victims: vec![Entity {
    ///         r#type: Some("minecraft:skeleton_horse".to_string()),
    ///         nbt: Some("{SkeletonTrap: true}".to_string()),
    ///         ..Entity::default()
    ///     }],
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:channeled_lightning")]
    ChanneledLightning {
        /// The victims hit by the lightning summoned by the Channeling enchantment. All entities
        /// in this list must be hit. Each entry may also be a list of predicates that must pass
        /// in order for the trigger to activate. The checks are applied to the victim hit by the
        /// enchanted trident.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        victims: Vec<Entity>,
        /// The player that would get the advancement. May also be a list of predicates that must
        /// pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
    /// Triggers when the player enters a bed.
    ///
    /// ```
    /// # use minecraft_json::assert_equiv_pretty_protected;
    /// # use minecraft_json::minecraft::data::conditions::{Item, Location};
    /// # use minecraft_json::minecraft::data::advancement::Criterion;
    /// # use minecraft_json::minecraft::common::{Vector3d, Ranged};
    /// assert_equiv_pretty_protected!(r#"{
    ///   "trigger": "minecraft:slept_in_bed",
    ///   "conditions": {
    ///     "location": {
    ///       "biome": "minecraft:desert",
    ///       "feature": "village",
    ///       "position": {
    ///         "y": {
    ///           "min": 50,
    ///           "max": 100
    ///         }
    ///       }
    ///     }
    ///   }
    /// }"#, Criterion::SleptInBed {
    ///     location: Some(Box::new(Location {
    ///         biome: Some("minecraft:desert".to_string()),
    ///         feature: Some("village".to_string()),
    ///         position: Some(Box::new(Vector3d {
    ///             y: Some(Ranged::Range {
    ///                 min: Some(50),
    ///                 max: Some(100),
    ///             }),
    ///             ..Vector3d::default()
    ///         })),
    ///         ..Location::default()
    ///     })),
    ///     player: None,
    /// });
    /// ```
    #[serde(rename = "minecraft:slept_in_bed")]
    SleptInBed {
        /// The location of the player.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        location: Option<Box<Location>>,
        /// The player that would get the advancement. May also be a list of predicates that
        /// must pass in order for the trigger to activate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        player: Option<PredicatesOrEntity>,
    },
}

/// An object representing the rewards provided when an [`Advancement`] is obtained.
#[derive(Eq, PartialEq, Debug, Default)]
#[derive(Derivative, Serialize, Deserialize)]
pub struct Rewards {
    /// A list of recipes to unlock.
    ///
    /// Item: A namespaced ID for a recipe.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub recipes: Vec<String>,
    /// A list of loot tables to give to the player.
    ///
    /// Item: A namespaced ID for a loot table.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub loot: Vec<String>,
    /// An amount of experience.
    #[serde(default, skip_serializing_if = "defaults::is_default")]
    pub experience: isize,
    /// A function to run. Function tags are not allowed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub function: Option<String>,
}