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
#![doc = include_str!("../README.md")]
#![allow(clippy::unseparated_literal_suffix, clippy::manual_string_new)]

pub mod active_status_effects;
pub mod attributes;
mod flags;
pub mod hitbox;
pub mod manager;
pub mod query;
pub mod tracked_data;

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use derive_more::{Deref, DerefMut};
pub use manager::EntityManager;
use paste::paste;
use tracing::warn;
use tracked_data::TrackedData;
use valence_math::{DVec3, Vec3};
use valence_protocol::{Decode, Encode, VarInt};
use valence_server_common::{Despawned, UniqueId};

use crate::attributes::TrackedEntityAttributes;

include!(concat!(env!("OUT_DIR"), "/entity.rs"));

pub struct EntityPlugin;

/// When new Minecraft entities are initialized and added to
/// [`EntityManager`].
///
/// Systems that need Minecraft entities to be in a valid state should run
/// _after_ this set.
///
/// This set lives in [`PostUpdate`].
#[derive(SystemSet, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct InitEntitiesSet;

/// When tracked data is written to the entity's [`TrackedData`] component.
/// Systems that modify tracked data should run _before_ this.
///
/// This set lives in [`PostUpdate`].
#[derive(SystemSet, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct UpdateTrackedDataSet;

/// When entities are updated and changes from the current tick are cleared.
/// Systems that need to observe changes to entities (Such as the difference
/// between [`Position`] and [`OldPosition`]) should run _before_ this set (and
/// probably after [`InitEntitiesSet`]).
///
/// This set lives in [`PostUpdate`].
#[derive(SystemSet, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct ClearEntityChangesSet;

impl Plugin for EntityPlugin {
    fn build(&self, app: &mut App) {
        app.insert_resource(EntityManager::new())
            .configure_sets(
                PostUpdate,
                (
                    InitEntitiesSet,
                    UpdateTrackedDataSet,
                    ClearEntityChangesSet
                        .after(InitEntitiesSet)
                        .after(UpdateTrackedDataSet),
                ),
            )
            .add_systems(
                PostUpdate,
                (remove_despawned_from_manager, init_entities)
                    .chain()
                    .in_set(InitEntitiesSet),
            )
            .add_systems(
                PostUpdate,
                (
                    clear_status_changes,
                    clear_animation_changes,
                    clear_tracked_data_changes,
                    clear_tracked_attributes_changes,
                    update_old_position,
                    update_old_layer_id,
                )
                    .in_set(ClearEntityChangesSet),
            );

        add_tracked_data_systems(app);
    }
}

fn update_old_position(mut query: Query<(&Position, &mut OldPosition)>) {
    for (pos, mut old_pos) in &mut query {
        old_pos.0 = pos.0;
    }
}

fn update_old_layer_id(mut query: Query<(&EntityLayerId, &mut OldEntityLayerId)>) {
    for (loc, mut old_loc) in &mut query {
        old_loc.0 = loc.0;
    }
}

fn remove_despawned_from_manager(
    entities: Query<&EntityId, (With<EntityKind>, With<Despawned>)>,
    mut manager: ResMut<EntityManager>,
) {
    for id in &entities {
        manager.id_to_entity.remove(&id.0);
    }
}

fn init_entities(
    mut entities: Query<
        (Entity, &mut EntityId, &Position, &mut OldPosition),
        (Added<EntityKind>, Without<Despawned>),
    >,
    mut manager: ResMut<EntityManager>,
) {
    for (entity, mut id, pos, mut old_pos) in &mut entities {
        *old_pos = OldPosition::new(pos.0);

        if *id == EntityId::default() {
            *id = manager.next_id();
        }

        if let Some(conflict) = manager.id_to_entity.insert(id.0, entity) {
            warn!(
                "entity {entity:?} has conflicting entity ID of {} with entity {conflict:?}",
                id.0
            );
        }
    }
}

