ghast-world 0.5.3

Chunk storage for the ghast Minecraft Java Edition client library: compact, O(1) block lookup, explicit loaded/unloaded columns, decoding of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 chunk and block-change packets
Documentation
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Modern world packets: configuration registries, dimension changes, the chunk window and
//! batches, chunk loads / unloads, biomes, block entities, block and section updates, the
//! world border; the shared-section update path and `Drop`.

use super::*;

impl World {
    // ------------------------------------------------------------------ configuration

    /// Applies a configuration `registry_data` packet (every one must be routed here, also
    /// after a reconfiguration).
    pub fn apply_registry_data(&mut self, p: &RegistryData) -> Applied {
        self.apply_registry(&p.id, p.entries.iter().map(|e| (&*e.key, e.value.as_ref())))
    }

    /// [`World::apply_registry_data`] without the packet struct: registry id and
    /// `(key, data)` entries in order.
    pub fn apply_registry<'a>(
        &mut self,
        id: &str,
        entries: impl ExactSizeIterator<Item = (&'a str, Option<&'a AnonNbt>)>,
    ) -> Applied {
        match id {
            "minecraft:dimension_type" => {
                self.registries.dimension_types = entries
                    .map(|(k, v)| match v {
                        Some(nbt) => DimensionType::from_nbt(k, nbt),
                        None => DimensionType::vanilla(k),
                    })
                    .collect();
                Applied::Changed
            }
            "minecraft:world_clock" => {
                self.registries.world_clocks = entries.map(|(k, _)| k.to_string()).collect();
                Applied::Changed
            }
            "minecraft:worldgen/biome" => {
                self.registries.biome_count = entries.len();
                self.registries.biome_climates = entries
                    .map(|(k, v)| match v {
                        Some(nbt) => climate_from_nbt(nbt),
                        None => crate::climate::Climate::vanilla(k),
                    })
                    .collect();
                Applied::Changed
            }
            _ => Applied::NotWorldPacket,
        }
    }

    // ------------------------------------------------------------------ play

    /// Applies any world-relevant packet; other packets return [`Applied::NotWorldPacket`].
    ///
    /// `chunk_batch_finished` needs the arrival time: use [`World::on_chunk_batch_finished`]
    /// (here it is applied with time 0 and its answer is dropped).
    ///
    /// # Errors
    /// Malformed chunk data (the affected column is unloaded).
    pub fn handle(&mut self, packet: &ClientboundPlayPacket) -> Result<Applied, WorldError> {
        use ClientboundPlayPacket as P;
        match packet {
            P::Login(p) => Ok(self.apply_login(p)),
            P::Respawn(p) => Ok(self.apply_respawn(p)),
            P::MapChunk(p) => self.apply_map_chunk(p),
            P::UnloadChunk(p) => Ok(self.apply_unload_chunk(p)),
            P::BlockChange(p) => Ok(self.apply_block_change(p)),
            P::MultiBlockChange(p) => Ok(self.apply_multi_block_change(p)),
            P::ChunkBiomes(p) => self.apply_chunk_biomes(p),
            P::UpdateViewPosition(p) => Ok(self.apply_view_position(p)),
            P::UpdateViewDistance(p) => Ok(self.apply_view_distance(p)),
            P::ChunkBatchStart(_) => Ok(self.batch_start()),
            P::ChunkBatchFinished(p) => Ok(self.batch_finished(p.batch_size)),
            P::InitializeWorldBorder(p) => Ok(self.apply_initialize_border(p)),
            P::WorldBorderCenter(p) => Ok(self.apply_border_center(p)),
            P::WorldBorderLerpSize(p) => Ok(self.apply_border_lerp_size(p)),
            P::WorldBorderSize(p) => Ok(self.apply_border_size(p)),
            P::WorldBorderWarningDelay(p) => Ok(self.apply_border_warning_delay(p)),
            P::WorldBorderWarningReach(p) => Ok(self.apply_border_warning_reach(p)),
            P::TileEntityData(p) if self.config.block_entities => {
                Ok(self.apply_tile_entity_data(p))
            }
            _ => Ok(Applied::NotWorldPacket),
        }
    }

    /// Applies a world packet straight from its raw body. `map_chunk` is decoded here without
    /// its heightmaps and light (the cheap path: nothing after the block entities is read);
    /// other ids are decoded as their own packet type (no whole-protocol decoder is linked).
    ///
    /// # Errors
    /// A malformed packet or malformed chunk data.
    pub fn handle_raw(&mut self, raw: &RawPacket) -> Result<Applied, WorldError> {
        macro_rules! decode {
            ($t:ty) => {
                &raw.decode_as::<$t>().map_err(WorldError::Decode)?
            };
        }
        match raw.id {
            cb::id::MAP_CHUNK => self.apply_map_chunk_body(&raw.body),
            cb::id::LOGIN => Ok(self.apply_login(decode!(Login))),
            cb::id::RESPAWN => Ok(self.apply_respawn(decode!(Respawn))),
            cb::id::UNLOAD_CHUNK => Ok(self.apply_unload_chunk(decode!(UnloadChunk))),
            cb::id::BLOCK_CHANGE => Ok(self.apply_block_change(decode!(BlockChange))),
            cb::id::MULTI_BLOCK_CHANGE => {
                Ok(self.apply_multi_block_change(decode!(MultiBlockChange)))
            }
            cb::id::CHUNK_BIOMES => self.apply_chunk_biomes(decode!(ChunkBiomes)),
            cb::id::UPDATE_VIEW_POSITION => {
                Ok(self.apply_view_position(decode!(UpdateViewPosition)))
            }
            cb::id::UPDATE_VIEW_DISTANCE => {
                Ok(self.apply_view_distance(decode!(UpdateViewDistance)))
            }
            cb::id::CHUNK_BATCH_START => {
                let _: &cb::ChunkBatchStart = decode!(cb::ChunkBatchStart);
                Ok(self.batch_start())
            }
            cb::id::CHUNK_BATCH_FINISHED => {
                Ok(self.batch_finished(decode!(cb::ChunkBatchFinished).batch_size))
            }
            cb::id::INITIALIZE_WORLD_BORDER => {
                Ok(self.apply_initialize_border(decode!(InitializeWorldBorder)))
            }
            cb::id::WORLD_BORDER_CENTER => {
                Ok(self.apply_border_center(decode!(cb::WorldBorderCenter)))
            }
            cb::id::WORLD_BORDER_LERP_SIZE => {
                Ok(self.apply_border_lerp_size(decode!(cb::WorldBorderLerpSize)))
            }
            cb::id::WORLD_BORDER_SIZE => Ok(self.apply_border_size(decode!(cb::WorldBorderSize))),
            cb::id::WORLD_BORDER_WARNING_DELAY => {
                Ok(self.apply_border_warning_delay(decode!(cb::WorldBorderWarningDelay)))
            }
            cb::id::WORLD_BORDER_WARNING_REACH => {
                Ok(self.apply_border_warning_reach(decode!(cb::WorldBorderWarningReach)))
            }
            cb::id::TILE_ENTITY_DATA if self.config.block_entities => {
                Ok(self.apply_tile_entity_data(decode!(TileEntityData)))
            }
            _ => Ok(Applied::NotWorldPacket),
        }
    }

    fn batch_start(&mut self) -> Applied {
        self.on_chunk_batch_start(0);
        Applied::Changed
    }

    fn batch_finished(&mut self, size: i32) -> Applied {
        self.on_chunk_batch_finished(size, 0);
        Applied::Changed
    }

    /// `set_border_center`.
    pub fn apply_border_center(&mut self, p: &cb::WorldBorderCenter) -> Applied {
        #[cfg(feature = "physics")]
        self.collision_border.set_center(p.x, p.z);
        self.apply_border(&BorderPacket {
            action: 2,
            x: Some(p.x),
            z: Some(p.z),
            ..BorderPacket::EMPTY
        })
    }

    /// `set_border_lerp_size` (lerp time in ticks).
    pub fn apply_border_lerp_size(&mut self, p: &cb::WorldBorderLerpSize) -> Applied {
        #[cfg(feature = "physics")]
        self.collision_border
            .lerp_size(p.old_diameter, p.new_diameter, p.speed);
        self.apply_border(&BorderPacket {
            action: 1,
            old_diameter: Some(p.old_diameter),
            new_diameter: Some(p.new_diameter),
            speed_ms: Some(p.speed.saturating_mul(50)),
            ..BorderPacket::EMPTY
        })
    }

    /// `set_border_size`.
    pub fn apply_border_size(&mut self, p: &cb::WorldBorderSize) -> Applied {
        #[cfg(feature = "physics")]
        self.collision_border.set_size(p.diameter);
        self.apply_border(&BorderPacket {
            action: 0,
            diameter: Some(p.diameter),
            ..BorderPacket::EMPTY
        })
    }

    /// `set_border_warning_delay`.
    pub fn apply_border_warning_delay(&mut self, p: &cb::WorldBorderWarningDelay) -> Applied {
        self.apply_border(&BorderPacket {
            action: 4,
            warning_time: Some(p.warning_time),
            ..BorderPacket::EMPTY
        })
    }

    /// `set_border_warning_distance`.
    pub fn apply_border_warning_reach(&mut self, p: &cb::WorldBorderWarningReach) -> Applied {
        self.apply_border(&BorderPacket {
            action: 5,
            warning_blocks: Some(p.warning_blocks),
            ..BorderPacket::EMPTY
        })
    }

    fn apply_border(&mut self, p: &BorderPacket) -> Applied {
        changed(self.border.apply(p))
    }

    /// `initialize_border` (lerp time in ticks).
    pub fn apply_initialize_border(&mut self, p: &InitializeWorldBorder) -> Applied {
        // ClientPacketListener.handleInitializeBorder.
        #[cfg(feature = "physics")]
        {
            let b = &mut self.collision_border;
            b.set_center(p.x, p.z);
            if p.speed > 0 {
                b.lerp_size(p.old_diameter, p.new_diameter, p.speed);
            } else {
                b.set_size(p.new_diameter);
            }
        }
        self.apply_border(&BorderPacket {
            action: 3,
            x: Some(p.x),
            z: Some(p.z),
            old_diameter: Some(p.old_diameter),
            new_diameter: Some(p.new_diameter),
            speed_ms: Some(p.speed.saturating_mul(50)),
            portal_boundary: Some(p.portal_teleport_boundary),
            warning_time: Some(p.warning_time),
            warning_blocks: Some(p.warning_blocks),
            diameter: None,
        })
    }

    /// `chunk_batch_start` at `now_nanos`.
    pub fn on_chunk_batch_start(&mut self, now_nanos: i64) {
        self.batch.on_batch_start(now_nanos);
    }

    /// `chunk_batch_finished` at `now_nanos`: returns the `chunks_per_tick` the client must
    /// answer with (`chunk_batch_received`), as vanilla computes it.
    pub fn on_chunk_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        self.batch.on_batch_finished(batch_size, now_nanos)
    }

    fn enter(
        &mut self,
        name: &str,
        type_index: i32,
        view_distance: Option<i32>,
        (seed, sea_level): (i64, i32),
    ) -> Applied {
        self.clear();
        #[cfg(feature = "physics")]
        {
            self.collision_border = ghast_physics::modern::BorderState::new();
        }
        self.biome_zoom_seed = seed;
        self.sea_level = sea_level;
        self.border = Border::new(LerpMath::Double);
        let radius_distance = view_distance.unwrap_or(self.view.radius - 3);
        self.view = ViewWindow::new(radius_distance);
        let kind = usize::try_from(type_index)
            .ok()
            .and_then(|i| self.registries.dimension_types.get(i))
            .cloned()
            .flatten();
        self.dim = kind.map(|kind| Dimension {
            name: name.to_string(),
            type_index,
            kind,
        });
        self.min_y = self.dim.as_ref().map_or(0, |d| d.kind.min_y);
        Applied::Changed
    }

    /// Enters a dimension without a `login` packet (tests, offline planning): a new client
    /// level like [`World::apply_login`]; `type_index` names a `dimension_type` registry entry.
    pub fn enter_dimension(&mut self, name: &str, type_index: i32, view_distance: i32) -> Applied {
        self.enter(name, type_index, Some(view_distance), (0, 63))
    }

    /// [`World::enter_dimension`] with the spawn info's hashed seed (the biome zoom seed) and
    /// sea level.
    pub fn enter_dimension_with(
        &mut self,
        name: &str,
        type_index: i32,
        view_distance: i32,
        hashed_seed: i64,
        sea_level: i32,
    ) -> Applied {
        self.enter(
            name,
            type_index,
            Some(view_distance),
            (hashed_seed, sea_level),
        )
    }

    /// Join game: a new client level (everything unloaded, window centred on 0, 0).
    pub fn apply_login(&mut self, p: &Login) -> Applied {
        self.enter(
            &p.world_state.name,
            p.world_state.dimension,
            Some(p.view_distance),
            (p.world_state.hashed_seed, p.world_state.sea_level),
        )
    }

    /// Respawn: vanilla creates a new level only when the dimension (world name) changes.
    pub fn apply_respawn(&mut self, p: &Respawn) -> Applied {
        if self
            .dim
            .as_ref()
            .is_some_and(|d| d.name == *p.world_state.name)
        {
            return Applied::Ignored;
        }
        self.enter(
            &p.world_state.name,
            p.world_state.dimension,
            None,
            (p.world_state.hashed_seed, p.world_state.sea_level),
        )
    }

    /// `set_chunk_cache_center`: moves the window; columns outside it are dropped.
    pub fn apply_view_position(&mut self, p: &UpdateViewPosition) -> Applied {
        self.view.center = (p.chunk_x, p.chunk_z);
        self.purge_outside_window()
    }

    /// `set_chunk_cache_radius`: resizes the window; columns outside it are dropped.
    pub fn apply_view_distance(&mut self, p: &UpdateViewDistance) -> Applied {
        let center = self.view.center;
        self.view = ViewWindow::new(p.view_distance);
        self.view.center = center;
        self.purge_outside_window()
    }

    fn purge_outside_window(&mut self) -> Applied {
        let before = self.columns.len();
        let view = self.view;
        match &self.shared {
            None => self.columns.retain(|p| view.contains(p.x, p.z)),
            Some(cache) => {
                for col in self.columns.extract(|p| view.contains(p.x, p.z)) {
                    cache.release_column(col.sections);
                }
            }
        }
        changed(self.columns.len() != before)
    }

    /// `forget_level_chunk`.
    pub fn apply_unload_chunk(&mut self, p: &UnloadChunk) -> Applied {
        let col = self.columns.take(p.chunk_x, p.chunk_z);
        let was_loaded = col.is_some();
        self.release(col);
        changed(was_loaded)
    }

    /// `level_chunk_with_light` (decoded with the generated type; [`World::handle_raw`] skips
    /// the light data instead of decoding it).
    ///
    /// # Errors
    /// Malformed section data (the column is unloaded).
    pub fn apply_map_chunk(&mut self, p: &MapChunk) -> Result<Applied, WorldError> {
        let bes = p
            .block_entities
            .iter()
            .map(|b| (b.x, b.y, b.z, b.r#type, b.nbt_data.clone()));
        self.apply_chunk(p.x, p.z, &p.chunk_data, bes)
    }

    /// `level_chunk_with_light` from its raw body: block data and block entities only.
    ///
    /// # Errors
    /// A truncated packet or malformed section data (the column is unloaded).
    pub fn apply_map_chunk_body(&mut self, body: &Bytes) -> Result<Applied, WorldError> {
        let mut r = Reader::new(body);
        let head = (|| {
            let x = r.read_i32()?;
            let z = r.read_i32()?;
            let n = r.read_varint()?;
            for _ in 0..n {
                r.read_varint()?;
                let longs = r.read_varint()?;
                let longs = usize::try_from(longs)
                    .map_err(|_| ghast_protocol::DecodeError::Invalid("heightmap length"))?;
                r.skip(longs.saturating_mul(8))?;
            }
            let data = r.read_byte_array()?;
            Ok::<_, ghast_protocol::DecodeError>((x, z, data))
        })();
        let (x, z, data) = head.map_err(WorldError::Decode)?;
        if !self.config.block_entities {
            return self.apply_chunk(x, z, &data, std::iter::empty());
        }
        let mut bes = Vec::new();
        let list = (|| {
            let n = r.read_varint()?;
            for _ in 0..n {
                let xz = r.read_u8()?;
                let y = r.read_i16()?;
                let ty = r.read_varint()?;
                let nbt = AnonNbt::read_optional(&mut r)?;
                bes.push((xz >> 4, y, xz & 15, ty, nbt));
            }
            Ok::<_, ghast_protocol::DecodeError>(())
        })();
        list.map_err(WorldError::Decode)?;
        self.apply_chunk(x, z, &data, bes.into_iter())
    }

    fn apply_chunk(
        &mut self,
        x: i32,
        z: i32,
        data: &Bytes,
        block_entities: impl Iterator<Item = (u8, i16, u8, i32, Option<AnonNbt>)>,
    ) -> Result<Applied, WorldError> {
        let Some((min_y, height)) = self.dim.as_ref().map(|d| (d.kind.min_y, d.kind.height)) else {
            return Ok(Applied::Ignored);
        };
        if !self.view.contains(x, z) {
            return Ok(Applied::Ignored);
        }
        let layout = Layout {
            sections: (height >> 4) as usize,
            biome_bits: ceil_log2(self.registries.biome_count.max(1)),
            biome_count: self.registries.biome_count,
            keep_biomes: self.config.biomes,
        };
        let decoded = match &self.shared {
            None => decode_sections(&mut self.builder, data, &layout),
            Some(cache) => decode_sections_shared(&mut self.builder, cache, data, &layout),
        };
        let (sections, biomes) = match decoded {
            Ok(d) => d,
            Err((j, reason)) => {
                let old = self.columns.take(x, z);
                self.release(old);
                return Err(WorldError::Section {
                    pos: ChunkPos::new(x, z),
                    section: j.min(255) as u8,
                    reason,
                });
            }
        };
        let mut col = Column {
            sections,
            cold: None,
        };
        col.set_stored_biomes(biomes.map(Vec::into_boxed_slice));
        if self.config.block_entities {
            for (bx, y, bz, ty, nbt) in block_entities {
                let ry = i32::from(y) - min_y;
                let Some(nbt) = nbt.filter(|n| !n.is_end()) else {
                    continue;
                };
                if !(0..height).contains(&ry) {
                    continue;
                }
                col.put_block_entity(
                    be_key(i32::from(bx), ry, i32::from(bz)),
                    BlockEntity::Nbt {
                        action: u8::try_from(ty).unwrap_or(u8::MAX),
                        // A copy of its own: a slice would keep the whole packet buffer alive.
                        nbt: Bytes::copy_from_slice(nbt.as_bytes()),
                    },
                );
            }
        }
        let old = self.columns.replace(x, z, col);
        self.release(old);
        Ok(Applied::Changed)
    }

    /// `chunks_biomes`: replaces the biomes of loaded columns (ignored without
    /// [`WorldConfig::biomes`]).
    ///
    /// # Errors
    /// Malformed biome data (the column's biomes are dropped).
    pub fn apply_chunk_biomes(&mut self, p: &ChunkBiomes) -> Result<Applied, WorldError> {
        if !self.config.biomes {
            return Ok(Applied::Ignored);
        }
        let Some(height) = self.height() else {
            return Ok(Applied::Ignored);
        };
        let n = (height >> 4) as usize;
        let bits = ceil_log2(self.registries.biome_count.max(1));
        let count = self.registries.biome_count;
        let mut any = false;
        for e in &p.biomes {
            let (cx, cz) = (e.position.x, e.position.z);
            if !self.view.contains(cx, cz) {
                continue;
            }
            let Some(col) = self.columns.get_mut(cx, cz) else {
                continue;
            };
            let mut r = Reader::new(&e.data);
            let mut v = Vec::with_capacity(n);
            for j in 0..n {
                match read_biomes(&mut r, bits, count) {
                    Ok(b) => v.push(b),
                    Err(reason) => {
                        col.set_stored_biomes(None);
                        return Err(WorldError::Section {
                            pos: ChunkPos::new(cx, cz),
                            section: j.min(255) as u8,
                            reason,
                        });
                    }
                }
            }
            col.set_stored_biomes(Some(v.into_boxed_slice()));
            any = true;
        }
        Ok(changed(any))
    }

    /// The block entity at a position (`None` when absent or the column is not loaded).
    #[must_use]
    pub fn block_entity(&self, x: i32, y: i32, z: i32) -> Option<&BlockEntity> {
        let ry = y.checked_sub(self.min_y()?)?;
        let k = be_key(x, ry, z);
        self.columns
            .get(x >> 4, z >> 4)?
            .stored_block_entities()
            .iter()
            .find(|(key, _)| *key == k)
            .map(|(_, b)| b)
    }

    /// `block_entity_data` (with [`WorldConfig::block_entities`]): stored for a loaded column
    /// whatever the block is (vanilla only loads it into an existing block entity of that type).
    pub fn apply_tile_entity_data(&mut self, p: &TileEntityData) -> Applied {
        if !self.config.block_entities {
            return Applied::Ignored;
        }
        let Some((min_y, height)) = self.dim.as_ref().map(|d| (d.kind.min_y, d.kind.height)) else {
            return Applied::Ignored;
        };
        let l = p.location;
        let ry = l.y.wrapping_sub(min_y);
        let Some(nbt) = p.nbt_data.as_ref().filter(|n| !n.is_end()) else {
            return Applied::Ignored;
        };
        if !(0..height).contains(&ry) {
            return Applied::Ignored;
        }
        let Some(col) = self.columns.get_mut(l.x >> 4, l.z >> 4) else {
            return Applied::Ignored;
        };
        col.put_block_entity(
            be_key(l.x, ry, l.z),
            BlockEntity::Nbt {
                action: u8::try_from(p.action).unwrap_or(u8::MAX),
                // A copy of its own: a slice would keep the whole packet buffer alive.
                nbt: Bytes::copy_from_slice(nbt.as_bytes()),
            },
        );
        Applied::Changed
    }

    /// Sets a block locally (client-side prediction). Returns `false` and does nothing when
    /// the column is not loaded or `y` is outside the build height.
    pub fn set_block_state(&mut self, x: i32, y: i32, z: i32, s: BlockState) -> bool {
        self.set_raw(x, y, z, s.id())
    }

    fn set_raw(&mut self, x: i32, y: i32, z: i32, raw: u16) -> bool {
        let Some(min_y) = self.min_y() else {
            return false;
        };
        let Some(col) = self.columns.get_mut(x >> 4, z >> 4) else {
            return false;
        };
        let ry = y.wrapping_sub(min_y);
        if ry < 0 {
            return false;
        }
        let j = (ry >> 4) as usize;
        let i = block_index(x, ry, z);
        let old = match &self.shared {
            None => {
                let Some(s) = sections_mut(&mut col.sections).get_mut(j) else {
                    return false;
                };
                s.set(i, raw)
            }
            Some(cache) => {
                let Some(s) = col.sections.get(j) else {
                    return false;
                };
                let old = s.get(i);
                // A section of the store moves to the shared section with this change; a
                // section this world owns is changed in place.
                if old != raw
                    && !cache.update(
                        super::PROTOCOL,
                        &mut col.sections,
                        j,
                        std::iter::once((i, raw)),
                        None,
                    )
                {
                    sections_mut(&mut col.sections)[j].set(i, raw);
                }
                old
            }
        };
        if col.has_block_entities() && !same_block(old, raw) {
            let k = be_key(x, ry, z);
            if let Some(c) = &mut col.cold {
                c.block_entities.retain(|(key, _)| *key != k);
            }
        }
        true
    }

    /// `block_update`. Unknown state ids read as air; unloaded columns are ignored.
    pub fn apply_block_change(&mut self, p: &BlockChange) -> Applied {
        changed(self.set_raw(
            p.location.x,
            p.location.y,
            p.location.z,
            raw_from_wire(i64::from(p.r#type)),
        ))
    }

    /// `section_blocks_update` (section position + `state << 12 | x << 8 | z << 4 | y`).
    pub fn apply_multi_block_change(&mut self, p: &MultiBlockChange) -> Applied {
        let c = &p.chunk_coordinates;
        let sy = (c.y << 12) >> 12;
        if !self.columns.contains(c.x, c.z) {
            return Applied::Ignored;
        }
        if self.shared.is_some() && self.update_section_shared(c.x, sy, c.z, &p.records) {
            return changed(!p.records.is_empty());
        }
        let mut any = false;
        for &r in &p.records {
            let local = (r & 0xFFF) as i32;
            let y = sy.wrapping_mul(16).wrapping_add(local & 15);
            any |= self.set_raw(
                c.x.wrapping_mul(16) | ((local >> 8) & 15),
                y,
                c.z.wrapping_mul(16) | ((local >> 4) & 15),
                raw_from_wire(((r as u64) >> 12) as i64),
            );
        }
        changed(any)
    }
}

impl World {
    /// `section_blocks_update` for a section of the store: every record in one step, so that
    /// the worlds that receive the same packet end up sharing one section again (and a world
    /// copies the section at most once per packet). `false` when this is not possible (the
    /// section is outside the column or owned by this world): the caller then applies the
    /// records one by one.
    fn update_section_shared(&mut self, cx: i32, sy: i32, cz: i32, records: &[i64]) -> bool {
        let (Some(cache), Some(min_y)) = (&self.shared, self.min_y()) else {
            return false;
        };
        // `ry = sy * 16 + local y - min_y` is in one section for every record only when the
        // dimension starts on a section boundary (vanilla requires it).
        let base = sy.wrapping_mul(16).wrapping_sub(min_y);
        if min_y & 15 != 0 || base < 0 {
            return false;
        }
        let Some(col) = self.columns.get_mut(cx, cz) else {
            return false;
        };
        let j = (base >> 4) as usize;
        if j >= col.sections.len() {
            return false;
        }
        let recs = records.iter().map(|&r| {
            let local = (r & 0xFFF) as i32;
            (
                block_index((local >> 8) & 15, local & 15, (local >> 4) & 15),
                raw_from_wire(((r as u64) >> 12) as i64),
            )
        });
        let Column { sections, cold } = col;
        let has_block_entities = cold.as_ref().is_some_and(|c| !c.block_entities.is_empty());
        let mut drop_block_entity = |i: usize, old: u16, new: u16| {
            if !same_block(old, new)
                && let Some(c) = cold
            {
                // `be_key` of the block: its row above `min_y`, then z and x as in the index.
                let k = ((base as u32 + (i >> 8) as u32) << 8) | (i & 0xFF) as u32;
                c.block_entities.retain(|(key, _)| *key != k);
            }
        };
        cache.update(
            super::PROTOCOL,
            sections,
            j,
            recs,
            has_block_entities.then_some(&mut drop_block_entity as &mut dyn FnMut(usize, u16, u16)),
        )
    }
}

impl Drop for World {
    fn drop(&mut self) {
        // Hands the section arrays back to the store (see `SharedChunks::release_column`).
        self.clear();
    }
}