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
//! Modern versions: our own entity's data and the other entities around the player (the ones
//! that tick before it, their pushes after its tick).
use super::*;
impl ModernSim {
/// `set_entity_data`, `add_entity`, `remove_entities` for our own entity and attached
/// rockets (everything else is read only up to the entity id, or the entity type).
pub(super) fn own_entity_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use super::proto::play::clientbound as cb;
use super::proto::types::EntityMetadataEntryValue as V;
let mut r = ghast_protocol::Reader::new(&raw.body);
match raw.id {
cb::id::ENTITY_METADATA => {
let id = r.read_varint()?;
let rocket = self.own.rockets.iter().position(|&(rid, _)| rid == id);
let mount = self.own.mounts.iter().position(|m| m.id == id);
if id != self.own.id && rocket.is_none() && mount.is_none() {
return Ok(());
}
let p: cb::EntityMetadata = raw.decode_as()?;
for e in &p.metadata {
match (&e.value, e.key) {
(V::Byte(b), DATA_SHARED_FLAGS) if id == self.own.id => {
self.server_flags = Some(*b as u8);
self.ext.apply_shared_flags(&mut self.player, *b as u8);
self.ext_active |= self.ext.fall_flying;
}
// Player.DATA_PLAYER_ABSORPTION_ID (after Avatar's two entries).
(V::Float(a), 17) if id == self.own.id => {
self.absorption = *a;
self.absorption_dirty = true;
}
// LivingEntity.SLEEPING_POS_ID: onSyncedDataUpdated → setPosToBed (the
// bed's sleep height + 0.125; nothing moves without a bed there)
(V::OptionalBlockPos(p), DATA_SLEEPING_POS) if id == self.own.id => {
// (26.1 / 26.2: the block's centre + 0.6875, bed or not)
if let Some(b) = p
&& let Some(dy) = if SLEEP_ON_BED_ONLY {
sleep_height(&self.world, [b.x, b.y, b.z]).map(|h| h + 0.125)
} else {
Some(0.6875)
}
{
self.player.set_pos(
f64::from(b.x) + 0.5,
f64::from(b.y) + dy,
f64::from(b.z) + 0.5,
);
}
// isSleeping: the pose follows in the tick (updatePlayerPose)
self.ext.sleeping = p.is_some();
self.ext_active |= self.ext.sleeping;
self.sleep = Some(*p);
}
// Entity.DATA_POSE as the server sends it with a sleep or wake-up:
// setPose's refreshDimensions at once. Other poses: the client's own
// updatePlayerPose decides.
(V::Pose(pose), DATA_POSE)
if id == self.own.id
&& (*pose == 2 || self.player.pose == modern::Pose::Sleeping) =>
{
self.player.set_pose(match pose {
1 => modern::Pose::FallFlying,
2 => modern::Pose::Sleeping,
3 => modern::Pose::Swimming,
4 => modern::Pose::SpinAttack,
5 => modern::Pose::Crouching,
7 => modern::Pose::Dying,
_ => modern::Pose::Standing,
});
}
(V::Byte(b), DATA_LIVING_FLAGS) if id == self.own.id => {
self.ext.apply_living_flags(*b as u8);
self.ext_active |= self.ext.spin_attack;
}
(V::HumanoidArm(a), DATA_PLAYER_MAIN_HAND) if id == self.own.id => {
// HumanoidArm: LEFT 0, RIGHT 1.
self.own.main_arm_left = a.0 == 0;
}
(V::Boolean(b), DATA_BABY) if mount.is_some() => {
self.own.mounts[mount.unwrap_or(0)].baby = *b;
}
(V::Int(t), DATA_BOOST_TIME)
if mount.is_some_and(|k| {
EntityIds::get().steered.contains(&self.own.mounts[k].ty)
}) =>
{
// ItemBasedSteering.onSynced: a boost of `t` ticks starts.
self.own.mounts[mount.unwrap_or(0)].boost = Some(*t);
if let Some(Riding::Mount { id: rid, mount, .. }) = &mut self.riding
&& *rid == id
{
mount.set_boost_time(*t);
} else if self.parked.is_some_and(|p| p.id == id && p.living)
&& let Some(m) = &mut self.left_mount
{
m.set_boost_time(*t);
}
}
(V::Pose(_) | V::Long(_) | V::Boolean(_), _)
if mount.is_some_and(|k| {
EntityIds::get().horses[5..].contains(&self.own.mounts[k].ty)
}) && matches!(
e.key,
DATA_POSE | DATA_CAMEL_LAST_POSE | DATA_CAMEL_DASH
) =>
{
// A camel's pose, pose change tick and dash flag.
let k = mount.unwrap_or(0);
let target = match &mut self.riding {
Some(Riding::Mount { id: rid, mount, .. }) if *rid == id => {
Some(&mut **mount)
}
_ if self.parked.is_some_and(|p| p.id == id && p.living) => {
self.left_mount.as_deref_mut()
}
_ => None,
};
match e.value {
V::Pose(p) => {
self.own.mounts[k].camel_pose.0 = p == 10;
if let Some(m) = target {
m.set_camel_sitting(p == 10);
}
}
V::Long(t) => {
self.own.mounts[k].camel_pose.1 = t;
if let Some(m) = target {
m.set_last_pose_change_tick(t);
}
}
V::Boolean(b) => {
if let Some(m) = target {
m.set_dashing(b);
} else {
let g = self.tracked_on_ground(id);
self.own.dash_synced(k, b, self.player.age, g);
}
}
_ => {}
}
}
(V::Boolean(b), DATA_STAYS_STILL)
if mount.is_some_and(|k| {
self.own.mounts[k].ty == EntityIds::get().happy_ghast
}) =>
{
// HappyGhast.STAYS_STILL: kept still, the rider does not steer.
self.own.mounts[mount.unwrap_or(0)].stays_still = *b;
if let Some(Riding::Mount { id: rid, mount, .. }) = &mut self.riding
&& *rid == id
{
mount.set_stays_still(*b);
} else if self.parked.is_some_and(|p| p.id == id && p.living)
&& let Some(m) = &mut self.left_mount
{
m.set_stays_still(*b);
}
}
(V::Boolean(b), DATA_NAUTILUS_DASH)
if mount.is_some_and(|k| {
EntityIds::get().nautili.contains(&self.own.mounts[k].ty)
}) =>
{
// AbstractNautilus.DASH from the server: its dash cooldown starts.
if let Some(Riding::Mount { id: rid, mount, .. }) = &mut self.riding
&& *rid == id
{
mount.set_dash(*b);
} else if self.parked.is_some_and(|p| p.id == id && p.living)
&& let Some(m) = &mut self.left_mount
{
m.set_dash(*b);
} else if let Some(k) = mount {
let g = self.tracked_on_ground(id);
self.own.dash_synced(k, *b, self.player.age, g);
}
}
(V::Byte(f), DATA_MOUNT_FLAGS) if mount.is_some() => {
self.own.mounts[mount.unwrap_or(0)].flags = *f as u8;
if let Some(Riding::Mount { id: rid, mount, .. }) = &mut self.riding
&& *rid == id
{
mount.set_horse_flags(*f as u8);
}
}
(V::OptionalUnsignedInt(v), DATA_ATTACHED_TO_TARGET) => {
if let Some(k) = rocket
&& *v - 1 == self.own.id
{
let (rid, pos) = self.own.rockets.swap_remove(k);
let ok = self.ext.attach_rocket(rid, pos);
self.ext_active |= ok;
log::debug!("firework rocket {rid} attached to us ({ok})");
}
}
_ => {}
}
}
}
cb::id::SPAWN_ENTITY => {
let id = r.read_varint()?;
r.skip(16)?; // uuid
let ty = r.read_varint()?;
// Vehicles the player may ride (the full tracker knows them when it runs).
let ids = EntityIds::get();
if self.entities.is_none()
&& u16::try_from(ty)
.ok()
.and_then(super::data::entity_type)
.and_then(|t| vehicle_kind(t.name))
.is_some()
{
self.vehicle_tracker_mut().apply(raw)?;
if !ids.is_mount(ty) {
return Ok(());
}
}
if ids.is_mount(ty) {
self.own.mounts.retain(|m| m.id != id);
if self.own.mounts.len() >= MAX_MOUNTS {
self.own.mounts.remove(0);
}
self.own.mounts.push(Mount {
id,
ty,
baby: false,
flags: 0,
saddled: false,
attrs: Vec::new(),
boost: None,
stays_still: false,
camel_pose: (false, 0),
spawned: self.player.age,
dash: (0, false, self.player.age),
grounded: false,
});
self.filter_dirty |= self.own.mounts.len() == 1;
return Ok(());
}
if ty != ids.firework_rocket {
return Ok(());
}
let p: cb::SpawnEntity = raw.decode_as()?;
if self.own.rockets.len() >= MAX_PENDING_ROCKETS {
self.own.rockets.remove(0);
}
self.own.rockets.push((id, [p.x, p.y, p.z]));
}
cb::id::ENTITY_DESTROY => {
if self.own.rockets.is_empty()
&& self.ext.rocket_count() == 0
&& self.own.mounts.is_empty()
&& self.vehicles.is_none()
&& self.riding.is_none()
{
return Ok(());
}
let p: cb::EntityDestroy = raw.decode_as()?;
if let Some(v) = &mut self.vehicles {
v.apply(raw)?;
}
for id in p.entity_ids {
self.own.rockets.retain(|&(rid, _)| rid != id);
self.own.mounts.retain(|m| m.id != id);
self.ext.remove_rocket(id);
// The vehicle is gone: its passenger is off (removePassenger).
if self.riding.as_ref().is_some_and(|v| v.id() == id) {
self.riding = None;
}
if self.parked.is_some_and(|p| p.id == id) {
self.parked = None;
}
}
if self.vehicles.as_ref().is_some_and(|v| v.is_empty()) {
self.vehicles = None;
self.filter_dirty = true;
}
}
_ => {}
}
Ok(())
}
/// `ClientLevel.tickEntities` up to the player: the entities near it that tick before it
/// (before its root vehicle when riding) tick now, and their pushes act before its tick.
#[inline(never)]
pub(super) fn tick_before_player(&mut self, pose: &mut Pose) {
let Some(t) = &mut self.entities else { return };
let me = self.riding.as_ref().map_or(self.own.id, Riding::id);
let Some(me_seq) = t.tick_seq(me) else { return };
let p = &self.player;
let reach = |v: f64| v.abs() + 4.0;
let (rx, ry, rz) = (reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2]));
let pre = &mut self.around.pre;
pre.clear();
let mut found: Vec<(u64, i32)> = Vec::new();
for e in t.iter() {
let [x, y, z] = e.position();
if (x - p.pos[0]).abs() > rx + 2.0
|| (y - p.pos[1]).abs() > ry + 2.0
|| (z - p.pos[2]).abs() > rz + 2.0
{
continue;
}
if entity_bits(e) & (COLLIDES | PUSH_LIVING | PUSH_BOAT) == 0 && self.riding.is_none() {
continue;
}
let Some(seq) = t.tick_seq(e.id()).filter(|&q| q < me_seq) else {
continue;
};
found.push((seq, e.id()));
}
if found.is_empty() {
return;
}
found.sort_unstable();
let (world, level) = (&self.world, &self.player.level);
for &(_, id) in &found {
t.tick_early(id, |e, bb| block_free(world, level, e, bb));
pre.push(id);
}
if self.riding.is_none() {
self.push_player(pose, true);
}
}
/// The pushes of the entities that ticked after the player (`LivingEntity.pushEntities`,
/// `AbstractBoat.tick`), each with its box after its own tick.
#[inline(never)]
pub(super) fn push_player(&mut self, pose: &mut Pose, before: bool) {
if !self.entity_push {
return;
}
let p = &self.player;
let a = &mut self.around;
a.pushers.clear();
let parked = self.parked.as_ref();
// The boat the player left pushes from where it is (without the tracker, only it).
if let Some(k) = parked
&& !before
&& self.entities.as_ref().is_none_or(|t| t.get(k.id).is_none())
{
a.pushers.push((
i64::from(k.id),
modern::Pusher::new(
k.pos,
aabb(k.bb),
if k.living {
modern::PushKind::Living
} else {
modern::PushKind::Boat
},
),
None,
));
}
for e in self.entities.iter().flat_map(|t| t.iter()) {
let t = self.entities.as_ref().unwrap();
// Those that tick before the player pushed it before its tick.
if before != (!a.pre.is_empty() && a.pre.contains(&e.id())) {
continue;
}
let bits = entity_bits(e);
if bits & (PUSH_LIVING | PUSH_BOAT) == 0 {
continue;
}
let Some((pos, b)) = Parked::of(parked, e).or_else(|| entity_box(e)) else {
continue;
};
// Boats reach 0.2 farther; nothing else can touch the player.
let m = 0.25;
if b[3] < p.bb.min_x - m
|| b[0] > p.bb.max_x + m
|| b[4] < p.bb.min_y - m
|| b[1] > p.bb.max_y + m
|| b[5] < p.bb.min_z - m
|| b[2] > p.bb.max_z + m
{
continue;
}
// Only ticking entities push (their column is loaded).
if !t.is_ticking(e) {
continue;
}
// Entity.push: a spectator player has noPhysics (set in its tick) and pushes
// nothing. A dead or dying pusher still pushes (its aiStep runs until removed).
if t.is_spectator(e) {
continue;
}
// EntitySelector.pushableBy: the pusher's and the player's team collision rules.
if let Some(teams) = self.teams.as_deref().filter(|t| t.any_rule()) {
let mut buf = [0u8; 36];
if !teams.may_push(scoreboard_name(t, e, &mut buf), &self.profile_name) {
continue;
}
}
let kind = if bits & PUSH_BOAT != 0 {
modern::PushKind::Boat
} else {
modern::PushKind::Living
};
// In the client's tick order.
let seq = t.tick_seq(e.id()).map_or(i64::MAX, |q| q as i64);
// A mount or boat the client keeps a motion for, carrying nobody (`!isVehicle`):
// the same `Entity.push` pushes it too.
let half =
(e.passengers().is_empty() && t.client_motion(e.id()).is_some()).then_some(e.id());
a.pushers
.push((seq, modern::Pusher::new(pos, aabb(b), kind), half));
}
if a.pushers.is_empty() {
return;
}
a.pushers.sort_by_key(|x| x.0);
let p = &mut self.player;
let view = self
.world
.view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
let mut halves: Vec<(i32, [f64; 2])> = Vec::new();
for (_, pusher, half) in &a.pushers {
if let Some(d) = modern::push_by_pair::<Rules, _>(p, &self.ext, &view, pusher)
&& let Some(id) = half
{
halves.push((*id, d));
}
}
if let Some(t) = &mut self.entities {
for (id, d) in halves {
t.push_motion(id, d);
}
}
pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
}
}