fn clear_status_changes(mut statuses: Query<&mut EntityStatuses, Changed<EntityStatuses>>) {
    for mut statuses in &mut statuses {
        statuses.0 = 0;
    }
}

fn clear_animation_changes(
    mut animations: Query<&mut EntityAnimations, Changed<EntityAnimations>>,
) {
    for mut animations in &mut animations {
        animations.0 = 0;
    }
}

fn clear_tracked_data_changes(mut tracked_data: Query<&mut TrackedData, Changed<TrackedData>>) {
    for mut tracked_data in &mut tracked_data {
        tracked_data.clear_update_values();
    }
}

fn clear_tracked_attributes_changes(
    mut attributes: Query<&mut TrackedEntityAttributes, Changed<TrackedEntityAttributes>>,
) {
    for mut attributes in &mut attributes {
        attributes.clear();
    }
}

/// Contains the entity layer an entity is on.
#[derive(Component, Copy, Clone, PartialEq, Eq, Debug, Deref)]
pub struct EntityLayerId(pub Entity);

impl Default for EntityLayerId {
    fn default() -> Self {
        Self(Entity::PLACEHOLDER)
    }
}

impl PartialEq<OldEntityLayerId> for EntityLayerId {
    fn eq(&self, other: &OldEntityLayerId) -> bool {
        self.0 == other.0
    }
}

/// The value of [`EntityLayerId`] from the end of the previous tick.
#[derive(Component, Copy, Clone, PartialEq, Eq, Debug, Deref)]
pub struct OldEntityLayerId(Entity);

impl OldEntityLayerId {
    pub fn get(&self) -> Entity {
        self.0
    }
}

impl Default for OldEntityLayerId {
    fn default() -> Self {
        Self(Entity::PLACEHOLDER)
    }
}

impl PartialEq<EntityLayerId> for OldEntityLayerId {
    fn eq(&self, other: &EntityLayerId) -> bool {
        self.0 == other.0
    }
}

#[derive(Component, Copy, Clone, PartialEq, Default, Debug, Deref, DerefMut)]
pub struct Position(pub DVec3);

impl Position {
    pub fn new<P: Into<DVec3>>(pos: P) -> Self {
        Self(pos.into())
    }

    pub fn get(self) -> DVec3 {
        self.0
    }

    pub fn set<P: Into<DVec3>>(&mut self, pos: P) {
        self.0 = pos.into();
    }
}

impl PartialEq<OldPosition> for Position {
    fn eq(&self, other: &OldPosition) -> bool {
        self.0 == other.0
    }
}

/// The value of [`Position`] from the end of the previous tick.
///
/// **NOTE**: You should not modify this component after the entity is spawned.
#[derive(Component, Clone, PartialEq, Default, Debug, Deref)]
pub struct OldPosition(DVec3);

impl OldPosition {
    pub fn new<P: Into<DVec3>>(pos: P) -> Self {
        Self(pos.into())
    }

    pub fn get(&self) -> DVec3 {
        self.0
    }
}

impl PartialEq<Position> for OldPosition {
    fn eq(&self, other: &Position) -> bool {
        self.0 == other.0
    }
}

/// Describes the direction an entity is looking using pitch and yaw angles.
#[derive(Component, Copy, Clone, PartialEq, Default, Debug)]
pub struct Look {
    /// The yaw angle in degrees, where:
    /// - `-90` is looking east (towards positive x).
    /// - `0` is looking south (towards positive z).
    /// - `90` is looking west (towards negative x).
    /// - `180` is looking north (towards negative z).
    ///
    /// Values -180 to 180 are also valid.
    pub yaw: f32,
    /// The pitch angle in degrees, where:
    /// - `-90` is looking straight up.
    /// - `0` is looking straight ahead.
    /// - `90` is looking straight down.
    pub pitch: f32,
}

impl Look {
    pub const fn new(yaw: f32, pitch: f32) -> Self {
        Self { yaw, pitch }
    }

