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
#![doc = include_str!("../README.md")]

pub mod event;

use std::borrow::Cow;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemParam;
pub use bevy_hierarchy;
use bevy_hierarchy::{Children, HierarchyPlugin, Parent};
use derive_more::{Deref, DerefMut};
use event::{handle_advancement_tab_change, AdvancementTabChangeEvent};
use rustc_hash::FxHashMap;
use valence_server::client::{Client, FlushPacketsSet, SpawnClientsSet};
use valence_server::protocol::packets::play::{
    advancement_update_s2c as packet, SelectAdvancementTabS2c,
};
use valence_server::protocol::{
    anyhow, packet_id, Encode, Packet, PacketSide, PacketState, RawBytes, VarInt, WritePacket,
};
use valence_server::{Ident, ItemStack, Text};

pub struct AdvancementPlugin;

#[derive(SystemSet, Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub struct WriteAdvancementPacketToClientsSet;

#[derive(SystemSet, Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub struct WriteAdvancementToCacheSet;

impl Plugin for AdvancementPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        app.add_plugins(HierarchyPlugin)
            .configure_sets(
                PostUpdate,
                (
                    WriteAdvancementPacketToClientsSet.before(FlushPacketsSet),
                    WriteAdvancementToCacheSet.before(WriteAdvancementPacketToClientsSet),
                ),
            )
            .add_event::<AdvancementTabChangeEvent>()
            .add_systems(
                PreUpdate,
                (
                    add_advancement_update_component_to_new_clients.after(SpawnClientsSet),
                    handle_advancement_tab_change,
                ),
            )
            .add_systems(
                PostUpdate,
                (
                    update_advancement_cached_bytes.in_set(WriteAdvancementToCacheSet),
                    send_advancement_update_packet.in_set(WriteAdvancementPacketToClientsSet),
                ),
            );
    }
}

/// Components for advancement that are required
/// Optional components:
/// [`AdvancementDisplay`]
/// [`Parent`] - parent advancement
#[derive(Bundle)]
pub struct AdvancementBundle {
    pub advancement: Advancement,
    pub requirements: AdvancementRequirements,
    pub cached_bytes: AdvancementCachedBytes,
}

fn add_advancement_update_component_to_new_clients(
    mut commands: Commands,
    query: Query<Entity, Added<Client>>,
) {
    for client in query.iter() {
        commands
            .entity(client)
            .insert(AdvancementClientUpdate::default());
    }
}

#[derive(SystemParam, Debug)]
struct UpdateAdvancementCachedBytesQuery<'w, 's> {
    advancement_id_query: Query<'w, 's, &'static Advancement>,
    criteria_query: Query<'w, 's, &'static AdvancementCriteria>,
}

impl<'w, 's> UpdateAdvancementCachedBytesQuery<'w, 's> {
    fn write(
        &self,
        a_identifier: &Advancement,
        a_requirements: &AdvancementRequirements,
        a_display: Option<&AdvancementDisplay>,
        a_children: Option<&Children>,
        a_parent: Option<&Parent>,
        w: impl Write,
    ) -> anyhow::Result<()> {
        let Self {
            advancement_id_query,
            criteria_query,
        } = self;

        let mut pkt = packet::Advancement {
            parent_id: None,
            display_data: None,
            criteria: vec![],
            requirements: vec![],
            sends_telemetry_data: false,
        };

        if let Some(a_parent) = a_parent {
            let a_identifier = advancement_id_query.get(a_parent.get())?;
            pkt.parent_id = Some(a_identifier.0.borrowed());
        }

        if let Some(a_display) = a_display {
            pkt.display_data = Some(packet::AdvancementDisplay {
                title: Cow::Borrowed(&a_display.title),
                description: Cow::Borrowed(&a_display.description),
                icon: &a_display.icon,
                frame_type: VarInt(a_display.frame_type as i32),
                flags: a_display.flags(),
                background_texture: a_display.background_texture.as_ref().map(|v| v.borrowed()),
                x_coord: a_display.x_coord,
                y_coord: a_display.y_coord,
            });
        }

        if let Some(a_children) = a_children {
            for a_child in a_children {
                let Ok(c_identifier) = criteria_query.get(*a_child) else {
                    continue;
                };
                pkt.criteria.push((c_identifier.0.borrowed(), ()));
            }
        }

        for requirements in &a_requirements.0 {
            let mut requirements_p = vec![];
            for requirement in requirements {
                let c_identifier = criteria_query.get(*requirement)?;
                requirements_p.push(c_identifier.0.as_str());
            }
            pkt.requirements.push(packet::AdvancementRequirements {
                requirement: requirements_p,
            });
        }

        (&a_identifier.0, pkt).encode(w)
    }
}

