forked from CryptoMorin/XSeries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParticleDisplay.java
1634 lines (1474 loc) · 58.5 KB
/
ParticleDisplay.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
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License (MIT)
*
* Copyright (c) 2024 Crypto Morin
*
* 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.cryptomorin.xseries.particles;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.World;
import org.bukkit.block.data.BlockData;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.util.NumberConversions;
import org.bukkit.util.Vector;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Represents how particles should be spawned. The simplest use case would be the following code
* which spawns a single particle in front of the player:
* <pre>{@code
* ParticleDisplay.of(Particle.FLAME).spawn(player.getEyeLocation());
* }</pre>
* This class is disposable by {@link XParticle} methods.
* It should not be used across multiple methods. I.e. it should not be
* used even to spawn a simple particle after it was used by one of {@link XParticle} methods.
* <p>
* By default, the particle xyz offsets and speed aren't 0, but
* everything will be 0 by default in this class.
* Particles are spawned to a location. So all the nearby players can see it.
* <p>
* For cross-version compatibility, instead of Bukkit's {@link org.bukkit.Color}
* the java awt {@link Color} class is used.
* <p>
* the data field is used to store special particle data, such as colored particles.
* For colored particles a float list is used since the particle size is a float.
* The format of float list data for a colored particle is:
* <code>[r, g, b, size]</code>
*
* @author Crypto Morin
* @version 10.0.0
* @see XParticle
*/
@SuppressWarnings("CallToSimpleGetterFromWithinClass")
public class ParticleDisplay implements Cloneable {
/**
* Checks if spawn methods should use particle data classes such as {@link org.bukkit.Particle.DustOptions}
* which is only available from 1.13+ (FOOTSTEP was removed in 1.13)
*
* @since 1.0.0
*/
private static final boolean ISFLAT = XParticle.getParticle("FOOTSTEP") == null;
/**
* Checks if spawn methods should use particle data classes such as {@link org.bukkit.Particle.DustTransition}
* which is only available from 1.17+ (DUST_COLOR_TRANSITION was released in 1.17)
*
* @since 8.6.0.0.1
*/
private static final boolean SUPPORTS_DUST_TRANSITION = XParticle.getParticle("DUST_COLOR_TRANSITION") != null;
// private static final Axis[] DEFAULT_ROTATION_ORDER = {Axis.X, Axis.Y, Axis.Z};
/**
* Flames seem to be the simplest particles that allows you to get a good visual
* on how precise shapes that depend on complex algorithms play out.
*/
@Nonnull
private static final Particle DEFAULT_PARTICLE = Particle.FLAME;
public int count = 1;
public double extra;
public boolean force;
@Nonnull
private Particle particle = DEFAULT_PARTICLE;
@Nullable
private Location location, lastLocation;
@Nullable
private Vector offset = new Vector();
/**
* The direction is mostly used for APIs to call {@link #advanceInDirection(double)}
* instead of handling the direction in a specific axis.
* This makes it easier for them as well and allows easier use of the {@link #rotations} API.
*/
@Nonnull
private Vector direction = new Vector(0, 1, 0);
/**
* The xyz axis order of how the particle's matrix should be rotated.
* Yes, it matters which axis you rotate first as it'll have an impact on the
* other rotations.
* <p>
* Check <a href="https://stackoverflow.com/questions/11819644/pitch-yaw-roll-angle-independency">this stackoverflow question.</a>
* Quaternions are a solution to this problem which is already present in {@link org.bukkit.entity.Display} entities API.
* See <a href="https://www.youtube.com/watch?v=zjMuIxRvygQ">this 3Blue1Brown YouTube video.</a>
* <p>
* You could use an axis two times such as yaw -> roll -> yaw sequence which is the canonical Euler sequence.
* But here for the standard {@link XParticle} methods, we're going to be using Tait–Bryan angles.
* Minecraft Euler angles use XYZ order.
* <a href="https://www.spigotmc.org/threads/euler-angles-strange-behavior.377072/">Source</a>
* <a href="https://www.youtube.com/watch?v=zc8b2Jo7mno">Gimbal lock</a>.
* <p>
* For 2D shapes, it's recommended that your algorithm uses the x and z axis and leave y as 0.
* <p>
* Each list within the main list represents the rotations that are going to be applied individually in order.
* While it's true that in order to combine multiple quaternion rotations you'd have to multiply them,
* quaternion multiplication is not commutative and some rotations should be done separately.
*/
@Nonnull
public List<List<Rotation>> rotations = new ArrayList<>();
@Nullable
private List<Quaternion> cachedFinalRotationQuaternions;
@Nullable
private Object data;
@Nullable
private Consumer<CalculationContext> preCalculation;
@Nullable
private Consumer<CalculationContext> postCalculation;
@Nullable
private Function<Double, Double> onAdvance;
@Nullable
private Set<Player> players;
/**
* Builds a simple ParticleDisplay object with cross-version
* compatible {@link org.bukkit.Particle.DustOptions} properties.
* Only REDSTONE particle type can be colored like this.
*
* @param location the location of the display.
* @param size the size of the dust.
* @return a redstone colored dust.
* @see #simple(Location, Particle)
* @since 1.0.0
* @deprecated use {@link #withColor(float, float, float, float)}
*/
@Nonnull
@Deprecated
public static ParticleDisplay colored(@Nullable Location location, int r, int g, int b, float size) {
return ParticleDisplay.simple(location, Particle.REDSTONE).withColor(r, g, b, size);
}
/**
* @return the players that this particle will be visible to or null if it's visible to all.
* @since 9.0.0
*/
@Nullable
public Set<Player> getPlayers() {
return players;
}
/**
* Makes this particle only visible to certain players.
*
* @since 9.0.0
*/
public ParticleDisplay onlyVisibleTo(Collection<Player> players) {
if (players.isEmpty()) return this;
if (this.players == null) this.players = Collections.newSetFromMap(new WeakHashMap<>());
this.players.addAll(players);
return this;
}
/**
* @see #onlyVisibleTo(Collection)
* @since 9.0.0
*/
public ParticleDisplay onlyVisibleTo(Player... players) {
if (players.length == 0) return this;
if (this.players == null) this.players = Collections.newSetFromMap(new WeakHashMap<>());
Collections.addAll(this.players, players);
return this;
}
/**
* Builds a simple ParticleDisplay object with cross-version
* compatible {@link org.bukkit.Particle.DustOptions} properties.
* Only REDSTONE particle type can be colored like this.
*
* @param color the color of the particle.
* @param size the size of the dust.
* @return a redstone colored dust.
* @since 3.0.0
* @deprecated use {@link #withColor(Color, float)}
*/
@Nonnull
@Deprecated
public static ParticleDisplay colored(Location location, @Nonnull Color color, float size) {
return colored(location, color.getRed(), color.getGreen(), color.getBlue(), size);
}
/**
* Builds a simple ParticleDisplay object.
* An invocation of this method yields exactly the same result as the expression:
* <p>
* <blockquote>
* new ParticleDisplay(particle, location, 1, 0, 0, 0, 0);
* </blockquote>
*
* @param location the location of the display.
* @param particle the particle of the display.
* @return a simple ParticleDisplay with count 1 and no offset, rotation etc.
* @since 1.0.0
* @deprecated use {@link #of(Particle)} and {@link #withLocation(Location)}
*/
@Nonnull
@Deprecated
public static ParticleDisplay simple(@Nullable Location location, @Nonnull Particle particle) {
Objects.requireNonNull(particle, "Cannot build ParticleDisplay with null particle");
ParticleDisplay display = new ParticleDisplay();
display.particle = particle;
display.location = location;
return display;
}
/**
* @since 6.0.0.1
*/
@Nonnull
public static ParticleDisplay of(@Nonnull Particle particle) {
return simple(null, particle);
}
/**
* A quick access method to display a simple particle.
* An invocation of this method yields the same result as the expression:
* <p>
* <blockquote>
* ParticleDisplay.simple(location, particle).spawn();
* </blockquote>
*
* @param location the location of the particle.
* @param particle the particle to show.
* @return a simple ParticleDisplay with count 1 and no offset, rotation etc.
* @since 1.0.0
* @deprecated use {@link #of(Particle)} and {@link #withLocation(Location)}
*/
@Nullable
@Deprecated
public static ParticleDisplay display(@Nonnull Location location, @Nonnull Particle particle) {
Objects.requireNonNull(location, "Cannot display particle in null location");
ParticleDisplay display = simple(location, particle);
display.spawn();
return display;
}
/**
* Builds particle settings from a configuration section.
*
* @param config the config section for the settings.
* @return a parsed ParticleDisplay from the config.
* @since 1.0.0
*/
public static ParticleDisplay fromConfig(@Nonnull ConfigurationSection config) {
return edit(new ParticleDisplay(), config);
}
private static int toInt(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return 0;
}
}
private static double toDouble(String str) {
try {
return Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return 0;
}
}
private static java.util.List<String> split(@Nonnull String str, @SuppressWarnings("SameParameterValue") char separatorChar) {
List<String> list = new ArrayList<>(5);
boolean match = false, lastMatch = false;
int len = str.length();
int start = 0;
for (int i = 0; i < len; i++) {
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
// This is important, it should not be i++
start = i + 1;
continue;
}
lastMatch = false;
match = true;
}
if (match || lastMatch) {
list.add(str.substring(start, len));
}
return list;
}
/**
* Builds particle settings from a configuration section. Keys in config can be :
* <ul>
* <li>particle : the particle type.
* <li>count : the count as integer, at least 0.
* <li>extra : the particle speed, most of the time.
* <li>force : true or false, if the particle has force or not.
* <li>offset : the offset where values are separated by commas "dx, dy, dz".
* <li>rotation : the rotation of the particles in degrees.
* <li>color : the data representing color "R, G, B, size" where RGB values are integers
* between 0 and 255 and size is a positive (or null) float.
* <li>blockdata : the data representing block data. Given by a material name that's a block.
* <li>materialdata : same than blockdata, but with legacy data before 1.12.
* <strong>Do not use this in 1.13 and above.</strong>
* <li>itemstack : the data representing item. Given by a material name that's an item.
* </ul>
*
* @param display the particle display settings to update.
* @param config the config section for the settings.
* @return the same ParticleDisplay, but edited.
* @since 5.0.0
*/
@Nonnull
public static ParticleDisplay edit(@Nonnull ParticleDisplay display, @Nonnull ConfigurationSection config) {
Objects.requireNonNull(display, "Cannot edit a null particle display");
Objects.requireNonNull(config, "Cannot parse ParticleDisplay from a null config section");
String particleName = config.getString("particle");
Particle particle = particleName == null ? null : XParticle.getParticle(particleName);
if (particle != null) display.particle = particle;
if (config.isSet("count")) display.withCount(config.getInt("count"));
if (config.isSet("extra")) display.withExtra(config.getDouble("extra"));
if (config.isSet("force")) display.forceSpawn(config.getBoolean("force"));
String offset = config.getString("offset");
if (offset != null) {
List<String> offsets = split(offset.replace(" ", ""), ',');
if (offsets.size() >= 3) {
double offsetx = toDouble(offsets.get(0));
double offsety = toDouble(offsets.get(1));
double offsetz = toDouble(offsets.get(2));
display.offset(offsetx, offsety, offsetz);
} else {
double masterOffset = toDouble(offsets.get(0));
display.offset(masterOffset);
}
}
ConfigurationSection rotations = config.getConfigurationSection("rotations");
if (rotations != null) {
/*
rotations:
group-1:
0:
angle: 3.14
axis: "Y"
1:
angle: 4
axis: "3, 5, 3.4"
group-2:
0:
angle: 1.6
axis: "6, 4, 2"
*/
for (String rotationGroupName : rotations.getKeys(false)) {
ConfigurationSection rotationGroup = rotations.getConfigurationSection(rotationGroupName);
List<Rotation> grouped = new ArrayList<>();
for (String rotationName : rotationGroup.getKeys(false)) {
ConfigurationSection rotation = rotationGroup.getConfigurationSection(rotationName);
double angle = rotation.getDouble("angle");
Vector axis;
String axisStr = rotation.getString("vector").toUpperCase(Locale.ENGLISH).replace(" ", "");
if (axisStr.length() == 1) {
axis = Axis.valueOf(axisStr).vector;
} else {
String[] split = axisStr.split(",");
axis = new Vector(Math.toRadians(Double.parseDouble(split[0])),
Math.toRadians(Double.parseDouble(split[1])),
Math.toRadians(Double.parseDouble(split[2])));
}
grouped.add(Rotation.of(angle, axis));
}
display.rotations.add(grouped);
}
}
String color = config.getString("color"); // array-like "R, G, B"
String blockdata = config.getString("blockdata"); // material name
String item = config.getString("itemstack"); // material name
String materialdata = config.getString("materialdata"); // material name
float size;
if (config.isSet("size")) {
size = (float) config.getDouble("size");
if (display.data instanceof float[]) {
float[] datas = (float[]) display.data;
if (datas.length > 3) {
datas[3] = size;
}
}
} else {
size = 1f;
}
if (color != null) {
List<String> colors = split(color.replace(" ", ""), ',');
if (colors.size() <= 3 || colors.size() == 6) { // 1 or 3 : single color, 2 or 6 : two colors for DUST_TRANSITION
Color parsedColor1 = Color.white;
Color parsedColor2 = null;
if (colors.size() <= 2) {
try {
parsedColor1 = Color.decode(colors.get(0));
if (colors.size() == 2)
parsedColor2 = Color.decode(colors.get(1));
} catch (NumberFormatException ex) {
/* I don't think it's worth it.
try {
parsedColor = (Color) Color.class.getField(colors[0].toUpperCase(Locale.ENGLISH)).get(null);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) { }
*/
}
} else {
parsedColor1 = new Color(toInt(colors.get(0)), toInt(colors.get(1)), toInt(colors.get(2)));
if (colors.size() == 6)
parsedColor2 = new Color(toInt(colors.get(3)), toInt(colors.get(4)), toInt(colors.get(5)));
}
if (parsedColor2 != null) {
display.data = new float[]{
parsedColor1.getRed(), parsedColor1.getGreen(), parsedColor1.getBlue(),
size,
parsedColor2.getRed(), parsedColor2.getGreen(), parsedColor2.getBlue()
};
} else {
display.data = new float[]{
parsedColor1.getRed(), parsedColor1.getGreen(), parsedColor1.getBlue(),
size
};
}
}
} else if (blockdata != null) {
Material material = Material.getMaterial(blockdata);
if (material != null && material.isBlock()) {
display.data = material.createBlockData();
}
} else if (item != null) {
Material material = Material.getMaterial(item);
if (material != null && material.isItem()) {
display.data = new ItemStack(material, 1);
}
} else if (materialdata != null) {
Material material = Material.getMaterial(materialdata);
if (material != null && material.isBlock()) {
display.data = material.getData();
}
}
return display;
}
/**
* Serialize a ParticleDisplay into a ConfigurationSection
*
* @param display The ParticleDisplay to serialize
* @param section The ConfigurationSection to serialize into
*/
@SuppressWarnings("deprecation")
public static void serialize(ParticleDisplay display, ConfigurationSection section) {
section.set("particle", display.particle.name());
if (display.count != 1) {
section.set("count", display.count);
}
if (display.extra != 0) {
section.set("extra", display.extra);
}
if (display.force) {
section.set("force", true);
}
if (display.offset != null) {
Vector offset = display.offset;
section.set("offset", offset.getX() + ", " + offset.getY() + ", " + offset.getZ());
}
if (!display.rotations.isEmpty()) {
ConfigurationSection rotations = section.createSection("rotations");
int index = 1;
for (List<Rotation> rotationGroup : display.rotations) {
ConfigurationSection rotationGroupSection = rotations.createSection("group-" + index++);
int groupIndex = 1;
for (Rotation rotation : rotationGroup) {
ConfigurationSection rotationSection = rotationGroupSection.createSection(
String.valueOf(groupIndex++));
rotationSection.set("angle", rotation.angle);
Vector axis = rotation.axis;
Optional<Axis> mainAxis = Arrays.stream(Axis.values())
.filter(x -> x.vector.equals(axis))
.findFirst();
if (mainAxis.isPresent()) {
rotationSection.set("axis", mainAxis.get().name());
} else {
rotationSection.set("axis", axis.getX() + ", " + axis.getY() + ", " + axis.getZ());
}
}
}
}
if (display.data instanceof float[]) {
float size = 1f;
float[] datas = (float[]) display.data;
StringJoiner colorJoiner = new StringJoiner(", ");
if (datas.length >= 3) {
if (datas.length > 3) {
size = datas[3];
}
Color color1 = new Color(datas[0], datas[1], datas[2]);
colorJoiner.add(Integer.toString(color1.getRed()));
colorJoiner.add(Integer.toString(color1.getGreen()));
colorJoiner.add(Integer.toString(color1.getBlue()));
}
if (datas.length >= 7) {
Color color2 = new Color(datas[4], datas[5], datas[6]);
colorJoiner.add(Integer.toString(color2.getRed()));
colorJoiner.add(Integer.toString(color2.getGreen()));
colorJoiner.add(Integer.toString(color2.getBlue()));
}
section.set("color", colorJoiner.toString());
section.set("size", size);
}
if (ISFLAT) {
if (display.data instanceof BlockData) {
section.set("blockdata", ((BlockData) display.data).getMaterial().name());
}
}
if (display.data instanceof ItemStack) {
section.set("itemstack", ((ItemStack) display.data).getType().name());
} else if (display.data instanceof MaterialData) {
section.set("materialdata", ((MaterialData) display.data).getItemType().name());
}
}
/**
* Rotates the given location vector around a certain axis.
*
* @param location the location to rotate.
* @param axis the axis to rotate the location around.
* @param rotation the rotation vector that contains the degrees of the rotation. The number is taken from this vector according to the given axis.
* @since 7.0.0
*/
public static Vector rotateAround(@Nonnull Vector location, @Nonnull Axis axis, @Nonnull Vector rotation) {
Objects.requireNonNull(axis, "Cannot rotate around null axis");
Objects.requireNonNull(rotation, "Rotation vector cannot be null");
switch (axis) {
case X:
return rotateAround(location, axis, rotation.getX());
case Y:
return rotateAround(location, axis, rotation.getY());
case Z:
return rotateAround(location, axis, rotation.getZ());
default:
throw new AssertionError("Unknown rotation axis: " + axis);
}
}
/**
* Rotates the given location vector around a certain axis.
*
* @param location the location to rotate.
* @since 7.0.0
*/
public static Vector rotateAround(@Nonnull Vector location, double x, double y, double z) {
rotateAround(location, Axis.X, x);
rotateAround(location, Axis.Y, y);
rotateAround(location, Axis.Z, z);
return location;
}
/**
* Rotates the given location vector around a certain axis.
* It simply uses the <a href="https://en.wikipedia.org/wiki/Rotation_matrix">rotation matrix</a>.
*
* @param location the location to rotate.
* @param axis the axis to rotate the location around.
* @param angle the rotation angle in radians.
* @since 7.0.0
*/
public static Vector rotateAround(@Nonnull Vector location, @Nonnull Axis axis, double angle) {
Objects.requireNonNull(location, "Cannot rotate a null location");
Objects.requireNonNull(axis, "Cannot rotate around null axis");
if (angle == 0) return location;
double cos = Math.cos(angle);
double sin = Math.sin(angle);
switch (axis) {
case X: {
double y = location.getY() * cos - location.getZ() * sin;
double z = location.getY() * sin + location.getZ() * cos;
return location.setY(y).setZ(z);
}
case Y: {
double x = location.getX() * cos + location.getZ() * sin;
double z = location.getX() * -sin + location.getZ() * cos;
return location.setX(x).setZ(z);
}
case Z: {
double x = location.getX() * cos - location.getY() * sin;
double y = location.getX() * sin + location.getY() * cos;
return location.setX(x).setY(y);
}
default:
throw new AssertionError("Unknown rotation axis: " + axis);
}
}
/**
* Called before rotation is applied to the xyz spawn location. The xyz provided
* in this method is implementation-specific, but it should be the xyz values that
* are going to be {@link Location#add(Vector)} to {@link #getLocation()}.
* <p>
* The provided xyz local coordinates vector might be null.
*
* @return the same particle display.
* @since 9.0.0
*/
public ParticleDisplay preCalculation(@Nullable Consumer<CalculationContext> preCalculation) {
this.preCalculation = preCalculation;
return this;
}
/**
* Called after rotation is applied to the xyz spawn location. This is the final
* location that's going to spawn a single particle.
* <p>
* The provided xyz local coordinates vector might be null.
*
* @return the same particle display.
* @since 10.0.0
*/
public ParticleDisplay postCalculation(@Nullable Consumer<CalculationContext> postCalculation) {
this.postCalculation = postCalculation;
return this;
}
/**
* Called when {@link #advanceInDirection(double)} is called.
*
* @param onAdvance The argument and the return values are the amount of blocks to advance.
* @return the same particle display.
* @since 9.0.0
*/
public ParticleDisplay onAdvance(@Nullable Function<Double, Double> onAdvance) {
this.onAdvance = onAdvance;
return this;
}
/**
* @since 7.0.0
*/
public ParticleDisplay withParticle(@Nonnull Particle particle) {
this.particle = Objects.requireNonNull(particle, "Particle cannot be null");
return this;
}
/**
* @see #direction
* @since 8.0.0
*/
@Nonnull
public Vector getDirection() {
return direction;
}
/**
* Changes the current {@link #location} in {@link #direction} by {@code distance} blocks.
*
* @since 8.0.0
*/
public void advanceInDirection(double distance) {
Objects.requireNonNull(direction, "Cannot advance with null direction");
if (distance == 0) return;
if (this.onAdvance != null) distance = onAdvance.apply(distance);
this.location.add(this.direction.clone().multiply(distance));
}
/**
* @see #direction
* @since 8.0.0
*/
public ParticleDisplay withDirection(@Nullable Vector direction) {
this.direction = direction.clone().normalize();
return this;
}
/**
* Get the particle.
*
* @return the particle.
*/
@Nonnull
public Particle getParticle() {
return particle;
}
/**
* Get the count of the particle.
*
* @return the count of the particle.
*/
public int getCount() {
return count;
}
/**
* Get the extra data of the particle.
*
* @return the extra data of the particle.
*/
public double getExtra() {
return extra;
}
/**
* Get the data object. Currently, it can be instance of float[] with [R, G, B, size],
* or instance of {@link BlockData}, {@link MaterialData} for legacy usage or {@link ItemStack}
*
* @return the data object.
* @since 5.1.0
*/
@SuppressWarnings("deprecation")
@Nullable
public Object getData() {
return data;
}
@Override
public String toString() {
return "ParticleDisplay:[" +
"Particle=" + particle + ", " +
"Count=" + count + ", " +
"Offset:{" + offset.getX() + ", " + offset.getY() + ", " + offset.getZ() + "}, " +
(location != null ? (
"Location:{" + location.getWorld().getName() + location.getX() + ", " + location.getY() + ", " + location.getZ() + "}, "
) : "") +
"Rotation:" + this.rotations + ", " +
"Extra=" + extra + ", " +
"Force=" + force + ", " +
"Data=" + (data == null ? "null" : data instanceof float[] ? Arrays.toString((float[]) data) : data);
}
/**
* Changes the particle count of the particle settings.
*
* @param count the particle count.
* @return the same particle display.
* @since 3.0.0
*/
@Nonnull
public ParticleDisplay withCount(int count) {
this.count = count;
return this;
}
/**
* In most cases extra is the speed of the particles.
*
* @param extra the extra number.
* @return the same particle display.
* @since 3.0.1
*/
@Nonnull
public ParticleDisplay withExtra(double extra) {
this.extra = extra;
return this;
}
/**
* A displayed particle with force can be seen further
* away for all player regardless of their particle
* settings. Force has no effect if specific players
* are added with {@link #spawn(Location)}.
*
* @param force the force argument.
* @return the same particle display, but modified.
* @since 5.0.1
*/
@Nonnull
public ParticleDisplay forceSpawn(boolean force) {
this.force = force;
return this;
}
/**
* Adds color properties to the particle settings.
* The particle must be {@link Particle#REDSTONE}
* to get custom colors.
*
* @param color the RGB color of the particle.
* @param size the size of the particle.
* @return the same particle display, but modified.
* @see #colored(Location, Color, float)
* @since 3.0.0
*/
@Nonnull
public ParticleDisplay withColor(@Nonnull Color color, float size) {
return withColor(color.getRed(), color.getGreen(), color.getBlue(), size);
}
/**
* @since 7.1.0
* @deprecated use {@link #withColor(Color, float)}
*/
@Nonnull
@Deprecated
public ParticleDisplay withColor(float red, float green, float blue, float size) {
this.data = new float[]{red, green, blue, size};
return this;
}
/**
* Adds color properties to the particle settings.
* The particle must be {@link Particle#DUST_COLOR_TRANSITION}
* to get custom colors.
*
* @param fromColor the RGB color of the particle on spawn.
* @param size the size of the particle.
* @param toColor the RGB color of the particle at the end.
* @return the same particle display, but modified.
* @see #colored(Location, Color, float)
* @since 8.6.0.0.1
*/
@Nonnull
public ParticleDisplay withTransitionColor(@Nonnull Color fromColor, float size, @Nonnull Color toColor) {
this.data = new float[]{
fromColor.getRed(), fromColor.getGreen(), fromColor.getBlue(),
size,
toColor.getRed(), toColor.getGreen(), toColor.getBlue()
};
return this;
}
/**
* @since 8.6.0.0.1
* @deprecated use {@link #withTransitionColor(Color, float, Color)}
*/
@Nonnull
@Deprecated
public ParticleDisplay withTransitionColor(float red1, float green1, float blue1,
float size,
float red2, float green2, float blue2) {
this.data = new float[]{red1, green1, blue1, size, red2, green2, blue2};
return this;
}
/**
* Adds data for {@link Particle#BLOCK_CRACK}, {@link Particle#BLOCK_DUST},
* {@link Particle#FALLING_DUST} and {@link Particle#BLOCK_MARKER} particles.
* The displayed particle will depend on the given block data for its color.
* <p>
* Only works on minecraft version 1.13 and more, because
* {@link BlockData} didn't exist before.
*
* @param blockData the block data that will change the particle data.
* @return the same particle display, but modified.
* @since 5.1.0
*/
@Nonnull
public ParticleDisplay withBlock(@Nonnull BlockData blockData) {
this.data = blockData;
return this;
}
/**
* Adds data for {@link Particle#LEGACY_BLOCK_CRACK}, {@link Particle#LEGACY_BLOCK_DUST}
* and {@link Particle#LEGACY_FALLING_DUST} particles if the minecraft version is 1.13 or more.
* <p>
* If version is at most 1.12, old particles {@link Particle#BLOCK_CRACK},
* {@link Particle#BLOCK_DUST} and {@link Particle#FALLING_DUST} will support this data.
*
* @param materialData the material data that will change the particle data.
* @return the same particle display, but modified.
* @see #withBlock(BlockData)
* @since 5.1.0
*/
@SuppressWarnings("deprecation")
@Nonnull
public ParticleDisplay withBlock(@Nonnull MaterialData materialData) {
this.data = materialData;
return this;
}
/**
* Adds extra data for {@link Particle#ITEM_CRACK}
* particle, depending on the given item stack.
*
* @param item the item stack that will change the particle data.
* @return the same particle display, but modified.
* @since 5.1.0
*/
@Nonnull
public ParticleDisplay withItem(@Nonnull ItemStack item) {
this.data = item;
return this;
}
@Nullable
public Vector getOffset() {
return offset;
}
/**
* Saves an instance of an entity to track the location from.
*
* @param entity the entity to track the location from.
* @return the same particle settings with the caller added.
* @since 3.1.0
*/
@Nonnull
public ParticleDisplay withEntity(@Nonnull Entity entity) {
return withLocationCaller(entity::getLocation);
}
/**
* Sets a caller for location changes.
*
* @param locationCaller the caller to call to get the new location.
* @return the same particle settings with the caller added.
* @since 3.1.0
*/
@Nonnull
public ParticleDisplay withLocationCaller(@Nullable Callable<Location> locationCaller) {
this.preCalculation = (loc) -> {
try {
this.location = locationCaller.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
return this;
}
/**
* Gets the location of an entity if specified or the constant location.
* <p>
* This method is usually the center of the shape if the algorithm which uses
* it supports the use of {@link #advanceInDirection(double)}.
*
* @return the location of the particle.
* @since 3.1.0
*/
@Nullable
public Location getLocation() {
return location;
}
/**
* Sets the location that this particle should spawn.