    /// Gets a normalized direction vector from the yaw and pitch.
    pub fn vec(self) -> Vec3 {
        let (yaw_sin, yaw_cos) = (self.yaw + 90.0).to_radians().sin_cos();
        let (pitch_sin, pitch_cos) = (-self.pitch).to_radians().sin_cos();

        Vec3::new(yaw_cos * pitch_cos, pitch_sin, yaw_sin * pitch_cos)
    }

    /// Sets the yaw and pitch using a normalized direction vector.
    pub fn set_vec(&mut self, dir: Vec3) {
        debug_assert!(
            dir.is_normalized(),
            "the direction vector should be normalized"
        );

        // Preserve the current yaw if we're looking straight up or down.
        if dir.x != 0.0 || dir.z != 0.0 {
            self.yaw = f32::atan2(dir.z, dir.x).to_degrees() - 90.0;
        }

        self.pitch = -(dir.y).asin().to_degrees();
    }
}

#[derive(Component, Copy, Clone, PartialEq, Eq, Default, Debug, Deref, DerefMut)]
pub struct OnGround(pub bool);

/// A Minecraft entity's ID according to the protocol.
///
/// IDs should be _unique_ for the duration of the server and  _constant_ for
/// the lifetime of the entity. IDs of -1 (the default) will be assigned to
/// something else on the tick the entity is added. If you need to know the ID
/// ahead of time, set this component to the value returned by
/// [`EntityManager::next_id`] before spawning.
#[derive(Component, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Deref)]
pub struct EntityId(i32);

impl EntityId {
    /// Returns the underlying entity ID as an integer.
    pub fn get(self) -> i32 {
        self.0
    }
}

/// Returns an entity ID of -1.
impl Default for EntityId {
    fn default() -> Self {
        Self(-1)
    }
}

#[derive(Component, Copy, Clone, PartialEq, Default, Debug, Deref, DerefMut)]
pub struct HeadYaw(pub f32);

/// Entity velocity in m/s.
#[derive(Component, Copy, Clone, Default, Debug, Deref, DerefMut)]
pub struct Velocity(pub Vec3);

impl Velocity {
    pub fn to_packet_units(self) -> valence_protocol::Velocity {
        valence_protocol::Velocity::from_ms_f32(self.0.into())
    }
}

// TODO: don't make statuses and animations components.

#[derive(Component, Copy, Clone, Default, Debug, Deref, DerefMut)]
pub struct EntityStatuses(pub u64);

impl EntityStatuses {
    pub fn trigger(&mut self, status: EntityStatus) {
        self.set(status, true);
    }

    pub fn set(&mut self, status: EntityStatus, triggered: bool) {
        self.0 |= u64::from(triggered) << status as u64;
    }

    pub fn get(&self, status: EntityStatus) -> bool {
        (self.0 >> status as u64) & 1 == 1
    }
}

#[derive(Component, Default, Debug, Copy, Clone, Deref, DerefMut)]
pub struct EntityAnimations(pub u8);

impl EntityAnimations {
    pub fn trigger(&mut self, anim: EntityAnimation) {
        self.set(anim, true);
    }

    pub fn set(&mut self, anim: EntityAnimation, triggered: bool) {
        self.0 |= u8::from(triggered) << anim as u8;
    }

    pub fn get(&self, anim: EntityAnimation) -> bool {
        (self.0 >> anim as u8) & 1 == 1
    }
}

/// Extra integer data passed to the entity spawn packet. The meaning depends on
/// the type of entity being spawned.
///
/// Some examples:
/// - **Experience Orb**: Experience count
/// - **(Glowing) Item Frame**: Rotation
/// - **Painting**: Rotation
/// - **Falling Block**: Block state
/// - **Fishing Bobber**: Hook entity ID
/// - **Warden**: Initial pose
#[derive(Component, Default, Debug, Deref, DerefMut)]
pub struct ObjectData(pub i32);

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct VillagerData {
    pub kind: VillagerKind,
    pub profession: VillagerProfession,
    pub level: i32,
}

