/
ItemScriptHelper.java
417 lines (352 loc) · 17 KB
/
ItemScriptHelper.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
package net.aufdemrand.denizen.scripts.containers.core;
import net.aufdemrand.denizen.BukkitScriptEntryData;
import net.aufdemrand.denizencore.events.OldEventManager;
import net.aufdemrand.denizen.objects.*;
import net.aufdemrand.denizencore.objects.*;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ItemScriptHelper implements Listener {
public static Map<String, ItemScriptContainer> item_scripts = new ConcurrentHashMap<String, ItemScriptContainer>(8, 0.9f, 1);
public static Map<String, ItemScriptContainer> item_scripts_by_hash_id = new HashMap<String, ItemScriptContainer>();
public ItemScriptHelper() {
DenizenAPI.getCurrentInstance().getServer().getPluginManager()
.registerEvents(this, DenizenAPI.getCurrentInstance());
}
// Remove all recipes stored by Denizen
public static void removeDenizenRecipes() {
ItemScriptContainer.specialrecipesMap.clear();
ItemScriptContainer.shapelessRecipesMap.clear();
}
public static boolean isBound(ItemStack item) {
return (isItemscript(item) && getItemScriptContainer(item).bound);
}
public static boolean isItemscript(ItemStack item) {
return getItemScriptContainer(item) != null;
}
public static ItemScriptContainer getItemScriptContainer(ItemStack item) {
if (item == null || !item.hasItemMeta() || !item.getItemMeta().hasLore())
return null;
for (String itemLore : item.getItemMeta().getLore()) {
if (itemLore.startsWith(dItem.itemscriptIdentifier))
return item_scripts.get(itemLore.replace(dItem.itemscriptIdentifier, ""));
if (itemLore.startsWith(ItemScriptHashID))
return item_scripts_by_hash_id.get(itemLore);
}
return null;
}
public static String ItemScriptHashID = ChatColor.RED.toString() + ChatColor.BLUE + ChatColor.BLACK;
public static String createItemScriptID(ItemScriptContainer container) {
String colors = createItemScriptID(container.getName());
container.setHashID(colors);
return colors;
}
public static String createItemScriptID(String name) {
String script = name.toUpperCase();
StringBuilder colors = new StringBuilder();
colors.append(ItemScriptHashID);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = script.getBytes("UTF-8");
md.update(bytes, 0, bytes.length);
String hash = new BigInteger(1, md.digest()).toString(16);
for (int i = 0; i < 16; i++) {
colors.append(ChatColor.COLOR_CHAR).append(hash.charAt(i));
}
}
catch (Exception ex) {
dB.echoError(ex);
colors.append(ChatColor.BLUE);
}
return colors.toString();
}
// When special Denizen recipes that have itemscripts as ingredients
// are being used, check crafting matrix for recipe matches whenever
// clicks are made in CRAFTING or RESULT slots
@EventHandler
public void specialRecipeClick(InventoryClickEvent event) {
// Proceed only if at least one special recipe has been stored
if (ItemScriptContainer.specialrecipesMap.isEmpty()
&& ItemScriptContainer.shapelessRecipesMap.isEmpty())
return;
// Proceed only if this is a CraftingInventory
if (!(event.getInventory() instanceof CraftingInventory))
return;
// Store the slot type that was clicked
SlotType slotType = event.getSlotType();
// Proceed only if a CRAFTING or RESULT slot was clicked
if (slotType.equals(InventoryType.SlotType.CRAFTING) ||
slotType.equals(InventoryType.SlotType.RESULT)) {
CraftingInventory inventory = (CraftingInventory) event.getInventory();
Player player = (Player) event.getWhoClicked();
// If the RESULT slot was shift-clicked, emulate
// shift click behavior for it
if (slotType.equals(InventoryType.SlotType.RESULT) &&
event.isShiftClick()) {
emulateSpecialRecipeResultShiftClick(inventory, player);
}
// Otherwise check for special recipe matches
else {
processSpecialRecipes(inventory, player);
}
if (slotType.equals(SlotType.RESULT)) {
removeOneFromEachSlot(inventory, player);
}
}
}
public void removeOneFromEachSlot(final CraftingInventory inventory, final Player player) {
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(),
new Runnable() {
@Override
public void run() {
ItemStack[] matrix = inventory.getMatrix();
for (int i = 0; i < matrix.length; i++) {
if (matrix[i] != null) {
if (matrix[i].getAmount() == 0) {
matrix[i] = null;
} else {
matrix[i].setAmount(matrix[i].getAmount() - 1);
if (matrix[i].getAmount() == 0) {
matrix[i] = null;
}
}
}
}
inventory.setContents(matrix);
player.updateInventory();
}
}, 0);
}
// When special Denizen recipes that have itemscripts as ingredients
// are being used, check crafting matrix for recipe matches whenever
// drags (which are entirely separate from clicks) are made in CRAFTING slots
@EventHandler
public void specialRecipeDrag(InventoryDragEvent event) {
// Proceed only if at least one special recipe has been stored
if (ItemScriptContainer.specialrecipesMap.isEmpty()
&& ItemScriptContainer.shapelessRecipesMap.isEmpty())
return;
// Proceed only if this is a CraftingInventory
if (!(event.getInventory() instanceof CraftingInventory))
return;
// Check for special recipe matches if the drag involved a CRAFTING slot,
// which can have an ID of between 1 and 9 in a CraftingInventory
for (Integer slot : event.getInventorySlots()) {
if (slot < 10) {
CraftingInventory inventory = (CraftingInventory) event.getInventory();
Player player = (Player) event.getWhoClicked();
processSpecialRecipes(inventory, player);
break;
}
}
}
// Compare a crafting matrix with all stored special recipes right
// after a click or drag has been made in it
public void processSpecialRecipes(final CraftingInventory inventory, final Player player) {
// Run a task 1 tick later than the event from which this method
// was called, to check the new state of the CraftingInventory's matrix
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(),
new Runnable() {
@Override
public void run() {
// Store the current matrix
ItemStack[] matrix = inventory.getMatrix();
// Get the result of the special recipe that this matrix matches,
// if any
dItem result = getSpecialRecipeResult(matrix);
// Proceed only if the result was not null
if (result != null) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("inventory", new dInventory(inventory));
context.put("item", result);
dList recipeList = new dList();
for (ItemStack item : inventory.getMatrix()) {
if (item != null)
recipeList.add(new dItem(item).identify());
else
recipeList.add(new dItem(Material.AIR).identify());
}
context.put("recipe", recipeList);
List<String> determinations = OldEventManager.doEvents(Arrays.asList
("item crafted",
result.identifySimple() + " crafted",
result.identifyMaterial() + " crafted"),
new BukkitScriptEntryData(new dPlayer(player), null), context);
for (String determination: determinations) {
if (determination.toUpperCase().startsWith("CANCELLED"))
return;
else if (dItem.matches(determination)) {
result = dItem.valueOf(determination);
}
}
// If this was a valid match, set the crafting's result
inventory.setResult(result.getItemStack());
// Update the player's inventory
//
// TODO: Replace with non-deprecated method once one
// is added to Bukkit
player.updateInventory();
}
}
}, 0);
}
// Check if a CraftingInventory's crafting matrix matches a special
// recipe and return that recipe's dItem result if it does
public dItem getSpecialRecipeResult(ItemStack[] matrix) {
// Iterate through all the special recipes
master: for (Map.Entry<dItem, dList> entry :
ItemScriptContainer.specialrecipesMap.entrySet()) {
// Check if the two sets of items match each other
for (int n = 0; n < 9; n++) {
// Use dItem.valueOf on the entry values to ensure
// correct comparison
dItem valueN = dItem.valueOf(entry.getValue().get(n));
dItem matrixN = matrix.length <= n || matrix[n] == null ? new dItem(Material.AIR): new dItem(matrix[n].clone());
// If one's an item script and the other's not, it's a fail
if (valueN.isItemscript() != matrixN.isItemscript())
continue master;
// If they're both item scripts, and they are different scripts, it's a fail
if (valueN.isItemscript() && matrixN.isItemscript()) {
if (!valueN.getScriptName().equalsIgnoreCase(matrixN.getScriptName()))
continue master;
}
// If they're both not item scripts, and the materials are different, it's a fail
else if (!valueN.getMaterial().matchesMaterialData(matrixN.getMaterial().getMaterialData()))
continue master;
}
// If all the items match, return the special recipe's dItem key
return entry.getKey();
}
primary: for (Map.Entry<dItem, dList> entry :
ItemScriptContainer.shapelessRecipesMap.entrySet()) {
for (int i = 0; i < entry.getValue().size(); i++) {
if (!containsAny(dItem.valueOf(entry.getValue().get(i)), matrix)) {
continue primary;
}
}
return entry.getKey();
}
return null;
}
public boolean containsAny(dItem item, ItemStack[] matrix) {
String full = item.getFullString();
for (int i = 0; i < matrix.length; i++) {
if (full.equalsIgnoreCase(new dItem(matrix[i]).getFullString())) {
return true;
}
}
return false;
}
// Because Denizen special recipes are basically fake recipes,
// shift clicking the result slot will not work by itself and needs
// to be emulated like below
public void emulateSpecialRecipeResultShiftClick(CraftingInventory inventory, Player player) {
// Store the crafting matrix
ItemStack[] matrix = inventory.getMatrix();
// Get the result of the special recipe that this matrix matches,
// if any
dItem result = getSpecialRecipeResult(matrix);
// Proceed only if the result was not null
if (result != null) {
// In a shift click, the amount of the resulting dItem should
// be based on the amount of the least numerous ingredient,
// so track it
int lowestAmount = 0;
// Set lowestAmount to the amount of the first item found,
// then set it to that of the ingredient with the lowest amount
// found that isn't zero
for (int n = 0; n < matrix.length - 1; n++) {
if ((matrix[n].getAmount() > 0 &&
matrix[n].getAmount() < lowestAmount) || lowestAmount == 0) {
lowestAmount = matrix[n].getAmount();
}
}
// Deduct that amount from every ingredient in the matrix
for (int n = 0; n < matrix.length - 1; n++) {
if (matrix[n].getAmount() > 0) {
matrix[n].setAmount(matrix[n].getAmount() - lowestAmount);
if (matrix[n].getAmount() <= 0) {
matrix[n] = null;
}
}
}
// If the lowest amount is 1, there is no need to further
// emulate a shift click at this point, and continuing the
// emulation will actually cause bugs in the inventory's updating,
// so only proceed if lowestAmount is higher than 1
if (lowestAmount > 1) {
// Get a clone of the recipe's result itemstack, so that
// changing its amount now does not affect future craftings
ItemStack resultStack = result.getItemStack().clone();
// Set the itemstack's amount
resultStack.setAmount(lowestAmount * resultStack.getAmount());
inventory.setContents(matrix);
// Set the crafting's result
inventory.setResult(resultStack);
// Update the player's inventory
//
// TODO: Replace with non-deprecated method once one
// is added to Bukkit
player.updateInventory();
}
}
}
@EventHandler
public void boundInventoryClickEvent(InventoryClickEvent event) {
// Proceed only if this is a CraftingInventory
if (!(event.getInventory() instanceof CraftingInventory))
return;
// Proceed only if the click has a cursor item that is bound
ItemStack item = event.getCursor();
if (item == null || !isBound(item))
return;
if (event.getInventory().getType() != InventoryType.PLAYER) {
event.setCancelled(true);
return;
}
if (!((Player)event.getInventory().getHolder()).getName().equalsIgnoreCase(event.getWhoClicked().getName())) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void boundInventoryDragEvent(InventoryDragEvent event) {
// Proceed only if this is a CraftingInventory
if (!(event.getInventory() instanceof CraftingInventory))
return;
// Proceed only if the items are bound
ItemStack item = event.getOldCursor();
if (item == null || !isBound(item))
return;
if (event.getInventory().getType() != InventoryType.PLAYER) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void boundDropItem(PlayerDropItemEvent event) {
// If the item is bound, don't let them drop it!
if (isBound(event.getItemDrop().getItemStack())) {
event.setCancelled(true);
}
}
}