/
Utilities.java
519 lines (430 loc) · 17.3 KB
/
Utilities.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
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
package net.aufdemrand.denizen.utilities;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import net.aufdemrand.denizen.Settings;
import net.aufdemrand.denizen.objects.dNPC;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.tags.TagManager;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
/**
* This class has utility methods for various tasks.
*
* @author aufdemrand, dbixler, AgentK
*/
public class Utilities {
static Random random = new Random();
public static Location getWalkableLocationNear(Location location, int range) {
Location returnable;
int selected_x = random.nextInt(range * 2);
int selected_z = random.nextInt(range * 2);
returnable = location.add(selected_x - range, 1, selected_z - range);
if (!isWalkable(returnable)) return getWalkableLocationNear(location, range);
else return returnable;
}
public static boolean isWalkable(Location location) {
return ((location.getBlock().getType() == Material.AIR
|| location.getBlock().getType() == Material.GRASS)
&& (location.add(0, 1, 0).getBlock().getType() == Material.AIR));
}
public static String arrayToString(String[] input, String glue) {
String output="";
int length = input.length;
int i = 1;
for(String s : input) { // TODO: Should this be? : output = output.concat(s);
output.concat(s);
i++;
if(i!=length){
output.concat(glue); // TODO: Same as above
}
}
return output;
}
public static String[] wrapWords(String text, int width) {
StringBuilder sb = new StringBuilder(text);
int i = 0;
while (i + width < sb.length() && (i = sb.lastIndexOf(" ", i + width)) != -1) {
sb.replace(i, i + 1, "\n");
}
return sb.toString().split("\n");
}
/**
*
*
* @param player the player doing the talking
* @param npc the npc being talked to
* @param range the range, in blocks, that 'bystanders' will hear he chat
*
*/
public static void talkToNPC(String message, dPlayer player, dNPC npc, double range) {
String replacer = String.valueOf((char)0x03);
// Get formats from Settings, and fill in <TEXT>
String talkFormat = Settings.ChatToNpcFormat()
.replace("<TEXT>", replacer).replace("<text>", replacer).replace("<Text>", replacer);
String bystanderFormat = Settings.ChatToNpcOverheardFormat()
.replace("<TEXT>", replacer).replace("<text>", replacer).replace("<Text>", replacer);
// Fill in tags
talkFormat = TagManager.tag(player, npc, talkFormat, false).replace(replacer, message);
bystanderFormat = TagManager.tag(player, npc, bystanderFormat, false).replace(replacer, message);
// Send message to player
player.getPlayerEntity().sendMessage(talkFormat);
// Send message to bystanders
for (Player target : Bukkit.getOnlinePlayers()) {
if (target != player.getPlayerEntity())
if (target.getWorld().equals(player.getPlayerEntity().getWorld())
&& target.getLocation().distance(player.getPlayerEntity().getLocation()) <= range)
target.sendMessage(bystanderFormat);
}
}
public static int lastIndexOfUCL(String str) {
for(int i=str.length()-1; i>=0; i--) {
if(Character.isUpperCase(str.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Checks if c is in between a and b.
*
* @param a
* @param b
* @param c
* @return true if c is in between.
*/
public static boolean isBetween(double a, double b, double c) {
return b > a ? c > a && c < b : c > b && c < a;
}
public static int lastIndexOfLCL(String str) {
for(int i=str.length()-1; i>=0; i--) {
if(Character.isLowerCase(str.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Gets the plugin version from the maven info in the jar, if available.
*
* @return
*/
public String getVersionNumber() {
Properties props = new Properties();
//Set a default just in case.
props.put("version", "Unknown development build");
try {
props.load(this.getClass().getResourceAsStream("/META-INF/maven/net.aufdemrand/denizen/pom.properties"));
}
catch(Exception e) {
//Maybe log?
}
return props.getProperty("version");
}
public static List<Block> getRandomSolidBlocks(Location location, int range, int count) {
List<Block> blocks = new ArrayList<Block>();
int x = 0;
int f = 0;
while (x < count) {
if (f > 1000) break;
f++;
Location loc = location.clone()
.add(Utilities.getRandom().nextInt(range * 2) - range,
Utilities.getRandom().nextInt(range * 2) - range,
Utilities.getRandom().nextInt(range * 2) - range);
if (loc.getBlock().getType().isSolid()) {
blocks.add(loc.getBlock());
x++;
}
}
dB.log(blocks.size() + " blocksize");
return blocks;
}
/**
* Finds the closest Player to a particular location.
*
* @param location The location to find the closest Player to.
* @param range The maximum range to look for the Player.
*
* @return The closest Player to the location, or null if no Player was found
* within the range specified.
*/
public static Player getClosestPlayer (Location location, int range) {
Player closestPlayer = null;
double closestDistance = Math.pow(range, 2);
List<Player> playerList = new ArrayList<Player>(Arrays.asList(Bukkit.getOnlinePlayers()));
Iterator<Player> it = playerList.iterator();
while (it.hasNext()) {
Player player = it.next();
Location loc = player.getLocation();
if (loc.getWorld().equals(location.getWorld())
&& loc.distanceSquared(location) < closestDistance) {
closestPlayer = player;
closestDistance = player.getLocation().distanceSquared(location);
}
}
return closestPlayer;
}
/**
* Finds the closest Players to a particular location.
*
* @param location The location to find the closest Player to.
* @param range The maximum range to look for the Player.
*
* @return The closest Player to the location, or null if no Player was found
* within the range specified.
*/
public static List<dPlayer> getClosestPlayers(Location location, int range) {
List<dPlayer> closestPlayers = new ArrayList<dPlayer>();
double closestDistance = Math.pow(range, 2);
List<Player> playerList = new ArrayList<Player>(Arrays.asList(Bukkit.getOnlinePlayers()));
Iterator<Player> it = playerList.iterator();
while (it.hasNext()) {
Player player = it.next();
Location loc = player.getLocation();
if (loc.getWorld().equals(location.getWorld())
&& loc.distanceSquared(location) < closestDistance) {
closestPlayers.add(dPlayer.mirrorBukkitPlayer(player));
}
}
return closestPlayers;
}
/**
* Finds the closest NPC to a particular location.
*
* @param location The location to find the closest NPC to.
* @param range The maximum range to look for the NPC.
*
* @return The closest NPC to the location, or null if no NPC was found
* within the range specified.
*/
public static dNPC getClosestNPC (Location location, int range) {
dNPC closestNPC = null;
double closestDistance = Math.pow(range, 2);
Iterator<dNPC> it = DenizenAPI.getSpawnedNPCs().iterator();
while (it.hasNext()) {
dNPC npc = it.next();
Location loc = npc.getLocation();
if (loc.getWorld().equals(location.getWorld())
&& loc.distanceSquared(location) < closestDistance) {
closestNPC = npc;
closestDistance = npc.getLocation().distanceSquared(location);
}
}
return closestNPC;
}
/**
* Returns a list of all NPCs within a certain range.
*
* @param location The location to search.
* @param maxRange The maximum range of the NPCs
*
* @return The list of NPCs within the max range.
*/
public static Set<dNPC> getClosestNPCs (Location location, int maxRange) {
maxRange = (int) Math.pow(maxRange, 2);
Set<dNPC> closestNPCs = new HashSet<dNPC> ();
Iterator<dNPC> it = DenizenAPI.getSpawnedNPCs().iterator();
while (it.hasNext ()) {
dNPC npc = it.next ();
Location loc = npc.getLocation();
if (loc.getWorld().equals(location.getWorld()) && loc.distanceSquared(location) < maxRange) {
closestNPCs.add(npc);
}
}
return closestNPCs;
}
/**
* Checks entity's location against a Location (with leeway). Should be faster than
* bukkit's built in Location.distance(Location) since there's no sqrt math.
*
* Thanks chainsol :)
*
* @return true if within the specified location, false otherwise.
*/
public static boolean checkLocation(LivingEntity entity, Location theLocation, int theLeeway) {
if (entity.getWorld() != theLocation.getWorld())
return false;
Location entityLocation = entity.getLocation();
if (Math.abs(entityLocation.getX() - theLocation.getX())
> theLeeway) return false;
if (Math.abs(entityLocation.getY() - theLocation.getY())
> theLeeway) return false;
if (Math.abs(entityLocation.getZ() - theLocation.getZ())
> theLeeway) return false;
return true;
}
/**
* Checks entity's location against a Location (with leeway). Should be faster than
* bukkit's built in Location.distance(Location) since there's no sqrt math.
*
* Thanks chainsol :)
*
* @return true if within the specified location, false otherwise.
*/
public static boolean checkLocation(Location baseLocation, Location theLocation, int theLeeway) {
if (!baseLocation.getWorld().getName().equals(theLocation.getWorld().getName()))
return false;
if (Math.abs(baseLocation.getX() - theLocation.getX())
> theLeeway) return false;
if (Math.abs(baseLocation.getY() - theLocation.getY())
> theLeeway) return false;
if (Math.abs(baseLocation.getZ() - theLocation.getZ())
> theLeeway) return false;
return true;
}
protected static FilenameFilter scriptsFilter;
static {
scriptsFilter = new FilenameFilter() {
public boolean accept(File file, String fileName) {
if(fileName.startsWith(".")) return false;
String ext = fileName.substring(fileName.lastIndexOf('.') + 1);
return ext.equalsIgnoreCase("YML") || ext.equalsIgnoreCase("DSCRIPT");
}
};
}
/**
* Lists all files in the given directory.
*
* @param dir The directory to search in
* @param recursive If true subfolders will also get checked
* @return A {@link File} collection
*/
public static List<File> listDScriptFiles(File dir, boolean recursive) {
List<File> files = new ArrayList<File>();
File[] entries = dir.listFiles();
for (File file : entries) {
// Add file
if (scriptsFilter == null || scriptsFilter.accept(dir, file.getName())) {
files.add(file);
}
// Add subdirectories
if (recursive && file.isDirectory()) {
files.addAll(listDScriptFiles(file, recursive));
}
}
return files;
}
public static Random getRandom() {
return random;
}
/**
* Set the lines on a sign to the strings in a string array
*
* @param sign The sign
* @param lines The string array
*/
public static void setSignLines(Sign sign, String[] lines) {
int n = 0;
for (String line : lines) {
sign.setLine(n, line);
n++;
}
sign.update();
}
/**
* Make a wall sign attach itself to an available surface
*
* @param signState The sign's blockState
*/
public static void setSignRotation(BlockState signState) {
BlockFace[] blockFaces = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH};
for (BlockFace blockFace : blockFaces) {
Block block = signState.getBlock().getRelative(blockFace);
if ((block.getType() != Material.AIR)
&& block.getType() != Material.SIGN_POST
&& block.getType() != Material.WALL_SIGN) {
((org.bukkit.material.Sign) signState.getData())
.setFacingDirection(blockFace.getOppositeFace());
signState.update();
}
}
}
public static void setSignRotation(BlockState signState, String direction) {
BlockFace[] blockFaces = {BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH};
for (BlockFace blockFace : blockFaces) {
if (blockFace.name().startsWith(direction.toUpperCase().substring(0, 1)))
((org.bukkit.material.Sign) signState.getData())
.setFacingDirection(blockFace);
}
signState.update();
}
/**
* Check if a block location equals another location.
* @param block The block location to check for.
* @param location The location to check against.
* @return Whether or not the block location equals the location.
*/
public static boolean isBlock(Location block, Location location) {
if (!block.getWorld().getName().equals(location.getWorld().getName()))
return false;
if (Math.abs(block.getBlockX() - location.getBlockX())
> 0) return false;
if (Math.abs(block.getBlockY() - location.getBlockY())
> 0) return false;
if (Math.abs(block.getBlockZ() - location.getBlockZ())
> 0) return false;
return true;
}
/**
* Extract a file from a zip or jar.
* @param jarFile The zip/jar file to use
* @param fileName Which file to extract
* @param destDir Where to extract it to
*/
public static void extractFile(File jarFile, String fileName, String destDir) {
java.util.jar.JarFile jar = null;
try {
jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration myEnum = jar.entries();
while (myEnum.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) myEnum.nextElement();
if (file.getName().equalsIgnoreCase(fileName)) {
java.io.File f = new java.io.File(destDir + "/" + file.getName());
if (file.isDirectory()) {
continue;
}
java.io.InputStream is = jar.getInputStream(file);
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0)
fos.write(is.read());
fos.close();
is.close();
return;
}
}
dB.echoError(fileName + " not found in the jar!");
}
catch (IOException e) {
if (dB.showStackTraces)
e.printStackTrace();
}
finally {
if (jar != null) {
try {
jar.close();
}
catch (IOException e) {
if (dB.showStackTraces)
e.printStackTrace();
}
}
}
}
}