fn update_advancement_cached_bytes(
    mut query: Query<
        (
            &Advancement,
            &AdvancementRequirements,
            &mut AdvancementCachedBytes,
            Option<&AdvancementDisplay>,
            Option<&Children>,
            Option<&Parent>,
        ),
        Or<(
            Changed<AdvancementDisplay>,
            Changed<Children>,
            Changed<Parent>,
            Changed<AdvancementRequirements>,
        )>,
    >,
    update_advancement_cached_bytes_query: UpdateAdvancementCachedBytesQuery,
) {
    for (a_identifier, a_requirements, mut a_bytes, a_display, a_children, a_parent) in &mut query {
        a_bytes.0.clear();
        update_advancement_cached_bytes_query
            .write(
                a_identifier,
                a_requirements,
                a_display,
                a_children,
                a_parent,
                &mut a_bytes.0,
            )
            .expect("Failed to write an advancement");
    }
}

#[derive(SystemParam, Debug)]
#[allow(clippy::type_complexity)]
pub(crate) struct SingleAdvancementUpdateQuery<'w, 's> {
    advancement_bytes: Query<'w, 's, &'static AdvancementCachedBytes>,
    advancement_id: Query<'w, 's, &'static Advancement>,
    criteria: Query<'w, 's, &'static AdvancementCriteria>,
    parent: Query<'w, 's, &'static Parent>,
}

#[derive(Debug)]
pub(crate) struct AdvancementUpdateEncodeS2c<'w, 's, 'a> {
    client_update: AdvancementClientUpdate,
    queries: &'a SingleAdvancementUpdateQuery<'w, 's>,
}

impl<'w, 's, 'a> Encode for AdvancementUpdateEncodeS2c<'w, 's, 'a> {
    fn encode(&self, w: impl Write) -> anyhow::Result<()> {
        let SingleAdvancementUpdateQuery {
            advancement_bytes: advancement_bytes_query,
            advancement_id: advancement_id_query,
            criteria: criteria_query,
            parent: parent_query,
        } = self.queries;

        let AdvancementClientUpdate {
            new_advancements,
            remove_advancements,
            progress,
            reset,
            ..
        } = &self.client_update;

        let mut pkt = packet::GenericAdvancementUpdateS2c {
            reset: *reset,
            advancement_mapping: vec![],
            identifiers: vec![],
            progress_mapping: vec![],
        };

        for new_advancement in new_advancements {
            let a_cached_bytes = advancement_bytes_query.get(*new_advancement)?;
            pkt.advancement_mapping
                .push(RawBytes(a_cached_bytes.0.as_slice()));
        }

        for remove_advancement in remove_advancements {
            let a_identifier = advancement_id_query.get(*remove_advancement)?;
            pkt.identifiers.push(a_identifier.0.borrowed());
        }

        let mut progress_mapping: FxHashMap<Entity, Vec<(Entity, Option<i64>)>> =
            FxHashMap::default();
        for progress in progress {
            let a = parent_query.get(progress.0)?;
            progress_mapping
                .entry(a.get())
                .and_modify(|v| v.push(*progress))
                .or_insert(vec![*progress]);
        }

        for (a, c_progresses) in progress_mapping {
            let a_identifier = advancement_id_query.get(a)?;
            let mut c_progresses_p = vec![];
            for (c, c_progress) in c_progresses {
                let c_identifier = criteria_query.get(c)?;
                c_progresses_p.push(packet::AdvancementCriteria {
                    criterion_identifier: c_identifier.0.borrowed(),
                    criterion_progress: c_progress,
                });
            }
            pkt.progress_mapping
                .push((a_identifier.0.borrowed(), c_progresses_p));
        }

        pkt.encode(w)
    }
}

impl<'w, 's, 'a> Packet for AdvancementUpdateEncodeS2c<'w, 's, 'a> {
    const ID: i32 = packet_id::ADVANCEMENT_UPDATE_S2C;
    const NAME: &'static str = "AdvancementUpdateEncodeS2c";
    const SIDE: PacketSide = PacketSide::Clientbound;
    const STATE: PacketState = PacketState::Play;
}

#[allow(clippy::type_complexity)]
fn send_advancement_update_packet(
    mut client: Query<(&mut AdvancementClientUpdate, &mut Client)>,
    update_single_query: SingleAdvancementUpdateQuery,
) {
    for (mut advancement_client_update, mut client) in &mut client {
        match advancement_client_update.force_tab_update {
            ForceTabUpdate::None => {}
            ForceTabUpdate::First => {
                client.write_packet(&SelectAdvancementTabS2c { identifier: None })
            }
            ForceTabUpdate::Spec(spec) => {
                if let Ok(a_identifier) = update_single_query.advancement_id.get(spec) {
                    client.write_packet(&SelectAdvancementTabS2c {
                        identifier: Some(a_identifier.0.borrowed()),
                    });
                }
            }
        }

        if ForceTabUpdate::None != advancement_client_update.force_tab_update {
            advancement_client_update.force_tab_update = ForceTabUpdate::None;
        }

        if advancement_client_update.new_advancements.is_empty()
            && advancement_client_update.progress.is_empty()
            && advancement_client_update.remove_advancements.is_empty()
            && !advancement_client_update.reset
        {
            continue;
        }

        let advancement_client_update = std::mem::replace(
            advancement_client_update.as_mut(),
            AdvancementClientUpdate {
                reset: false,
                ..Default::default()
            },
        );

        client.write_packet(&AdvancementUpdateEncodeS2c {
            queries: &update_single_query,
            client_update: advancement_client_update,
        });
    }
}

