forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplayer_data.rs
More file actions
209 lines (183 loc) · 6.36 KB
/
player_data.rs
File metadata and controls
209 lines (183 loc) · 6.36 KB
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
use std::fs::File;
use crate::entity::BaseEntityData;
use crate::inventory::{
SlotIndex, HOTBAR_SIZE, INVENTORY_SIZE, SLOT_ARMOR_MAX, SLOT_ARMOR_MIN, SLOT_HOTBAR_OFFSET,
SLOT_INVENTORY_OFFSET, SLOT_OFFHAND,
};
use crate::ItemStack;
use feather_items::Item;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use tokio::prelude::AsyncRead;
use uuid::Uuid;
/// Represents the contents of a player data file.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct PlayerData {
// Inherit base entity data
#[serde(flatten)]
pub entity: BaseEntityData,
#[serde(rename = "playerGameType")]
pub gamemode: i32,
#[serde(rename = "Inventory")]
pub inventory: Vec<InventorySlot>,
}
/// Represents a single inventory slot (including position index).
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct InventorySlot {
#[serde(rename = "Count")]
pub count: i8,
#[serde(rename = "Slot")]
pub slot: i8,
#[serde(rename = "id")]
pub item: String,
}
impl InventorySlot {
/// Converts a slot to an ItemStack.
pub fn to_stack(&self) -> ItemStack {
ItemStack {
ty: Item::from_identifier(self.item.as_str()).unwrap_or(Item::Air),
amount: self.count as u8,
}
}
/// Converts a network protocol index, item, and count
/// to an `InventorySlot`.
pub fn from_network_index(network: SlotIndex, stack: ItemStack) -> Self {
let slot = if SLOT_HOTBAR_OFFSET <= network && network < SLOT_HOTBAR_OFFSET + HOTBAR_SIZE {
// Hotbar
(network - SLOT_HOTBAR_OFFSET) as i8
} else if network == SLOT_OFFHAND {
-106
} else if SLOT_ARMOR_MIN <= network && network <= SLOT_ARMOR_MAX {
((SLOT_ARMOR_MAX - network) + 100) as i8
} else if SLOT_INVENTORY_OFFSET <= network
&& network < SLOT_INVENTORY_OFFSET + INVENTORY_SIZE
{
network as i8
} else {
panic!("Invalid slot index {} on server", network);
};
Self {
count: stack.amount as i8,
slot,
item: stack.ty.identifier().to_string(),
}
}
/// Converts an NBT inventory index to a network protocol index.
/// Returns None if the index is invalid.
pub fn convert_index(&self) -> Option<SlotIndex> {
if 0 <= self.slot && self.slot <= 8 {
// Hotbar
Some(crate::inventory::SLOT_HOTBAR_OFFSET + (self.slot as usize))
} else if self.slot == -106 {
// Offhand
Some(crate::inventory::SLOT_OFFHAND as usize)
} else if 100 <= self.slot && self.slot <= 103 {
// Equipment
Some((108 - self.slot) as usize)
} else if 9 <= self.slot && self.slot <= 35 {
// Rest of inventory
Some(self.slot as usize)
} else {
// Unknown index
None
}
}
}
async fn load_from_file<R: AsyncRead + Unpin>(mut reader: R) -> Result<PlayerData, nbt::Error> {
let mut buf = vec![];
tokio::io::copy(&mut reader, &mut buf).await?;
nbt::from_gzip_reader(buf.as_slice())
}
pub async fn load_player_data(world_dir: &Path, uuid: Uuid) -> Result<PlayerData, nbt::Error> {
let file_path = file_path(world_dir, uuid);
let file = tokio::fs::File::open(file_path).await?;
let data = load_from_file(file).await?;
Ok(data)
}
fn save_to_file<W: Write>(mut writer: W, data: PlayerData) -> Result<(), nbt::Error> {
nbt::to_gzip_writer(&mut writer, &data, None)
}
pub fn save_player_data(world_dir: &Path, uuid: Uuid, data: PlayerData) -> Result<(), nbt::Error> {
fs::create_dir_all(world_dir.join("playerdata"))?;
let file_path = file_path(world_dir, uuid);
let file = File::create(file_path)?;
save_to_file(file, data)
}
fn file_path(world_dir: &Path, uuid: Uuid) -> PathBuf {
world_dir.join("playerdata").join(format!("{}.dat", uuid))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Gamemode;
use hashbrown::HashMap;
use std::io::Cursor;
#[tokio::test]
async fn test_deserialize_player() {
let cursor = Cursor::new(include_bytes!("player.dat").to_vec());
let player = load_from_file(cursor).await.unwrap();
assert_eq!(player.gamemode, i32::from(Gamemode::Creative.id()));
}
#[test]
fn test_convert_item() {
let slot = InventorySlot {
count: 1,
slot: 2,
item: String::from(Item::Feather.identifier()),
};
let item_stack = slot.to_stack();
assert_eq!(item_stack.ty, Item::Feather);
assert_eq!(item_stack.amount, 1);
}
#[test]
fn test_convert_item_unknown_type() {
let slot = InventorySlot {
count: 1,
slot: 2,
item: String::from("invalid:identifier"),
};
let item_stack = slot.to_stack();
assert_eq!(item_stack.ty, Item::Air);
}
#[test]
fn test_convert_slot_index() {
let mut map: HashMap<i8, usize> = HashMap::new();
// Equipment
map.insert(103, crate::inventory::SLOT_ARMOR_HEAD);
map.insert(102, crate::inventory::SLOT_ARMOR_CHEST);
map.insert(101, crate::inventory::SLOT_ARMOR_LEGS);
map.insert(100, crate::inventory::SLOT_ARMOR_FEET);
map.insert(-106, crate::inventory::SLOT_OFFHAND);
// Hotbar
for x in 0..9 {
map.insert(x, crate::inventory::SLOT_HOTBAR_OFFSET + (x as usize));
}
// Rest of inventory
for x in 9..36 {
map.insert(x, x as usize);
}
// Check all valid slots
for (src, expected) in map {
let slot = InventorySlot {
slot: src,
count: 1,
item: String::from(Item::Stone.identifier()),
};
assert_eq!(slot.convert_index().unwrap(), expected);
assert_eq!(
InventorySlot::from_network_index(expected, ItemStack::new(Item::Stone, 1)),
slot
);
}
// Check that invalid slots error out
for invalid_slot in [-1, -2, 104].iter() {
let slot = InventorySlot {
slot: *invalid_slot as i8,
count: 1,
item: String::from("invalid:identifier"),
};
assert!(slot.convert_index().is_none());
}
}
}