-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Store.java
457 lines (414 loc) · 16.4 KB
/
Store.java
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
/*
* Copyright (c) 2017 - 2021 tastybento
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wasteofplastic.invswitcher;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.advancement.Advancement;
import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.wasteofplastic.invswitcher.dataobjects.InventoryStorage;
import world.bentobox.bentobox.database.Database;
import world.bentobox.bentobox.util.Util;
/**
* Enables inventory switching between games. Handles food, experience and spawn points.
* @author tastybento
*
*/
public class Store {
private static final CharSequence THE_END = "_the_end";
private static final CharSequence NETHER = "_nether";
@SuppressWarnings("deprecation")
private static final List<Material> BLOCKS = Arrays.stream(Material.values()).filter(Material::isBlock).filter(m -> !m.isLegacy()).toList();
@SuppressWarnings("deprecation")
private static final List<Material> ITEMS = Arrays.stream(Material.values()).filter(Material::isItem).filter(m -> !m.isLegacy()).toList();
private static final List<EntityType> LIVING_ENTITIES = Arrays.stream(EntityType.values()).filter(EntityType::isAlive).toList();
private final Database<InventoryStorage> database;
private final Map<UUID, InventoryStorage> cache;
private final InvSwitcher addon;
public Store(InvSwitcher addon) {
this.addon = addon;
database = new Database<>(addon, InventoryStorage.class);
cache = new HashMap<>();
}
/**
* Check if there is a world storage for the player for this world or not
* @param player - player
* @param world - world
* @return true if there is a world stored for this player, otherwise false
*/
public boolean isWorldStored(Player player, World world) {
// Get the store
InventoryStorage store = getInv(player);
String overworldName = (world.getName().replace(THE_END, "")).replace(NETHER, "");
return store.isInventory(overworldName);
}
/**
* Gets items for world. Changes the inventory of player immediately.
* @param player - player
* @param world - world
*/
public void getInventory(Player player, World world) {
// Get the store
InventoryStorage store = getInv(player);
// Do not differentiate between world environments.
String overworldName = Objects.requireNonNull(Util.getWorld(world)).getName();
// Inventory
if (addon.getSettings().isInventory()) {
player.getInventory().setContents(store.getInventory(overworldName).toArray(new ItemStack[0]));
}
if (addon.getSettings().isHealth()) {
setHeath(store, player, overworldName);
}
if (addon.getSettings().isFood()) {
setFood(store, player, overworldName);
}
if (addon.getSettings().isExperience()) {
// Experience
setTotalExperience(player, store.getExp().getOrDefault(overworldName, 0));
}
if (addon.getSettings().isGamemode()) {
// Game modes
player.setGameMode(store.getGameMode(overworldName));
}
if (addon.getSettings().isAdvancements()) {
setAdvancements(store, player, overworldName);
}
if (addon.getSettings().isEnderChest()) {
player.getEnderChest().setContents(store.getEnderChest(overworldName).toArray(new ItemStack[0]));
}
if (addon.getSettings().isStatistics()) {
getStats(store, player, overworldName);
}
}
private void setHeath(InventoryStorage store, Player player, String overworldName) {
// Health
double health = store.getHealth().getOrDefault(overworldName, player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
AttributeInstance attr = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attr != null && health > attr.getValue()) {
health = attr.getValue();
}
if (health < 0D) {
health = 0D;
}
player.setHealth(health);
}
private void setFood(InventoryStorage store, Player player, String overworldName) {
// Food
int food = store.getFood().getOrDefault(overworldName, 20);
if (food > 20) {
food = 20;
} else if (food < 0) {
food = 0;
}
player.setFoodLevel(food);
}
private void setAdvancements(InventoryStorage store, Player player, String overworldName) {
// Advancements
store.getAdvancements(overworldName).forEach((k, v) -> {
Iterator<Advancement> it = Bukkit.advancementIterator();
while (it.hasNext()) {
Advancement a = it.next();
if (a.getKey().toString().equals(k)) {
// Award
v.forEach(player.getAdvancementProgress(a)::awardCriteria);
}
}
});
}
public void removeFromCache(Player player) {
cache.remove(player.getUniqueId());
}
/**
* Get the inventory storage object for player from the database or make a new one
* @param player - player
* @return inventory storage object
*/
private InventoryStorage getInv(Player player) {
if (cache.containsKey(player.getUniqueId())) {
return cache.get(player.getUniqueId());
}
if (database.objectExists(player.getUniqueId().toString())) {
InventoryStorage store = database.loadObject(player.getUniqueId().toString());
if (store != null) {
cache.put(player.getUniqueId(), store);
return store;
}
}
InventoryStorage store = new InventoryStorage();
store.setUniqueId(player.getUniqueId().toString());
cache.put(player.getUniqueId(), store);
return store;
}
/**
* Stores the player's inventory and other items
* @param player - player
* @param world - the world that is associated with these items/elements
*/
public void storeInventory(Player player, World world) {
storeAndSave(player, world);
clearPlayer(player);
// Done!
}
/**
* Store and save the player to the database
* @param player - player
* @param world - world to save
*/
public void storeAndSave(Player player, World world) {
// Get the player's store
InventoryStorage store = getInv(player);
// Do not differentiate between world environments
String worldName = world.getName();
String overworldName = (world.getName().replace(THE_END, "")).replace(NETHER, "");
if (addon.getSettings().isInventory()) {
// Copy the player's items to the store
List<ItemStack> contents = Arrays.asList(player.getInventory().getContents());
store.setInventory(overworldName, contents);
}
if (addon.getSettings().isHealth()) {
store.setHealth(overworldName, player.getHealth());
}
if (addon.getSettings().isFood()) {
store.setFood(overworldName, player.getFoodLevel());
}
if (addon.getSettings().isExperience()) {
store.setExp(overworldName, getTotalExperience(player));
}
if (addon.getSettings().isGamemode()) {
store.setGameMode(overworldName, player.getGameMode());
}
if (addon.getSettings().isAdvancements()) {
// Advancements
store.clearAdvancement(worldName);
Iterator<Advancement> it = Bukkit.advancementIterator();
while (it.hasNext()) {
Advancement a = it.next();
AdvancementProgress p = player.getAdvancementProgress(a);
if (!p.getAwardedCriteria().isEmpty()) {
store.setAdvancement(worldName, a.getKey().toString(), new ArrayList<>(p.getAwardedCriteria()));
}
}
}
if (addon.getSettings().isEnderChest()) {
// Copy the player's ender chest items to the store
List<ItemStack> contents = Arrays.asList(player.getEnderChest().getContents());
store.setEnderChest(overworldName, contents);
}
if (addon.getSettings().isStatistics()) {
saveStats(store, player, overworldName);
}
database.saveObjectAsync(store);
}
private void saveStats(InventoryStorage store, Player player, String worldName) {
store.clearStats(worldName);
// Statistics
Arrays.stream(Statistic.values()).forEach(s -> {
Map<Material, Integer> map;
Map<EntityType, Integer> entMap;
switch (s.getType()) {
case BLOCK -> {
map = BLOCKS.stream().filter(m -> player.getStatistic(s, m) > 0)
.collect(Collectors.toMap(k -> k, v -> player.getStatistic(s, v)));
if (!map.isEmpty()) {
store.getBlockStats(worldName).put(s, map);
}
}
case ITEM -> {
map = ITEMS.stream().filter(m -> player.getStatistic(s, m) > 0)
.collect(Collectors.toMap(k -> k, v -> player.getStatistic(s, v)));
if (!map.isEmpty()) {
store.getItemStats(worldName).put(s, map);
}
}
case ENTITY -> {
entMap = LIVING_ENTITIES.stream().filter(m -> player.getStatistic(s, m) > 0)
.collect(Collectors.toMap(k -> k, v -> player.getStatistic(s, v)));
if (!entMap.isEmpty()) {
store.getEntityStats(worldName).put(s, entMap);
}
}
case UNTYPED -> {
int sc = player.getStatistic(s);
if (sc > 0) {
store.getUntypedStats(worldName).put(s, sc);
}
}
}
});
}
/**
* Get all the stats for this world and apply them to the player
* @param store - store
* @param player - player
* @param worldName - world name
*/
private void getStats(InventoryStorage store, Player player, String worldName) {
// Statistics
Arrays.stream(Statistic.values()).forEach(s -> getStat(s, store, player, worldName));
}
private void getStat(Statistic s, InventoryStorage store, Player player, String worldName) {
switch(s.getType()) {
case BLOCK -> store.getBlockStats(worldName).getOrDefault(s, Collections.emptyMap()).forEach((k,v) -> player.setStatistic(s, k, v));
case ITEM -> store.getItemStats(worldName).getOrDefault(s, Collections.emptyMap()).forEach((k,v) -> player.setStatistic(s, k, v));
case ENTITY -> store.getEntityStats(worldName).getOrDefault(s, Collections.emptyMap()).forEach((k,v) -> player.setStatistic(s, k, v));
case UNTYPED -> {
if (store.getUntypedStats(worldName).containsKey(s)) {
player.setStatistic(s, store.getUntypedStats(worldName).get(s));
}
}
}
}
private void clearPlayer(Player player) {
if (this.addon.getSettings().isInventory())
{
// Clear the player's inventory
player.getInventory().clear();
}
if (this.addon.getSettings().isExperience())
{
// Reset experience
setTotalExperience(player, 0);
}
if (this.addon.getSettings().isAdvancements())
{
// Reset advancements
resetAdv(player);
}
if (this.addon.getSettings().isEnderChest())
{
// Reset enderchest
player.getEnderChest().clear();
}
if (this.addon.getSettings().isStatistics())
{
// Reset Statistics
Arrays.stream(Statistic.values()).forEach(s ->
resetStats(player, s));
}
}
private void resetAdv(Player player) {
Iterator<Advancement> it = Bukkit.advancementIterator();
while (it.hasNext())
{
Advancement a = it.next();
AdvancementProgress p = player.getAdvancementProgress(a);
p.getAwardedCriteria().forEach(p::revokeCriteria);
}
}
private void resetStats(Player player, Statistic s) {
switch (s.getType()) {
case BLOCK -> BLOCKS.forEach(m -> player.setStatistic(s, m, 0));
case ITEM -> ITEMS.forEach(m -> player.setStatistic(s, m, 0));
case ENTITY -> LIVING_ENTITIES.forEach(en -> player.setStatistic(s, en, 0));
case UNTYPED -> player.setStatistic(s, 0);
}
}
//new Exp Math from 1.8
private static int getExpAtLevel(final int level)
{
if (level <= 15)
{
return (2*level) + 7;
}
if (level <= 30)
{
return (5 * level) -38;
}
return (9*level)-158;
}
private static int getExpAtLevel(final Player player)
{
return getExpAtLevel(player.getLevel());
}
//This method is required because the bukkit player.getTotalExperience() method, shows exp that has been 'spent'.
//Without this people would be able to use exp and then still sell it.
private static int getTotalExperience(final Player player)
{
int exp = Math.round(getExpAtLevel(player) * player.getExp());
int currentLevel = player.getLevel();
while (currentLevel > 0)
{
currentLevel--;
exp += getExpAtLevel(currentLevel);
}
if (exp < 0)
{
exp = Integer.MAX_VALUE;
}
return exp;
}
// These next methods are taken from Essentials code
//This method is used to update both the recorded total experience and displayed total experience.
//We reset both types to prevent issues.
private static void setTotalExperience(final Player player, final int exp)
{
if (exp < 0)
{
throw new IllegalArgumentException("Experience is negative!");
}
player.setExp(0);
player.setLevel(0);
player.setTotalExperience(0);
//This following code is technically redundant now, as bukkit now calculates levels more or less correctly
//At larger numbers however... player.getExp(3000), only seems to give 2999, putting the below calculations off.
int amount = exp;
while (amount > 0)
{
final int expToLevel = getExpAtLevel(player);
amount -= expToLevel;
if (amount >= 0)
{
// give until next level
player.giveExp(expToLevel);
}
else
{
// give the rest
amount += expToLevel;
player.giveExp(amount);
amount = 0;
}
}
}
/**
* Save all online players
*/
public void saveOnlinePlayers() {
Bukkit.getOnlinePlayers().forEach(p -> this.storeAndSave(p, p.getWorld()));
}
}