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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! The creative inventory screen of 1.8.9 (window 0 opened in creative mode), as the real
//! client drives it: `CreativeInventoryScreen.onMouseClick`, its `CreativeInventoryListener` on
//! window 0 (every slot that differs from window 0's tracked stacks is sent as a
//! `creative_inventory_action` when the handler broadcasts), the item tabs' own cursor rules and
//! the pick block key. Proven against the oracle's `clicks_creative_seed1.jsonl.gz`.
//!
//! A child module of `inventory` (it reads the inventory's private state).
use super::{ClickError, CreativePacket, Inventory, Outgoing, ScreenState};
use crate::rules::Version;
use crate::sim::{Layout, OUTSIDE, Screen, Sim};
use crate::stack::Stack;
/// The page the creative inventory screen shows (1.8.9 – 1.16.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CreativeTab {
/// The survival inventory tab: window 0's slots (5 ..) and the delete slot
/// ([`Inventory::creative_delete_slot`]). Clicks use window 0's slot numbers.
Inventory,
/// Any item tab (building blocks, tools, …): the menu (slots 0..45, clicked with
/// [`Inventory::creative_menu_click`]) and the hotbar row (slots 45..54).
Items,
}
/// The legacy creative screen's state; allocated at its first open.
#[derive(Debug, Clone)]
pub(crate) struct CreativeLegacy {
/// Window 0's tracked stacks (`ScreenHandler.trackedStacks`: what its last broadcast saw).
tracked: Vec<Option<Stack>>,
/// The screen is open.
pub(super) open: bool,
/// The selected tab (a static of the screen class: kept between openings).
tab: CreativeTab,
/// Packets the screen sent outside a click (the broadcast after opening).
echo: Vec<CreativePacket>,
}
impl CreativeLegacy {
fn new(len: usize) -> CreativeLegacy {
CreativeLegacy {
tracked: vec![None; len],
open: false,
// `selectedTab` starts at the building blocks tab
tab: CreativeTab::Items,
echo: Vec::new(),
}
}
/// A new player entity: a new window 0 (nothing tracked); the tab is a static and stays.
pub(crate) fn respawned(mut self: Box<Self>) -> Box<Self> {
self.tracked.iter_mut().for_each(|s| *s = None);
self.open = false;
self.echo.clear();
self
}
}
/// A stack the screen drops (`dropCreativeStack`: slot -1), after the arm swing 1.16.5's
/// `PlayerEntity.dropItem` sends on the client for a non-empty stack.
fn drop_into(v: Version, out: &mut Vec<CreativePacket>, item: Option<Stack>) {
if v == Version::V1_16_5 && item.as_ref().is_some_and(|s| s.count > 0) {
out.push(CreativePacket::Swing);
}
out.push(CreativePacket::SetSlot { slot: -1, item });
}
/// `ItemStack.equalsAll` (1.8): count, item, damage and NBT.
fn equals_all(a: Option<&Stack>, b: Option<&Stack>) -> bool {
crate::stack::stacks_equal(a, b)
}
impl Inventory {
/// Whether the open screen is the legacy creative inventory screen, and its tab.
#[must_use]
pub fn creative_screen_legacy(&self) -> Option<CreativeTab> {
self.creative16.as_ref().filter(|c| c.open).map(|c| c.tab)
}
/// The slot number of the creative inventory tab's delete slot (window 0's length): a
/// click drops the cursor stack, a shift-click asks the server to clear every window 0
/// slot.
#[must_use]
pub fn creative_delete_slot(&self) -> i16 {
Layout::new(self.version, Screen::Player).len as i16
}
/// The packets the legacy creative screen sent outside a click since the last call (the
/// listener's broadcast when the screen opened); send them right after the packet
/// [`Inventory::open_inventory`] returned.
pub fn take_creative_echo_legacy(&mut self) -> Vec<CreativePacket> {
self.creative16
.as_mut()
.map(|c| std::mem::take(&mut c.echo))
.unwrap_or_default()
}
/// Opening window 0 in creative mode (the inventory key): the survival screen the key
/// opens replaces itself with the creative screen, whose listener broadcasts.
pub(super) fn open_creative_legacy(&mut self) -> Option<Outgoing> {
let len = Layout::new(self.version, Screen::Player).len;
// the survival screen's `removed()`: `PlayerScreenHandler.close` (cursor dropped, the
// result cleared; 1.8 also drops the crafting grid, later versions only on the server)
let mut out = Vec::new();
if let Some(c) = self.m.cursor.take() {
self.events.cursor_changed = true;
// 1.16.5: `PlayerEntity.dropItem` swings on the client
if self.version == Version::V1_16_5 && c.count > 0 {
out.push(CreativePacket::Swing);
}
}
if self.m.craft_result.take().is_some() {
self.events.player_changed = true;
}
if self.version == Version::V1_8 {
if self.m.craft.iter().any(Option::is_some) {
self.events.player_changed = true;
}
self.m.craft = Default::default();
}
let c = self
.creative16
.get_or_insert_with(|| Box::new(CreativeLegacy::new(len)));
c.open = true;
self.screen = ScreenState::Inventory;
self.flags.opened = true;
self.creative_broadcast_legacy(&mut out);
if let Some(c) = &mut self.creative16 {
c.echo = out;
}
(self.version == Version::V1_8).then_some(Outgoing::OpenInventory)
}
/// `PlayerScreenHandler.sendContentUpdates` with the creative listener.
fn creative_broadcast_legacy(&mut self, out: &mut Vec<CreativePacket>) {
let lay = Layout::new(self.version, Screen::Player);
let Some(c) = &mut self.creative16 else {
return;
};
for (i, t) in c.tracked.iter_mut().enumerate().take(lay.len) {
let Some(l) = lay.loc(i) else { break };
let cur = self.m.at(l);
if !equals_all(t.as_ref(), cur.as_ref()) {
*t = cur.clone();
out.push(CreativePacket::SetSlot {
slot: i as i16,
item: cur.clone(),
});
}
}
}
/// `onScreenHandlerSlotUpdate` with the creative screen open: on an item tab window 0
/// slots outside the hotbar are not applied (the open handler is the creative one, whose
/// slots are the menu); 1.16.5 also ignores the cursor.
pub(super) fn creative_items_ignore_legacy(&self, window_id: i32, slot: i16) -> bool {
let Some(tab) = self.creative_screen_legacy() else {
return false;
};
// 1.16.5: the server's cursor is ignored while the creative screen is open
(window_id == -1 && self.version == Version::V1_16_5)
|| (window_id == 0 && !(36..45).contains(&slot) && tab == CreativeTab::Items)
}
/// Selects the creative screen's tab (no packet). The tab is kept while the screen is
/// closed (vanilla keeps it in a static), so this also chooses the tab the next opening
/// shows; the first opening shows an item tab.
pub fn set_creative_tab_legacy(&mut self, tab: CreativeTab) {
let len = Layout::new(self.version, Screen::Player).len;
self.creative16
.get_or_insert_with(|| Box::new(CreativeLegacy::new(len)))
.tab = tab;
}
/// 1.16.5: the swings of a window click's drops (`PlayerEntity.dropItem` on the client): a
/// throw that took items from its slot, a pickup click outside with a carried stack.
pub(super) fn drop_swings_1_16(
&self,
post: &crate::sim::Model,
lay: Layout,
slot: i16,
button: u8,
mode: u8,
) -> u8 {
if self.version != Version::V1_16_5 {
return 0;
}
let dropped = match mode {
0 | 1 => slot == OUTSIDE && button <= 1 && self.m.cursor.is_some(),
4 => {
self.m.cursor.is_none()
&& usize::try_from(slot).ok().is_some_and(|i| {
let Some(l) = lay.loc(i) else { return false };
let n = |m: &crate::sim::Model| m.at(l).as_ref().map_or(0, |s| s.count);
// a result slot is refilled at once (trade output, stonecutter, ...):
// taken when its inputs were consumed
let refilled = matches!(
lay.kind(i),
crate::SlotKind::CraftResult
| crate::SlotKind::TradeOutput
| crate::SlotKind::MenuResult
) && n(post) > 0
&& (post.container != self.m.container || post.craft != self.m.craft);
n(&self.m) > 0 && (n(post) < n(&self.m) || refilled)
})
}
_ => false,
};
u8::from(dropped)
}
/// 1.16.5: a server window replacing the open screen drops the carried stack on the client
/// (the old screen's `removed()` closes its handler: `PlayerEntity.dropItem` swings).
#[cfg(feature = "v1_16_5")]
pub(crate) fn carried_drop_swing(&self) -> bool {
self.version == Version::V1_16_5
&& self.screen != ScreenState::None
&& self.m.cursor.as_ref().is_some_and(|c| c.count > 0)
}
/// Runs window 0's click on a scratch model (`None`: ghast cannot predict it).
fn creative_window0_click(&mut self, slot: i16, button: u8, mode: u8) -> Option<()> {
let lay = Layout::new(self.version, Screen::Player);
let mut m = self.m.clone();
let r = {
let mut sim = Sim {
v: self.version,
lay,
m: &mut m,
book: &self.book,
binding_curse: None,
tags: self.tags16.as_deref(),
};
sim.click(slot, button, mode)
};
r.ok()?;
self.commit(m, lay);
Some(())
}
/// A click in the legacy creative screen ([`Inventory::click`] routes here while it is
/// open).
pub(super) fn creative_click_legacy(
&mut self,
slot: i16,
button: u8,
mode: u8,
) -> Result<Outgoing, ClickError> {
let tab = self.creative_screen_legacy().ok_or(ClickError::NoScreen)?;
let v = self.version;
if mode == 5 {
// drags are not modelled on the legacy versions
return Err(ClickError::Unpredictable);
}
if mode == 2 && button >= 9 && !(self.version == Version::V1_16_5 && button == 40) {
return Err(ClickError::InvalidButton);
}
let len = Layout::new(self.version, Screen::Player).len as i16;
let mut out = Vec::new();
let shift = mode == 1;
let mode = if slot == OUTSIDE && mode == 0 {
4
} else {
mode
};
match tab {
CreativeTab::Inventory => {
let delete = len;
// the crafting grid and result (0..5) are not on this tab
if slot != OUTSIDE && !(5..=delete).contains(&slot) {
return Err(ClickError::InvalidSlot);
}
if slot == delete && shift {
// asks the server to clear every slot; nothing changes here
for i in 0..len {
out.push(CreativePacket::SetSlot {
slot: i,
item: None,
});
}
} else if slot == delete {
if self.m.cursor.take().is_some() {
self.events.cursor_changed = true;
}
} else if mode == 4
&& let Some(l) = usize::try_from(slot)
.ok()
.and_then(|i| Layout::new(self.version, Screen::Player).loc(i))
&& let Some(st) = self.m.at(l).clone()
{
// `slot.takeStack(button == 0 ? 1 : max)`, then dropped
let n = if button == 0 {
1
} else {
self.version.max_count(&st)
};
let s = self.m.at_mut(l);
let dropped = if st.count <= n {
s.take()
} else {
if let Some(x) = s {
x.count -= n;
}
Some(st.with_count(n))
};
self.events.player_changed = true;
drop_into(v, &mut out, dropped);
if self.version != Version::V1_8 {
// 1.12+: the slot's rest goes out at once
out.push(CreativePacket::SetSlot {
slot,
item: self.m.at(l).clone(),
});
}
} else if mode == 4
&& let Some(c) = self.m.cursor.take()
{
self.events.cursor_changed = true;
drop_into(v, &mut out, Some(c));
} else {
let lay = Layout::new(v, Screen::Player);
let pre = self.m.clone();
self.creative_window0_click(slot, button, mode)
.ok_or(ClickError::Unpredictable)?;
let post = std::mem::replace(&mut self.m, pre);
let swings = self.drop_swings_1_16(&post, lay, slot, button, mode);
self.m = post;
for _ in 0..swings {
out.push(CreativePacket::Swing);
}
self.creative_broadcast_legacy(&mut out);
}
}
CreativeTab::Items => {
if slot == OUTSIDE {
if let Some(c) = &mut self.m.cursor {
if button == 0 {
let c = self.m.cursor.take();
drop_into(v, &mut out, c);
} else if button == 1 {
let one = c.with_count(1);
c.count -= 1;
// 1.8 empties only at exactly 0 (a zero-count stack goes to -1)
if c.count == 0 || (v != Version::V1_8 && c.count < 0) {
self.m.cursor = None;
}
drop_into(v, &mut out, Some(one));
}
self.events.cursor_changed = true;
}
} else {
if !(45..54).contains(&slot) {
return Err(ClickError::InvalidSlot);
}
let k = (slot - 45) as usize;
let w0 = 36 + k as i16;
let before = self.m.player[k].clone();
// 1.16.5: the handler's throw drops through `PlayerEntity.dropItem` (a swing)
if v == Version::V1_16_5
&& mode == 4
&& self.m.cursor.is_none()
&& before.is_some()
{
out.push(CreativePacket::Swing);
}
// 1.12+ swap with an over-stacked hotbar stack (above the slot limit): the
// clicked stack is inserted into the inventory instead of moving
let spill = (self.version != Version::V1_8
&& mode == 2
&& before.is_some()
&& self.m.player[usize::from(button)]
.as_ref()
.is_some_and(|h| h.count > 64))
.then(|| self.m.player.clone());
match mode {
// `transferSlot` of the creative handler empties a hotbar slot
1 if button <= 1 => {
if self.m.player[k].take().is_some() {
self.events.player_changed = true;
}
}
1 => {}
6 => self.creative_hotbar_pickup_all(k, button),
_ => {
self.creative_window0_click(w0, button, mode)
.ok_or(ClickError::Unpredictable)?;
}
}
if button & 3 == 2 {
// `unpackButtonId(button) == 2` (the drag header bits): the whole row
for (j, st) in self.m.player[..9].iter().enumerate() {
out.push(CreativePacket::SetSlot {
slot: 36 + j as i16,
item: st.clone(),
});
}
} else {
out.push(CreativePacket::SetSlot {
slot: w0,
item: self.m.player[k].clone(),
});
if self.version != Version::V1_8 {
// 1.12+: the screen kept the clicked slot's stack object from before
// the click: a swap sends it for the other slot (where it moved), a
// throw drops a copy of what is left of it (the throw split it);
// then window 0 broadcasts
if mode == 2 {
let moved = match (&spill, &before) {
// what of it the inventory did not take (dropped)
(Some(pre), Some(b)) => {
let like = |x: &Option<Stack>| {
x.as_ref()
.filter(|x| {
x.id == b.id
&& x.damage == b.damage
&& x.nbt_eq(b)
})
.map_or(0, |x| x.count)
};
let gained: i32 = (0..36)
.filter(|&i| i != k)
.map(|i| like(&self.m.player[i]) - like(&pre[i]))
.sum();
// a swap with itself split the stack first
let held = if usize::from(button) == k {
b.count - 64
} else {
b.count
};
let left = held - gained;
(left > 0).then(|| b.with_count(left))
}
_ => before.clone(),
};
out.push(CreativePacket::SetSlot {
slot: 36 + i16::from(button),
item: moved,
});
} else if mode == 4
&& before.is_some()
&& let Some(b) = &self.m.player[k]
{
let n = if button == 0 {
1
} else {
self.version.max_count(b)
};
drop_into(v, &mut out, Some(b.with_count(n)));
}
self.creative_broadcast_legacy(&mut out);
}
}
}
}
}
self.flags.clicked = true;
Ok(Outgoing::Creative(out))
}
/// Double click on a hotbar slot of an item tab: the creative handler gathers only from
/// its hotbar row (`canInsertIntoSlot(stack, slot)`: the slot is below y 90).
fn creative_hotbar_pickup_all(&mut self, k: usize, button: u8) {
let v = self.version;
let Some(mut c) = self.m.cursor.clone() else {
return;
};
if self.m.player[k].is_some() {
// the clicked slot holds a stack: no gathering
return;
}
let max = v.max_count(&c);
for pass in 0..2 {
let order: [usize; 9] = if button == 0 {
[0, 1, 2, 3, 4, 5, 6, 7, 8]
} else {
[8, 7, 6, 5, 4, 3, 2, 1, 0]
};
for x in order {
if c.count >= max {
break;
}
let Some(t) = &self.m.player[x] else { continue };
if !(c.id == t.id && c.damage == t.damage && t.nbt_eq(&c) && t.count <= max) {
continue;
}
if pass == 0 && t.count == v.max_count(t) {
continue;
}
let u = (max - c.count).min(t.count);
let s = &mut self.m.player[x];
if let Some(t) = s {
t.count -= u;
if t.count <= 0 {
*s = None;
}
}
c.count += u;
self.events.player_changed = true;
}
}
self.m.cursor = Some(c);
self.events.cursor_changed = true;
}
/// A click on the menu of a creative item tab: the menu slot shows `menu` (a stack of the
/// tab's item list; the server takes whatever the client sends, so any stack works). Pick
/// up / shift / double click set the cursor (no packet), the number keys put a full stack
/// into the hotbar (window 0 broadcasts), middle click clones, the drop key drops a copy.
///
/// # Errors
/// [`ClickError::NoScreen`] when no legacy creative item tab is open;
/// [`ClickError::InvalidSlot`] for a drag; [`ClickError::SameTick`] for a second action in
/// a tick.
pub fn creative_menu_click(
&mut self,
menu: Option<Stack>,
click: super::Click,
) -> Result<Outgoing, ClickError> {
self.can_click()?;
if self.creative_screen_legacy() != Some(CreativeTab::Items) {
return Err(ClickError::NoScreen);
}
let (_, button, mode) = click.wire();
if mode == 5 {
return Err(ClickError::InvalidSlot);
}
let v = self.version;
let mut out = Vec::new();
let full = mode == 1;
// 1.12+: a menu slot holding a locked stack (the saved toolbars' placeholder) cannot
// be taken from
if v != Version::V1_8
&& menu
.as_ref()
.is_some_and(|s| s.has_compound_tag("CustomCreativeLock"))
{
self.flags.clicked = true;
return Ok(Outgoing::Creative(out));
}
let legacy18 = v == Version::V1_8;
match mode {
2 => {
// 1.16.5 takes any button (40: the offhand)
if let Some(s) = &menu
&& (button < 9 || v == Version::V1_16_5 && button == 40)
{
self.m.player[usize::from(button)] = Some(s.with_count(v.max_count(s)));
self.events.player_changed = true;
self.creative_broadcast_legacy(&mut out);
}
}
3 => {
if self.m.cursor.is_none()
&& let Some(s) = &menu
{
self.m.cursor = Some(s.with_count(v.max_count(s)));
self.events.cursor_changed = true;
}
}
4 => {
if let Some(s) = &menu {
let n = if button == 0 { 1 } else { v.max_count(s) };
drop_into(v, &mut out, Some(s.with_count(n)));
}
}
_ => {
let cursor = self.m.cursor.take();
self.m.cursor = match (cursor, &menu) {
// same item and damage (1.12+: and NBT)
(Some(mut c), Some(s))
if c.id == s.id && c.damage == s.damage && (legacy18 || c.nbt_eq(s)) =>
{
let max = v.max_count(&c);
if button == 0 {
if full {
c.count = max;
} else if c.count < max {
c.count += 1;
}
Some(c)
} else if c.count <= 1 {
None
} else {
c.count -= 1;
Some(c)
}
}
(None, Some(s)) => {
let mut c = s.clone();
if full {
c.count = v.max_count(&c);
}
Some(c)
}
// 1.12+: the right button takes one off the cursor
(Some(mut c), _) if !legacy18 && button != 0 => {
c.count -= 1;
(c.count > 0).then_some(c)
}
_ => None,
};
self.events.cursor_changed = true;
}
}
self.flags.clicked = true;
Ok(Outgoing::Creative(out))
}
/// The pick block key (no screen open) for a target whose pick stack is `pick` (1.8: its
/// item and damage; `has_data`: the item has subtypes, so the damage must match too, as
/// 1.8 `doPick` passes it; 1.12.2: the whole stack, NBT included, the damage compared for
/// items with subtypes). 1.8 `PlayerInventory.addPickBlock` / 1.12 `method_13250` select a
/// hotbar slot that holds it or, in creative mode, put it into the selected (or first
/// empty) hotbar slot; in creative mode the selected slot is then sent. Returns the packet
/// (`None` in survival); the selected hotbar slot may change ([`Inventory::selected`]): the
/// client then sends `held_item_change`.
///
/// # Errors
/// [`ClickError::WindowOpen`] when a screen is open; [`ClickError::Unpredictable`] for a
/// 1.12.2 survival pick of a stack outside the hotbar (`MC|PickItem`, not modelled) and on
/// other versions.
pub fn pick_block_legacy(
&mut self,
pick: &Stack,
has_data: bool,
) -> Result<Option<Outgoing>, ClickError> {
if self.screen != ScreenState::None {
return Err(ClickError::WindowOpen);
}
match self.version {
Version::V1_8 => self.pick_1_8(pick.id, pick.damage, has_data),
Version::V1_12 | Version::V1_16_5 => self.pick_1_12(pick)?,
_ => return Err(ClickError::Unpredictable),
}
if !self.m.creative {
return Ok(None);
}
let sel = usize::from(self.m.selected);
Ok(Some(Outgoing::Creative(vec![CreativePacket::SetSlot {
slot: 36 + sel as i16,
item: self.m.player[sel].clone(),
}])))
}
fn pick_1_8(&mut self, item: i32, data: i16, has_data: bool) {
let creative = self.m.creative;
// the selected slot may move below (while `p` borrows the slots)
self.m.player.touch();
let p = &self.m.player;
let with = |id: i32, d: Option<i16>| {
(0..36).find(|&i| {
p[i].as_ref()
.is_some_and(|s| s.id == id && d.is_none_or(|d| s.damage == d))
})
};
let sel = usize::from(self.m.selected);
let held = p[sel].clone();
let found = with(item, has_data.then_some(data));
if let Some(i) = found.filter(|&i| i < 9) {
self.m.selected = i as u8;
} else if creative {
if let Some(j) = (0..36).find(|&i| p[i].is_none()).filter(|&j| j < 9) {
self.m.selected = j as u8;
}
let sel = usize::from(self.m.selected);
let keep = held.as_ref().is_some_and(|h| {
self.enchantable_1_8(h) && with(h.id, Some(h.damage)) == Some(sel)
});
if !keep {
let (n, from) = match with(item, Some(data)) {
Some(k) => (self.m.player[k].as_ref().map_or(1, |s| s.count), Some(k)),
None => (1, None),
};
if let Some(k) = from {
self.m.player[k] = self.m.player[sel].clone();
}
self.m.player[sel] = Some(Stack::new(item, n, data));
self.events.player_changed = true;
}
}
}
/// 1.12 `doPick`'s tail: `method_13253` (the first slot holding the stack) and, in
/// creative mode, `method_13250`.
fn pick_1_12(&mut self, pick: &Stack) -> Result<(), ClickError> {
let v = self.version;
// 1.16.5 `areItemsEqual`: item and tag (the damage is a tag)
let same = |s: &Stack| {
s.id == pick.id
&& (v == Version::V1_16_5 || !v.has_subtypes(pick.id) || s.damage == pick.damage)
&& s.nbt_eq(pick)
};
let ench = if v == Version::V1_16_5 {
"Enchantments"
} else {
"ench"
};
let i = (0..36).find(|&i| self.m.player[i].as_ref().is_some_and(same));
if let Some(i) = i.filter(|&i| i < 9) {
self.m.selected = i as u8;
self.m.player.touch();
return Ok(());
}
if !self.m.creative {
// the survival pick of a stack in the main inventory asks the server (`MC|PickItem`)
return match i {
None => Ok(()),
Some(_) => Err(ClickError::Unpredictable),
};
}
// `method_13259`: from the selected slot on, the first empty hotbar slot, else the first
// without enchantments, else the selected one
let start = usize::from(self.m.selected);
let p = &self.m.player;
let best = (0..9)
.map(|k| (start + k) % 9)
.find(|&j| p[j].is_none())
.or_else(|| {
(0..9)
.map(|k| (start + k) % 9)
.find(|&j| !p[j].as_ref().is_some_and(|s| s.has_nonempty_list_tag(ench)))
})
.unwrap_or(start);
self.m.selected = best as u8;
self.m.player.touch();
match i {
None => {
if self.m.player[best].is_some()
&& let Some(j) = (0..36).find(|&j| self.m.player[j].is_none())
{
self.m.player[j] = self.m.player[best].clone();
}
self.m.player[best] = Some(pick.clone());
}
Some(i) => self.m.player.swap(best, i),
}
self.events.player_changed = true;
Ok(())
}
/// 1.12.2 creative mode: a saved toolbar loaded with its key (hotbar key + the load key,
/// no screen open; `CreativeInventoryScreen.method_14550`): the hotbar becomes `saved`
/// (the toolbar the client stored earlier), each slot is sent, and window 0's broadcast
/// runs without a listener (it only records the slots as sent).
///
/// # Errors
/// [`ClickError::WindowOpen`] when a screen is open; [`ClickError::Unpredictable`] outside
/// creative mode or on other versions.
pub fn creative_load_hotbar_legacy(
&mut self,
saved: &[Option<Stack>; 9],
) -> Result<Outgoing, ClickError> {
if self.screen != ScreenState::None {
return Err(ClickError::WindowOpen);
}
if !matches!(self.version, Version::V1_12 | Version::V1_16_5) || !self.m.creative {
return Err(ClickError::Unpredictable);
}
let mut out = Vec::with_capacity(9);
for (j, s) in saved.iter().enumerate() {
self.m.player[j] = s.clone();
out.push(CreativePacket::SetSlot {
slot: 36 + j as i16,
item: s.clone(),
});
}
self.events.player_changed = true;
let lay = Layout::new(self.version, Screen::Player);
let c = self
.creative16
.get_or_insert_with(|| Box::new(CreativeLegacy::new(lay.len)));
for (i, t) in c.tracked.iter_mut().enumerate() {
if let Some(l) = lay.loc(i) {
t.clone_from(self.m.at(l));
}
}
Ok(Outgoing::Creative(out))
}
/// 1.8 `ItemStack.isEnchantable`: the item takes enchantments (one per stack and damageable
/// without subtypes; a book: a single one) and the stack has no `ench` list yet.
fn enchantable_1_8(&self, s: &Stack) -> bool {
let v = self.version;
let item_ok = match s.item_name(v) {
Some("book") => s.count == 1,
Some("enchanted_book") => false,
_ => v.max_count(s) == 1 && v.max_durability(s.id).is_some() && !v.has_subtypes(s.id),
};
item_ok && !s.has_list_tag("ench")
}
}
impl Stack {
/// The root compound has a compound tag `key` (`getNbtCompound(key) != null`).
pub(crate) fn has_compound_tag(&self, key: &str) -> bool {
use ghast_protocol::nbt::Tag;
let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
return false;
};
match &n.tag {
Tag::Compound(c) => matches!(crate::stack::last(c, key), Some(Tag::Compound(_))),
_ => false,
}
}
/// The root compound has a non-empty list tag `key` (1.12 `hasEnchantments` for `ench`).
pub(crate) fn has_nonempty_list_tag(&self, key: &str) -> bool {
use ghast_protocol::nbt::Tag;
let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
return false;
};
match &n.tag {
Tag::Compound(c) => {
matches!(crate::stack::last(c, key), Some(Tag::List(l)) if !l.items.is_empty())
}
_ => false,
}
}
/// The root compound has a list tag `key` (`contains(key, 9)`).
pub(crate) fn has_list_tag(&self, key: &str) -> bool {
use ghast_protocol::nbt::Tag;
let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
return false;
};
match &n.tag {
Tag::Compound(c) => matches!(crate::stack::last(c, key), Some(Tag::List(_))),
_ => false,
}
}
}
impl CreativePacket {
/// The 1.8 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
#[cfg(feature = "v1_8")]
#[must_use]
pub fn to_v1_8(&self) -> Option<ghast_protocol::v1_8::play::serverbound::SetCreativeSlot> {
match self {
CreativePacket::SetSlot { slot, item } => {
Some(ghast_protocol::v1_8::play::serverbound::SetCreativeSlot {
slot: *slot,
item: crate::stack::to_legacy_slot(item.as_ref()),
})
}
CreativePacket::Swing => None,
}
}
/// The 1.16.5 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
#[cfg(feature = "v1_16_5")]
#[must_use]
pub fn to_v1_16_5(
&self,
) -> Option<ghast_protocol::v1_16_5::play::serverbound::SetCreativeSlot> {
match self {
CreativePacket::SetSlot { slot, item } => Some(
ghast_protocol::v1_16_5::play::serverbound::SetCreativeSlot {
slot: *slot,
item: crate::stack::to_modern_slot(item.as_ref()),
},
),
CreativePacket::Swing => None,
}
}
/// The 1.12.2 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
#[cfg(feature = "v1_12")]
#[must_use]
pub fn to_v1_12_2(
&self,
) -> Option<ghast_protocol::v1_12_2::play::serverbound::SetCreativeSlot> {
match self {
CreativePacket::SetSlot { slot, item } => Some(
ghast_protocol::v1_12_2::play::serverbound::SetCreativeSlot {
slot: *slot,
item: crate::stack::to_legacy_slot(item.as_ref()),
},
),
CreativePacket::Swing => None,
}
}
}