/// Advancement's id. May not be updated.
#[derive(Component, Deref)]
pub struct Advancement(Ident<Cow<'static, str>>);

impl Advancement {
    pub fn new(ident: Ident<Cow<'static, str>>) -> Advancement {
        Self(ident)
    }

    pub fn get(&self) -> &Ident<Cow<'static, str>> {
        &self.0
    }
}

#[derive(Clone, Copy)]
pub enum AdvancementFrameType {
    Task,
    Challenge,
    Goal,
}

/// Advancement display. Optional component
#[derive(Component)]
pub struct AdvancementDisplay {
    pub title: Text,
    pub description: Text,
    pub icon: ItemStack,
    pub frame_type: AdvancementFrameType,
    pub show_toast: bool,
    pub hidden: bool,
    pub background_texture: Option<Ident<Cow<'static, str>>>,
    pub x_coord: f32,
    pub y_coord: f32,
}

impl AdvancementDisplay {
    pub(crate) fn flags(&self) -> i32 {
        let mut flags = 0;
        flags |= i32::from(self.background_texture.is_some());
        flags |= i32::from(self.show_toast) << 1;
        flags |= i32::from(self.hidden) << 2;
        flags
    }
}

/// Criteria's identifier. May not be updated
#[derive(Component, Deref)]
pub struct AdvancementCriteria(Ident<Cow<'static, str>>);

impl AdvancementCriteria {
    pub fn new(ident: Ident<Cow<'static, str>>) -> Self {
        Self(ident)
    }

    pub fn get(&self) -> &Ident<Cow<'static, str>> {
        &self.0
    }
}

/// Requirements for advancement to be completed.
/// All columns should be completed, column is completed when any of criteria in
/// this column is completed.
#[derive(Component, Default, Deref, DerefMut)]
pub struct AdvancementRequirements(pub Vec<Vec<Entity>>);

#[derive(Component, Default)]
pub struct AdvancementCachedBytes(pub(crate) Vec<u8>);

#[derive(Default, Debug, PartialEq)]
pub enum ForceTabUpdate {
    #[default]
    None,
    First,
    /// Should contain only root advancement otherwise the first will be chosen
    Spec(Entity),
}

#[derive(Component, Debug)]
pub struct AdvancementClientUpdate {
    /// Which advancement's descriptions send to client
    pub new_advancements: Vec<Entity>,
    /// Which advancements remove from client
    pub remove_advancements: Vec<Entity>,
    /// Criteria progress update.
    /// If None then criteria is not done otherwise it is done
    pub progress: Vec<(Entity, Option<i64>)>,
    /// Forces client to open a tab
    pub force_tab_update: ForceTabUpdate,
    /// Defines if other advancements should be removed.
    /// Also with this flag, client will not show a toast for advancements,
    /// which are completed. When the packet is sent, turns to false
    pub reset: bool,
}

impl Default for AdvancementClientUpdate {
    fn default() -> Self {
        Self {
            new_advancements: vec![],
            remove_advancements: vec![],
            progress: vec![],
            force_tab_update: ForceTabUpdate::default(),
            reset: true,
        }
    }
}

impl AdvancementClientUpdate {
    pub(crate) fn walk_advancements(
        root: Entity,
        children_query: &Query<&Children>,
        advancement_check_query: &Query<(), With<Advancement>>,
        func: &mut impl FnMut(Entity),
    ) {
        func(root);
        if let Ok(children) = children_query.get(root) {
            for child in children {
                let child = *child;
                if advancement_check_query.get(child).is_ok() {
                    Self::walk_advancements(child, children_query, advancement_check_query, func);
                }
            }
        }
    }

    /// Sends all advancements from the root
    pub fn send_advancements(
        &mut self,
        root: Entity,
        children_query: &Query<&Children>,
        advancement_check_query: &Query<(), With<Advancement>>,
    ) {
        Self::walk_advancements(root, children_query, advancement_check_query, &mut |e| {
            self.new_advancements.push(e)
        });
    }

    /// Removes all advancements from the root
    pub fn remove_advancements(
        &mut self,
        root: Entity,
        children_query: &Query<&Children>,
        advancement_check_query: &Query<(), With<Advancement>>,
    ) {
        Self::walk_advancements(root, children_query, advancement_check_query, &mut |e| {
            self.remove_advancements.push(e)
        });
    }

    /// Marks criteria as done
    pub fn criteria_done(&mut self, criteria: Entity) {
        self.progress.push((
            criteria,
            Some(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_millis() as i64,
            ),
        ))
    }

    /// Marks criteria as undone
    pub fn criteria_undone(&mut self, criteria: Entity) {
        self.progress.push((criteria, None))
    }
}