-
-
Notifications
You must be signed in to change notification settings - Fork 295
/
HologramTrait.java
925 lines (818 loc) · 32.4 KB
/
HologramTrait.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
package net.citizensnpcs.trait;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Display.Billboard;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.Player;
import org.bukkit.entity.TextDisplay;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Transformation;
import org.joml.Vector3d;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import net.citizensnpcs.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.command.Arg.CompletionsProvider;
import net.citizensnpcs.api.command.CommandContext;
import net.citizensnpcs.api.event.NPCEvent;
import net.citizensnpcs.api.npc.MemoryNPCDataStore;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.npc.NPCRegistry;
import net.citizensnpcs.api.persistence.Persist;
import net.citizensnpcs.api.trait.Trait;
import net.citizensnpcs.api.trait.TraitName;
import net.citizensnpcs.api.util.DataKey;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.api.util.Placeholders;
import net.citizensnpcs.api.util.SpigotUtil;
import net.citizensnpcs.util.NMS;
import net.citizensnpcs.util.Util;
/**
* Manages a set of <em>holograms</em> attached to the NPC. Holograms are lines of text or items that follow the NPC at
* some offset (typically vertically offset).
*/
@TraitName("hologramtrait")
public class HologramTrait extends Trait {
private Location currentLoc;
@Persist
private Color defaultBackgroundColor = Setting.DEFAULT_HOLOGRAM_BACKGROUND_COLOR.asString().isEmpty() ? null
: Util.parseColor(Setting.DEFAULT_HOLOGRAM_BACKGROUND_COLOR.asString());
private double lastEntityBbHeight = 0;
private boolean lastNameplateVisible;
@Persist
private double lineHeight = -1;
private final List<HologramLine> lines = Lists.newArrayList();
private HologramLine nameLine;
private final NPCRegistry registry = CitizensAPI.createCitizensBackedNPCRegistry(new MemoryNPCDataStore());
private int t;
@Persist
private int viewRange = -1;
public HologramTrait() {
super("hologramtrait");
}
/**
* Adds a new hologram line which will displayed over an NPC's head.
*
* @param text
* The new line to add
*/
public void addLine(String text) {
lines.add(new HologramLine(text, true, -1, createDefaultHologramRenderer()));
reloadLineHolograms();
}
public void addLine(String text, HologramRenderer hr) {
lines.add(new HologramLine(text, hr));
reloadLineHolograms();
}
/**
* Adds a new hologram line which will displayed over an NPC's head. It will not persist to disk and will last for
* the specified amount of ticks.
*
* @param text
* The new line to add
* @param ticks
* The number of ticks to last for
*/
public void addTemporaryLine(String text, int ticks) {
lines.add(new HologramLine(text, false, ticks, createDefaultHologramRenderer()));
reloadLineHolograms();
}
public void addTemporaryLine(String text, int ticks, HologramRenderer hr) {
lines.add(new HologramLine(text, false, ticks, hr));
reloadLineHolograms();
}
/**
* Clears all hologram lines
*/
public void clear() {
for (HologramLine line : lines) {
line.removeNPC();
}
lines.clear();
}
private HologramRenderer createDefaultHologramRenderer() {
HologramRenderer renderer;
String hologramSetting = Setting.DEFAULT_HOLOGRAM_RENDERER.asString();
if (!SUPPORTS_DISPLAY || hologramSetting.equalsIgnoreCase("armorstand")) {
renderer = new ArmorstandRenderer();
} else {
renderer = hologramSetting.equalsIgnoreCase("interaction") ? new InteractionVehicleRenderer()
: new TextDisplayRenderer();
}
if (HologramRendererCreateEvent.handlers.getRegisteredListeners().length > 0) {
HologramRendererCreateEvent event = new HologramRendererCreateEvent(npc, renderer, false);
Bukkit.getPluginManager().callEvent(event);
renderer = event.getRenderer();
}
return renderer;
}
private HologramRenderer createNameRenderer() {
HologramRenderer renderer;
if (SpigotUtil.getVersion()[1] >= 20) {
renderer = new TextDisplayVehicleRenderer();
} else if (SpigotUtil.getVersion()[1] == 19) {
renderer = new InteractionVehicleRenderer();
} else {
renderer = new ArmorstandVehicleRenderer();
}
if (HologramRendererCreateEvent.handlers.getRegisteredListeners().length > 0) {
HologramRendererCreateEvent event = new HologramRendererCreateEvent(npc, renderer, true);
Bukkit.getPluginManager().callEvent(event);
renderer = event.getRenderer();
}
return renderer;
}
public Color getDefaultBackgroundColor() {
return defaultBackgroundColor;
}
private double getHeight(int lineNumber) {
double base = lastNameplateVisible ? 0 : -getLineHeight();
for (int i = 0; i <= lineNumber; i++) {
HologramLine line = lines.get(i);
base += line.mb + getLineHeight();
if (i != lineNumber) {
base += line.mt;
}
}
return base;
}
@Deprecated
public Collection<Entity> getHologramEntities() {
return lines.stream().flatMap(l -> l.renderer.getEntities().stream()).collect(Collectors.toList());
}
public Collection<HologramRenderer> getHologramRenderers() {
return lines.stream().map(l -> l.renderer).collect(Collectors.toList());
}
/**
* @return The line height between each hologram line, in blocks
*/
public double getLineHeight() {
return lineHeight == -1 ? Setting.DEFAULT_NPC_HOLOGRAM_LINE_HEIGHT.asDouble() : lineHeight;
}
/**
* @return the hologram lines, in bottom-up order
*/
public List<String> getLines() {
return Lists.transform(lines, l -> l.text);
}
@Deprecated
public Entity getNameEntity() {
return nameLine == null || nameLine.renderer.getEntities().size() == 0 ? null
: nameLine.renderer.getEntities().iterator().next();
}
public HologramRenderer getNameRenderer() {
return nameLine == null ? null : nameLine.renderer;
}
public int getViewRange() {
return viewRange;
}
@Override
public void load(DataKey root) {
clear();
for (DataKey key : root.getRelative("lines").getIntegerSubKeys()) {
HologramLine line = new HologramLine(key.keyExists("text") ? key.getString("text") : key.getString(""),
true, -1, createDefaultHologramRenderer());
line.mt = key.keyExists("margin.top") ? key.getDouble("margin.top") : 0.0;
line.mb = key.keyExists("margin.bottom") ? key.getDouble("margin.bottom") : 0.0;
if (key.keyExists("backgroundcolor")) {
line.setBackgroundColor(Color.fromARGB(key.getInt("backgroundcolor")));
}
lines.add(line);
}
}
@Override
public void onDespawn() {
reloadLineHolograms();
}
@Override
public void onRemove() {
onDespawn();
}
@Override
public void onSpawn() {
if (!npc.isSpawned())
return;
lastNameplateVisible = Boolean
.parseBoolean(npc.data().<Object> get(NPC.Metadata.NAMEPLATE_VISIBLE, true).toString());
}
private void reloadLineHolograms() {
for (HologramLine line : lines) {
line.removeNPC();
}
if (nameLine != null) {
nameLine.removeNPC();
nameLine = null;
}
}
/**
* Removes the line at the specified index
*
* @param idx
*/
public void removeLine(int idx) {
if (idx < 0 || idx >= lines.size())
return;
lines.remove(idx).removeNPC();
reloadLineHolograms();
}
@Override
public void run() {
if (!npc.isSpawned()) {
onDespawn();
return;
}
boolean nameplateVisible = Boolean
.parseBoolean(npc.data().<Object> get(NPC.Metadata.NAMEPLATE_VISIBLE, true).toString());
if (npc.requiresNameHologram()) {
if (nameLine != null && !nameplateVisible) {
nameLine.removeNPC();
nameLine = null;
} else if (nameLine == null && nameplateVisible) {
nameLine = new HologramLine(npc.getRawName(), createNameRenderer());
}
}
Location npcLoc = npc.getStoredLocation();
Vector3d offset = new Vector3d();
boolean updatePosition = Setting.HOLOGRAM_ALWAYS_UPDATE_POSITION.asBoolean() || currentLoc == null
|| currentLoc.getWorld() != npcLoc.getWorld() || currentLoc.distance(npcLoc) >= 0.001
|| lastNameplateVisible != nameplateVisible
|| Math.abs(lastEntityBbHeight - NMS.getBoundingBoxHeight(npc.getEntity())) >= 0.05;
boolean updateName = false;
if (t++ >= Setting.HOLOGRAM_UPDATE_RATE.asTicks() + Util.getFastRandom().nextInt(3) /* add some jitter */) {
t = 0;
updateName = true;
}
lastNameplateVisible = nameplateVisible;
if (updatePosition) {
currentLoc = npcLoc.clone();
lastEntityBbHeight = NMS.getBoundingBoxHeight(npc.getEntity());
}
if (nameLine != null) {
if (updatePosition || nameLine.renderer.getEntities().size() == 0) {
nameLine.render(offset);
}
if (updateName) {
nameLine.setText(npc.getRawName());
}
}
for (int i = 0; i < lines.size(); i++) {
HologramLine line = lines.get(i);
if (line.ticks > 0 && --line.ticks == 0) {
lines.remove(i--).removeNPC();
continue;
}
if (updatePosition || line.renderer.getEntities().size() == 0) {
offset.y = getHeight(i);
line.render(offset);
}
if (updateName) {
line.setText(line.text);
}
}
}
@Override
public void save(DataKey root) {
root.removeKey("lines");
int i = 0;
for (HologramLine line : lines) {
if (!line.persist)
continue;
if (line.backgroundColor != null && !line.backgroundColor.equals(defaultBackgroundColor)) {
root.setInt("lines." + i + ".backgroundcolor", line.backgroundColor.asARGB());
} else {
root.removeKey("lines." + i + ".backgroundcolor");
}
root.setString("lines." + i + ".text", line.text);
root.setDouble("lines." + i + ".margin.top", line.mt);
root.setDouble("lines." + i + ".margin.bottom", line.mb);
i++;
}
}
public void setBackgroundColor(int idx, Color color) {
lines.get(idx).setBackgroundColor(color);
reloadLineHolograms();
}
public void setDefaultBackgroundColor(Color color) {
this.defaultBackgroundColor = color;
for (HologramLine line : Iterables.concat(lines, ImmutableList.of(nameLine))) {
if (line.backgroundColor == null) {
line.setBackgroundColor(color);
}
}
reloadLineHolograms();
}
/**
* Sets the hologram line at a specific index
*
* @param idx
* The index
* @param text
* The new line
*/
public void setLine(int idx, String text) {
if (idx == lines.size()) {
addLine(text);
return;
}
HologramLine line = lines.get(idx);
line.setText(text);
reloadLineHolograms();
}
/**
* Sets the line height
*
* @see #getLineHeight()
* @param height
* The line height in blocks
*/
public void setLineHeight(double height) {
lineHeight = height;
reloadLineHolograms();
}
/**
* Sets the margin of a line at a specific index
*
* @param idx
* The line index
* @param type
* The margin type, top or bottom
* @param margin
* The margin
*/
public void setMargin(int idx, String type, double margin) {
if (type.equalsIgnoreCase("top")) {
lines.get(idx).mt = margin;
} else if (type.equalsIgnoreCase("bottom")) {
lines.get(idx).mb = margin;
}
reloadLineHolograms();
}
public void setViewRange(int range) {
this.viewRange = range;
reloadLineHolograms();
}
public static class ArmorstandRenderer extends SingleEntityHologramRenderer {
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
NPC npc = registry().createNPC(EntityType.ARMOR_STAND, name);
npc.getOrAddTrait(ArmorStandTrait.class).setAsHelperEntityWithName(npc);
return npc;
}
@Override
protected void render0(NPC npc, Vector3d offset) {
hologram.getEntity().teleport(npc.getStoredLocation().clone().add(offset.x,
offset.y + NMS.getBoundingBoxHeight(npc.getEntity()), offset.z), TeleportCause.PLUGIN);
}
}
public static class ArmorstandVehicleRenderer extends ArmorstandRenderer {
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
NPC npc = registry().createNPC(EntityType.ARMOR_STAND, name);
npc.getOrAddTrait(ArmorStandTrait.class).setAsHelperEntityWithName(npc);
return npc;
}
@Override
public void render0(NPC base, Vector3d offset) {
if (hologram.getEntity().getVehicle() == null) {
NMS.mount(base.getEntity(), hologram.getEntity());
}
}
}
class HologramLine {
Color backgroundColor = defaultBackgroundColor;
double mb, mt;
boolean persist;
HologramRenderer renderer;
String text;
int ticks;
public HologramLine(String text, boolean persist, int ticks, HologramRenderer hr) {
if (ITEM_MATCHER.matcher(text).find()) {
mb = 0.21;
mt = 0.07;
hr = new ItemRenderer();
} else if (SUPPORTS_DISPLAY && backgroundColor != null) {
renderer = new TextDisplayRenderer(backgroundColor);
}
this.persist = persist;
this.ticks = ticks;
this.renderer = hr;
if (renderer instanceof SingleEntityHologramRenderer) {
SingleEntityHologramRenderer sr = (SingleEntityHologramRenderer) renderer;
sr.setViewRange(viewRange);
sr.setRegistry(registry);
}
setText(text);
}
public HologramLine(String text, HologramRenderer renderer) {
this(text, false, -1, renderer);
}
public void removeNPC() {
renderer.destroy();
}
public void render(Vector3d vector3d) {
renderer.render(npc, vector3d);
}
public void setBackgroundColor(Color color) {
this.backgroundColor = color;
renderer.setBackgroundColor(color);
}
public void setText(String text) {
this.text = text == null ? "" : text;
if (ITEM_MATCHER.matcher(text).find() && !(renderer instanceof ItemRenderer)) {
renderer.destroy();
mb = 0.21;
mt = 0.07;
renderer = new ItemRenderer();
}
renderer.updateText(npc, text);
}
}
/**
* API for rendering holograms. Assumptions are documented in Javadoc but the API is early and subject to change.
* Feedback is welcomed.
*/
public static interface HologramRenderer {
/**
* Destroy/teardown any rendered holograms.
*/
void destroy();
/**
* @return Any associated hologram entities. Used in {@link #getEntities()}.
*/
Collection<Entity> getEntities();
/**
* If {@link NPC.Metadata.HOLOGRAM_RENDERER} is set on any entity and ProtocolLib is enabled, this method will
* be called to modify the name per-player. Note: this should be async-safe. This method is fragile and may be
* moved elsewhere.
*
* @param hologram
* the <em>hologram</em> NPC
* @param viewer
* the viewing Player
* @return the modified text per Player
*/
String getPerPlayerText(NPC hologram, Player viewer);
/**
* If {@link NPC.Metadata.HOLOGRAM_RENDERER} is set on any entity and ProtocolLib is enabled, returns whether
* the NPC should be considered sneaking or not to the viewing player. Presently called only when player first
* sees the NPC (i.e. not proactively).Note: this should be async-safe. This method is fragile and may be moved
* elsewhere.
*
* @param hologram
* the <em>hologram</em> NPC
* @param player
* the viewing Player
* @return whether the NPC is sneaking
*/
default boolean isSneaking(NPC hologram, Player player) {
return NMS.isSneaking(player);
}
/**
* If {@link NPC.Metadata.HOLOGRAM_RENDERER} is set on any entity, called when it is seen for the first time by
* a Player.
*
* @param hologram
* the <em>hologram</em> NPC
* @param player
* the viewing Player
*/
default void onSeenByPlayer(NPC hologram, Player player) {
}
/**
* Render the hologram at a given offset. Any underlying hologram NPCs should be spawned at this point.
*
* @param parent
* the <em>parent</em> NPC.
* @param offset
* the offset, in blocks
*/
void render(NPC parent, Vector3d offset);
default void setBackgroundColor(Color color) {
}
/**
* Update the hologram text. Will be called first before {@link #render(NPC, Vector3d)}.
*
* @param parent
* the <em>parent</em> NPC
* @param text
* the new hologram text
*/
void updateText(NPC parent, String text);
}
public static class HologramRendererCreateEvent extends NPCEvent {
private final boolean nameRenderer;
private HologramRenderer renderer;
protected HologramRendererCreateEvent(NPC npc, HologramRenderer renderer, boolean nameRenderer) {
super(npc);
this.renderer = renderer;
this.nameRenderer = nameRenderer;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public HologramRenderer getRenderer() {
return renderer;
}
public boolean isNameRenderer() {
return nameRenderer;
}
public void setRenderer(HologramRenderer renderer) {
Objects.requireNonNull(renderer);
this.renderer = renderer;
}
private static final HandlerList handlers = new HandlerList();
}
public static class InteractionVehicleRenderer extends SingleEntityHologramRenderer {
private Vector3d lastOffset;
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
lastOffset = new Vector3d(offset);
return registry().createNPC(EntityType.INTERACTION, name);
}
@Override
public void onSeenByPlayer(NPC npc, Player player) {
if (lastOffset == null)
return;
NMS.linkTextInteraction(player, hologram.getEntity(), npc.getEntity(), lastOffset.y);
}
@Override
public void render0(NPC npc, Vector3d offset) {
lastOffset = new Vector3d(offset);
if (hologram.getEntity().getVehicle() == null) {
NMS.mount(npc.getEntity(), hologram.getEntity());
}
}
}
public static class ItemDisplayRenderer extends SingleEntityHologramRenderer {
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
Matcher itemMatcher = ITEM_MATCHER.matcher(name);
itemMatcher.find();
Material item = SpigotUtil.isUsing1_13API() ? Material.matchMaterial(itemMatcher.group(1), false)
: Material.matchMaterial(itemMatcher.group(1));
ItemStack itemStack = new ItemStack(item, 1);
NPC npc = registry().createNPCUsingItem(EntityType.ITEM_DISPLAY, "", itemStack);
npc.data().setPersistent(NPC.Metadata.NAMEPLATE_VISIBLE, false);
if (itemMatcher.group(2) != null) {
if (itemMatcher.group(2).charAt(1) == '{') {
Bukkit.getUnsafe().modifyItemStack(itemStack, itemMatcher.group(2).substring(1));
npc.setItemProvider(() -> itemStack);
} else {
npc.getOrAddTrait(ScoreboardTrait.class)
.setColor(Util.matchEnum(ChatColor.values(), itemMatcher.group(2).substring(1)));
}
}
return npc;
}
@Override
public void render0(NPC base, Vector3d offset) {
ItemDisplay disp = (ItemDisplay) hologram.getEntity();
Transformation tf = disp.getTransformation();
tf.getTranslation().y = (float) offset.y + 0.1f;
disp.setTransformation(tf);
if (hologram.getEntity().getVehicle() == null) {
NMS.mount(base.getEntity(), hologram.getEntity());
}
}
@Override
public void updateText(NPC npc, String text) {
this.text = Placeholders.replace(text, null, npc);
}
}
public static class ItemRenderer extends SingleEntityHologramRenderer {
private NPC itemNPC;
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
NPC mount = registry().createNPC(EntityType.ARMOR_STAND, "");
mount.getOrAddTrait(ArmorStandTrait.class).setAsPointEntity();
Matcher itemMatcher = ITEM_MATCHER.matcher(name);
itemMatcher.find();
Material item = SpigotUtil.isUsing1_13API() ? Material.matchMaterial(itemMatcher.group(1), false)
: Material.matchMaterial(itemMatcher.group(1));
ItemStack itemStack = new ItemStack(item, 1);
itemNPC = registry().createNPCUsingItem(Util.getFallbackEntityType("ITEM", "DROPPED_ITEM"), "", itemStack);
itemNPC.data().setPersistent(NPC.Metadata.NAMEPLATE_VISIBLE, false);
if (itemMatcher.group(2) != null) {
if (itemMatcher.group(2).charAt(1) == '{') {
Bukkit.getUnsafe().modifyItemStack(itemStack, itemMatcher.group(2).substring(1));
itemNPC.setItemProvider(() -> itemStack);
} else {
itemNPC.getOrAddTrait(ScoreboardTrait.class)
.setColor(Util.matchEnum(ChatColor.values(), itemMatcher.group(2).substring(1)));
}
}
itemNPC.spawn(base.getLocation());
itemNPC.getOrAddTrait(MountTrait.class).setMountedOn(mount.getUniqueId());
return mount;
}
@Override
public void destroy() {
super.destroy();
if (itemNPC == null)
return;
itemNPC.destroy();
itemNPC = null;
}
@Override
protected void render0(NPC npc, Vector3d offset) {
hologram.getEntity().teleport(npc.getStoredLocation().clone().add(offset.x,
offset.y + NMS.getBoundingBoxHeight(npc.getEntity()), offset.z), TeleportCause.PLUGIN);
}
@Override
public void updateText(NPC npc, String text) {
this.text = Placeholders.replace(text, null, npc);
}
}
/**
* A helper class that models a hologram as a single entity that represents a single line in game.
*/
// TODO: make view range part of hologram renderer?
public abstract static class SingleEntityHologramRenderer implements HologramRenderer {
protected NPC hologram;
private NPCRegistry registry;
protected String text;
protected int viewRange = -1;
protected abstract NPC createNPC(Entity base, String text, Vector3d offset);
@Override
public void destroy() {
if (hologram != null) {
hologram.destroy();
hologram = null;
}
}
@Override
public Collection<Entity> getEntities() {
return hologram != null && hologram.getEntity() != null ? ImmutableList.of(hologram.getEntity())
: Collections.emptyList();
}
@Override
public String getPerPlayerText(NPC npc, Player viewer) {
return Placeholders.replace(text, viewer, npc);
}
protected NPCRegistry registry() {
return registry == null ? registry = CitizensAPI.createCitizensBackedNPCRegistry(new MemoryNPCDataStore())
: registry;
}
@Override
public void render(NPC npc, Vector3d offset) {
if (hologram == null) {
spawnHologram(npc, offset);
}
render0(npc, offset);
}
/**
* Hologram spawning is delegated to {@link #createNPC(Entity, String, Vector3d)}
*/
protected abstract void render0(NPC npc, Vector3d offset);
public void setRegistry(NPCRegistry registry) {
this.registry = registry;
}
public void setViewRange(int range) {
this.viewRange = range;
}
protected void spawnHologram(NPC npc, Vector3d offset) {
hologram = createNPC(npc.getEntity(), text, offset);
if (!hologram.hasTrait(ClickRedirectTrait.class)) {
hologram.addTrait(new ClickRedirectTrait(npc));
}
hologram.data().set(NPC.Metadata.HOLOGRAM_RENDERER, this);
if (Setting.PACKET_HOLOGRAMS.asBoolean()) {
hologram.addTrait(PacketNPC.class);
}
if (viewRange != -1) {
hologram.data().set(NPC.Metadata.TRACKING_RANGE, viewRange);
} else if (npc.data().has(NPC.Metadata.TRACKING_RANGE)) {
hologram.data().set(NPC.Metadata.TRACKING_RANGE, npc.data().get(NPC.Metadata.TRACKING_RANGE));
}
hologram.spawn(npc.getEntity().getLocation().add(offset.x,
offset.y + NMS.getBoundingBoxHeight(npc.getEntity()), offset.z));
}
@Override
public void updateText(NPC npc, String raw) {
this.text = Placeholders.replace(raw, null, npc);
if (hologram == null)
return;
hologram.setName(text);
if (!Placeholders.containsPlaceholders(raw)) {
hologram.data().set(NPC.Metadata.NAMEPLATE_VISIBLE, Messaging.stripColor(raw).length() > 0);
}
}
}
public static class TabCompletions implements CompletionsProvider {
@Override
public Collection<String> getCompletions(CommandContext args, CommandSender sender, NPC npc) {
if (args.length() > 1 && npc != null && LINE_ARGS.contains(args.getString(1).toLowerCase())) {
HologramTrait ht = npc.getOrAddTrait(HologramTrait.class);
return IntStream.range(0, ht.getLines().size()).mapToObj(Integer::toString)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
private static Set<String> LINE_ARGS = ImmutableSet.of("set", "remove", "margintop", "marginbottom");
}
public static class TextDisplayRenderer extends SingleEntityHologramRenderer {
private Color color;
public TextDisplayRenderer() {
}
public TextDisplayRenderer(Color color) {
this.color = color;
}
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
NPC hologram = registry().createNPC(EntityType.TEXT_DISPLAY, "");
hologram.data().set(NPC.Metadata.NAMEPLATE_VISIBLE, false);
hologram.data().set(NPC.Metadata.TEXT_DISPLAY_COMPONENT, Messaging.minecraftComponentFromRawMessage(name));
return hologram;
}
@Override
public void render0(NPC base, Vector3d offset) {
TextDisplay disp = (TextDisplay) hologram.getEntity();
disp.setInterpolationDelay(0);
disp.setInterpolationDuration(0);
disp.setBillboard(Billboard.CENTER);
if (color != null) {
disp.setBackgroundColor(color);
}
hologram.getEntity().teleport(
base.getStoredLocation().clone().add(offset.x,
offset.y + NMS.getBoundingBoxHeight(base.getEntity()) + 0.2f, offset.z),
TeleportCause.PLUGIN);
}
@Override
public void setBackgroundColor(Color color) {
this.color = color;
}
@Override
public void updateText(NPC npc, String raw) {
this.text = Placeholders.replace(raw, null, npc);
if (hologram == null)
return;
hologram.data().set(NPC.Metadata.TEXT_DISPLAY_COMPONENT, Messaging.minecraftComponentFromRawMessage(text));
}
}
public static class TextDisplayVehicleRenderer extends SingleEntityHologramRenderer {
private Color color;
@Override
protected NPC createNPC(Entity base, String name, Vector3d offset) {
NPC hologram = registry().createNPC(EntityType.TEXT_DISPLAY, "");
hologram.data().set(NPC.Metadata.NAMEPLATE_VISIBLE, false);
hologram.data().set(NPC.Metadata.TEXT_DISPLAY_COMPONENT, Messaging.minecraftComponentFromRawMessage(name));
return hologram;
}
@Override
public void render0(NPC base, Vector3d offset) {
TextDisplay disp = (TextDisplay) hologram.getEntity();
disp.setInterpolationDelay(0);
disp.setInterpolationDuration(0);
disp.setBillboard(Billboard.CENTER);
Transformation tf = disp.getTransformation();
tf.getTranslation().y = (float) offset.y + 0.4f;
disp.setTransformation(tf);
if (color != null) {
disp.setBackgroundColor(color);
}
if (hologram.getEntity().getVehicle() == null) {
NMS.mount(base.getEntity(), hologram.getEntity());
}
}
@Override
public void setBackgroundColor(Color color) {
this.color = color;
}
@Override
public void updateText(NPC npc, String raw) {
this.text = Placeholders.replace(raw, null, npc);
if (hologram == null)
return;
hologram.data().set(NPC.Metadata.TEXT_DISPLAY_COMPONENT, Messaging.minecraftComponentFromRawMessage(text));
}
}
private static final Pattern ITEM_MATCHER = Pattern.compile("<item:([a-zA-Z0-9_ ]*?)([:].*?)?>");
private static boolean SUPPORTS_DISPLAY = false;
static {
try {
SUPPORTS_DISPLAY = Class.forName("org.bukkit.entity.Display") != null;
} catch (Throwable e) {
}
}
}