impl VillagerData {
    pub const fn new(kind: VillagerKind, profession: VillagerProfession, level: i32) -> Self {
        Self {
            kind,
            profession,
            level,
        }
    }
}

impl Default for VillagerData {
    fn default() -> Self {
        Self {
            kind: Default::default(),
            profession: Default::default(),
            level: 1,
        }
    }
}

impl Encode for VillagerData {
    fn encode(&self, mut w: impl std::io::Write) -> anyhow::Result<()> {
        self.kind.encode(&mut w)?;
        self.profession.encode(&mut w)?;
        VarInt(self.level).encode(w)
    }
}

impl Decode<'_> for VillagerData {
    fn decode(r: &mut &[u8]) -> anyhow::Result<Self> {
        Ok(Self {
            kind: VillagerKind::decode(r)?,
            profession: VillagerProfession::decode(r)?,
            level: VarInt::decode(r)?.0,
        })
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum VillagerKind {
    Desert,
    Jungle,
    #[default]
    Plains,
    Savanna,
    Snow,
    Swamp,
    Taiga,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum VillagerProfession {
    #[default]
    None,
    Armorer,
    Butcher,
    Cartographer,
    Cleric,
    Farmer,
    Fisherman,
    Fletcher,
    Leatherworker,
    Librarian,
    Mason,
    Nitwit,
    Shepherd,
    Toolsmith,
    Weaponsmith,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum Pose {
    #[default]
    Standing,
    FallFlying,
    Sleeping,
    Swimming,
    SpinAttack,
    Sneaking,
    LongJumping,
    Dying,
    Croaking,
    UsingTongue,
    Roaring,
    Sniffing,
    Emerging,
    Digging,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum BoatKind {
    #[default]
    Oak,
    Spruce,
    Birch,
    Jungle,
    Acacia,
    DarkOak,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum CatKind {
    Tabby,
    #[default]
    Black,
    Red,
    Siamese,
    BritishShorthair,
    Calico,
    Persian,
    Ragdoll,
    White,
    Jellie,
    AllBlack,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum FrogKind {
    #[default]
    Temperate,
    Warm,
    Cold,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum PaintingKind {
    #[default]
    Kebab,
    Aztec,
    Alban,
    Aztec2,
    Bomb,
    Plant,
    Wasteland,
    Pool,
    Courbet,
    Sea,
    Sunset,
    Creebet,
    Wanderer,
    Graham,
    Match,
    Bust,
    Stage,
    Void,
    SkullAndRoses,
    Wither,
    Fighters,
    Pointer,
    Pigscene,
    BurningSkull,
    Skeleton,
    Earth,
    Wind,
    Water,
    Fire,
    DonkeyKong,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug, Encode, Decode)]
pub enum SnifferState {
    #[default]
    Idling,
    FeelingHappy,
    Scenting,
    Sniffing,
    Searching,
    Digging,
    Rising,
}

#[derive(Clone, Copy, PartialEq, PartialOrd, Debug, Encode, Decode)]
pub struct EulerAngle {
    pub pitch: f32,
    pub yaw: f32,
    pub roll: f32,
}

#[derive(Copy, Clone)]
struct OptionalInt(Option<i32>);

impl Encode for OptionalInt {
    fn encode(&self, w: impl std::io::Write) -> anyhow::Result<()> {
        if let Some(n) = self.0 {
            VarInt(n.wrapping_add(1))
        } else {
            VarInt(0)
        }
        .encode(w)
    }
}

impl Decode<'_> for OptionalInt {
    fn decode(r: &mut &[u8]) -> anyhow::Result<Self> {
        let n = VarInt::decode(r)?.0;

        Ok(Self(if n == 0 {
            None
        } else {
            Some(n.wrapping_sub(1))
        }))
    }
}