-
Notifications
You must be signed in to change notification settings - Fork 8
/
witchcraft.clj
1987 lines (1673 loc) · 58.6 KB
/
witchcraft.clj
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
(ns lambdaisland.witchcraft
"Clojure API for Minecraft/Bukkit"
(:refer-clojure :exclude [time bean chunk satisfies?])
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.set :as set]
[lambdaisland.witchcraft.events :as events]
[lambdaisland.witchcraft.safe-bean :refer [bean bean->]]
[lambdaisland.witchcraft.util :as util]
[lambdaisland.witchcraft.markup :as markup]
[lambdaisland.witchcraft.reflect :as reflect])
(:import (java.util UUID)
(com.cryptomorin.xseries XMaterial XBlock)
(org.bukkit Bukkit
Chunk
Difficulty
Location
Material
Server
World
WorldCreator)
(org.bukkit.block Block BlockFace)
;; (org.bukkit.block.data BlockData) ; not yet available in Glowstone 1.12
(org.bukkit.configuration.serialization ConfigurationSerialization)
(org.bukkit.enchantments Enchantment)
(org.bukkit.entity Entity Player HumanEntity LivingEntity)
(org.bukkit.inventory ItemStack Inventory)
(org.bukkit.inventory.meta ItemMeta)
(org.bukkit.material MaterialData Directional)
(org.bukkit.plugin PluginManager Plugin)
(org.bukkit.potion Potion PotionEffectType)
(org.bukkit.scheduler BukkitScheduler)
(org.bukkit.util Vector)))
(set! *warn-on-reflection* true)
(def satisfies-cache (volatile! {}))
(defn satisfies?
"Like clojure.core/satisfies?, but cache the result. We make heavy use of
satisfies, and this is not very well optimized in core."
[protocol x]
(let [klazz (class x)
iface (:on-interface protocol)]
(if-some [i (get-in @satisfies-cache [iface klazz])]
(boolean i)
(let [i (boolean (find-protocol-impl protocol x))]
(vswap! satisfies-cache assoc-in [iface klazz] i)
i))))
(defonce server-type nil)
(def ^:dynamic *default-world* nil)
(defn pre-flattening? []
(not (XMaterial/supports 13)))
(defn start-glowstone!
"Start an embedded Glowstone server
Optionally provided with a map of config options.
See [[lambdaisland.witchcraft.config/key-values]]"
[& args]
(alter-var-root #'server-type (constantly :glowstone))
(apply @(requiring-resolve 'lambdaisland.witchcraft.glowstone/start!) args))
(defn start-paper!
"Start an embedded PaperMC server"
[& [gui?]]
(alter-var-root #'server-type (constantly :paper))
(@(requiring-resolve 'lambdaisland.witchcraft.paper/start!) gui?))
(defn stop!
"Stop the embedded server"
[]
(case server-type
:glowstone
(@(requiring-resolve 'lambdaisland.witchcraft.glowstone/stop!))
:paper
(throw (ex-info "stop! not implemented for PaperMC" {}))))
(declare in-front-of map->Location)
(def ^Plugin plugin
"For the rare API calls that really want a plugin instance"
(proxy [org.bukkit.plugin.PluginBase] []
(getDescription []
(org.bukkit.plugin.PluginDescriptionFile. "Witchcraft" "0.0" ""))
(isEnabled []
true)
(getLogger []
(java.util.logging.Logger/getLogger "witchcraft"))))
(defonce undo-history (atom ()))
(defonce redo-history (atom ()))
;; FIXME: these don't actually work the way I inteneded them to work, might
;; require a custom set implementation.
(def EMPTY_BLOCK_SET
"Make sure there is only one block for each coordinate in the set, and keep them
sorted by x/z/y."
(sorted-set-by #(compare ((juxt :x :z :y) %1)
((juxt :x :z :y) %2))))
(defn block-set
"Create a block set, a set of maps where every :x/:y/:z value can only occur
once."
([coll]
(into EMPTY_BLOCK_SET coll))
([xform coll]
(into EMPTY_BLOCK_SET xform coll)))
;; ================================================================================
(defn enchantment-key [^Enchantment e]
;; FIXME: no getKey on Glowstone 1.12
(keyword
(-> e
.getKey
str
(str/replace #"^minecraft:" "")
(str/replace #"_" "-"))))
(def entity-types
"Map from keyword to EntityType value"
(util/enum->map org.bukkit.entity.EntityType))
(def enchant-types
"Map from keyword to Enchantment"
(into {}
(map (juxt enchantment-key identity))
(Enchantment/values)))
(def difficulty-types
"Map from keyword to Difficulty"
{:peaceful Difficulty/PEACEFUL
:easy Difficulty/EASY
:normal Difficulty/NORMAL
:hard Difficulty/HARD})
(util/when-class-exists
org.bukkit.GameRule
(def game-rule-types
"Map from keyword to GameRule"
(into {}
(map (juxt #(keyword (util/dasherize (.getName ^org.bukkit.GameRule %))) identity))
(org.bukkit.GameRule/values))))
(def inventory-types
(util/enum->map org.bukkit.event.inventory.InventoryType))
(defonce ^{:doc "Map from keyword to XMaterial value"} materials {})
(defonce ^{:doc "Map from XMaterial value to keyword"} material-names {})
(def block-faces
"Map from keyword to BlockFace value"
(util/enum->map org.bukkit.block.BlockFace))
(def block-face-names
"Map from BlockFace value to keyword"
(into {} (map (juxt val key)) block-faces))
(def tree-species
"Map from keyword to TreeSpecies value"
(util/enum->map org.bukkit.TreeSpecies))
(def block-actions
"Map from keyword to block.Action value"
(util/enum->map org.bukkit.event.block.Action))
(defn server
"Get the currently active server."
^Server []
(Bukkit/getServer))
(defn plugin-manager
"Get the Bukkit plugin manager"
^PluginManager
[]
(Bukkit/getPluginManager))
(defn scheduler
"The Bukkit scheduler"
^BukkitScheduler
[]
(Bukkit/getScheduler))
;; =============================================================================
;; Functions for retrieving things from objects, like the location, x/y/z
;; values, world, etc. We also implement these for maps, where they do keyword
;; lookups. By using these in other functions we can accept a large range of
;; inputs, including both Glowstone/Bukkit objects and Clojure maps.
(defprotocol PolymorphicFunctions
;; Keep these classnames fully qualified, Clojure doesn't like it otherwise
;; when called from namespaces where these are not imported.
(-add [this that]
"Add locations, vectors, etc. That can also be a map of `:x`, `:y`, `:z`")
(^org.bukkit.util.Vector direction-vec [_])
(^org.bukkit.util.Vector as-vec [_] "Coerce to org.bukkit.util.Vector")
(material-data [_])
(with-xyz [_ xyz] "Return the same type, but with x/y/z updated")
(^org.bukkit.Chunk chunk [_] "Retrieve the chunk for a location, entity, etc.")
(entities [_] "Get the chunk's entities"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interop protocols
;;
;; These functions all start with a `-`, indicating they are just a low-level
;; proxy to an underlying interop form. See the `reflect/extend-signature` calls
;; lower down.
(defprotocol HasUUID
(^java.util.UUID -uuid [_]))
(defprotocol HasLocation
(^org.bukkit.Location -location [_] "Get the location of the given object"))
(defprotocol HasXYZ
(-x [_])
(-y [_])
(-z [_]))
(defprotocol HasPitchYaw
(-pitch [_])
(-yaw [_]))
(defprotocol HasWorld
(^org.bukkit.World -world [_] [_ _]))
(defprotocol HasWorlds
(^java.util.List -worlds [_])
(^org.bukkit.World -world-by-name [_ ^String _])
(^org.bukkit.World -world-by-uuid [_ ^UUID _]))
(defprotocol HasItemMeta
(^org.bukkit.inventory.meta.ItemMeta -item-meta [_])
(-set-item-meta [_ ^org.bukkit.inventory.meta.ItemMeta _]))
(defprotocol HasMaterial
(^org.bukkit.Material -material [_]))
(defprotocol HasDisplayName
(^String -display-name [_])
(-set-display-name [_ ^String _]))
(defprotocol CanRenderDisplayName
(-render-and-set-display-name [_ ^String _]))
(defprotocol HasLore
(^java.util.List -lore [_])
(-set-lore [_ _]))
(defprotocol HasTargetBlock
(^org.bukkit.Block -get-target-block [_ transparent max-distance]))
(defprotocol HasBlock
(^org.bukkit.block.Block -block [_]))
(defprotocol HasBlockData
(^org.bukkit.block.data.BlockData -get-block-data [_])
(-set-block-data [_ _]))
(defprotocol HasBlockState
(^org.bukkit.block.BlockState -block-state [_]))
(defprotocol HasCustomName
(^String -get-custom-name [_])
(-set-custom-name [_ ^String _]))
(defprotocol HasInventory
(^org.bukkit.inventory.Inventory -inventory [_]))
(defprotocol HasItemStack
(^org.bukkit.inventory.ItemStack -item-stack [_]))
(defprotocol HasEntity
(^org.bukkit.entity.Entity -entity [_]))
(defprotocol HasDifficulty
(-get-difficulty [_])
(-set-difficulty [_ d]))
(defprotocol HasPlayer
(-player [_]))
(defprotocol CanParseBlockData
(^org.bukkit.block.data.BlockData -parse-block-data [_ _]))
(defprotocol CanBreakNaturally (-break-naturally [_]))
(defprotocol CanBreakNaturallyTool (-break-naturally-tool [_ tool]))
(defprotocol CanBreakNaturallyEffect (-break-naturally-effect [_ effect]))
(defprotocol CanBreakNaturallyToolEffect (-break-naturally-tool-effect [_ tool effect?]))
(defprotocol CanSpawn (-spawn [thing location]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interop protocol implementations
(declare ^World default-world)
(reflect/extend-signatures HasUUID
"java.util.UUID getUniqueId()"
(-uuid [this] (.getUniqueId this))
"java.util.UUID uuid()"
(-uuid [this] (.uuid this))
"java.util.UUID id()"
(-uuid [this] (.id this))
"java.util.UUID getId()"
(-uuid [this] (.getId this))
"java.util.UUID getUID()"
(-uuid [this] (.getUID this))
"java.util.UUID getUUID()"
(-uuid [this] (.getUUID this)))
(reflect/extend-signatures HasLocation
"org.bukkit.Location getLocation()"
(-location [this]
(.getLocation this))
"org.bukkit.Location toLocation(org.bukkit.World)"
(-location [this]
(.toLocation this (default-world))))
(reflect/extend-signatures HasXYZ
"double getX()" (-x [this] (.getX this))
"double getY()" (-y [this] (.getY this))
"double getZ()" (-z [this] (.getZ this))
"int getX()" (-x [this] (.getX this))
"int getY()" (-y [this] (.getY this))
"int getZ()" (-z [this] (.getZ this)))
(reflect/extend-signatures HasPitchYaw
"float getPitch()" (-pitch [this] (.getPitch this))
"float getYaw()" (-yaw [this] (.getYaw this)))
;; Chunks only have x and z
(extend-protocol HasXYZ
org.bukkit.Chunk (-y [_] 0)
org.bukkit.ChunkSnapshot (-y [_] 0))
(reflect/extend-signatures HasWorld
"org.bukkit.World getWorld()"
(-world [this]
(.getWorld this)))
(reflect/extend-signatures HasWorlds
"java.util.List getWorlds()"
(-worlds [this]
(.getWorlds this))
"org.bukkit.World getWorld(java.lang.String)"
(-world-by-name [this ^String obj]
(.getWorld this obj))
"org.bukkit.World getWorld(java.util.UUID)"
(-world-by-uuid [this ^java.util.UUID obj]
(.getWorld this obj)))
(reflect/extend-signatures HasItemMeta
"org.bukkit.inventory.meta.ItemMeta getItemMeta()"
(-item-meta [this]
(.getItemMeta this))
"setItemMeta(org.bukkit.inventory.meta.ItemMeta)"
(-set-item-meta [this ^org.bukkit.inventory.meta.ItemMeta im]
(.setItemMeta this im)))
(reflect/extend-signatures HasDisplayName
"java.lang.String getDisplayName()"
(-display-name [this]
(.getDisplayName this))
"setDisplayName(java.lang.String)"
(-set-display-name [this ^String n]
(.setDisplayName this n)))
(reflect/extend-signatures CanRenderDisplayName
"displayName(net.kyori.adventure.text.Component)"
(-render-and-set-display-name [this ^String n]
;; This seems to be just a Paper thing
(.displayName this ((requiring-resolve 'lambdaisland.witchcraft.adventure.text/component) n))))
(reflect/extend-signatures HasLore
"java.util.List getLore()"
(-lore [this]
(.getLore this))
"setLore(java.util.List)"
(-set-lore [this lore]
(.setLore this lore)))
(reflect/extend-signatures HasTargetBlock
"org.bukkit.block.Block getTargetBlock(java.util.Set,int)"
(-get-target-block [this ^java.util.Set transparent ^long max-distance]
(.getTargetBlock this transparent max-distance)))
(reflect/extend-signatures HasBlock
"org.bukkit.block.Block getBlock()"
(-block [this]
(.getBlock this)))
(reflect/extend-signatures HasBlockState
"org.bukkit.block.BlockState getState()"
(-block-state [this]
(.getState this))
"org.bukkit.block.BlockState getBlockState()"
(-block-state [this]
(.getBlockState this)))
(reflect/extend-signatures HasCustomName
"java.lang.String getCustomName()"
(-get-custom-name [this]
(.getCustomName this))
"setCustomName(java.lang.String)"
(-set-custom-name [this name]
(.setCustomName this name)))
(util/when-class-exists org.bukkit.block.data.BlockData
(reflect/extend-signatures HasBlockData
"org.bukkit.block.data.BlockData getBlockData()"
(-get-block-data [this]
(.getBlockData this))
"void setBlockData(org.bukkit.block.data.BlockData)"
(-set-block-data [this ^org.bukkit.block.data.BlockData bd]
(.setBlockData this bd))))
(reflect/extend-signatures HasMaterial
"org.bukkit.Material getMaterial()"
(-material [this] (.getMaterial this))
"org.bukkit.Material getType()"
(-material [this] (.getType this)))
(reflect/extend-signatures HasEntity
"org.bukkit.entity.Entity getEntity()"
(-entity [this] (.getEntity this)))
(reflect/extend-signatures CanParseBlockData
"org.bukkit.block.data.BlockData createBlockData(java.lang.String)"
(-parse-block-data [this ^String string]
(.createBlockData this string)))
(reflect/extend-signatures HasInventory
"org.bukkit.inventory.Inventory getInventory()"
(-inventory [this]
(.getInventory this)))
(reflect/extend-signatures HasItemStack
"org.bukkit.inventory.ItemStack getItemStack()"
(-item-stack [this]
(.getItemStack this)))
(reflect/extend-signatures CanBreakNaturally
"boolean breakNaturally()"
(-break-naturally [this] (.breakNaturally this)))
(reflect/extend-signatures CanBreakNaturallyTool
"boolean breakNaturally(org.bukkit.inventory.ItemStack)"
(-break-naturally-tool [this ^ItemStack tool]
(.breakNaturally this tool)))
(reflect/extend-signatures CanBreakNaturallyEffect
"boolean breakNaturally(boolean)"
(-break-naturally-boolean [this ^Boolean effect]
(.breakNaturally this effect)))
(reflect/extend-signatures CanBreakNaturallyToolEffect
"boolean breakNaturally(org.bukkit.inventory.ItemStack,boolean)"
(-break-naturally-tool [this ^ItemStack tool ^Boolean effect]
(.breakNaturally this tool effect)))
(reflect/extend-signatures CanSpawn
"spawn(org.bukkit.Location)"
(-spawn [this loc] (.spawn this loc))
"spawnAt(org.bukkit.Location)"
(-spawn [this loc] (.spawnAt this loc)))
(reflect/extend-signatures HasDifficulty
"org.bukkit.Difficulty getDifficulty()"
(-get-difficulty [this] (.getDifficulty this))
"void setDifficulty(org.bukkit.Difficulty)"
(-set-difficulty [this d] (.setDifficulty this d)))
(reflect/extend-signatures HasPlayer
"org.bukkit.entity.Player getPlayer()"
(-player [this]
(.getPlayer this)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Interop wrappers
;;
;; Regular functions which delegate to interop protocols, but do some additional
;; type checks, coercion, or dealing with plain Clojure data along the way.
(declare ^Material material)
(declare ^clojure.lang.Keyword material-name)
(declare ^XMaterial xmaterial)
(declare ^Block get-block)
(declare ^clojure.lang.IPersistentMap block)
(declare ^World world)
(declare ^ItemStack item-stack)
(defn add
"Add multiple vector/location-like things together.
Returns a value with the same type of the first argument."
([this that]
(-add this that))
([this that & more]
(reduce -add (-add this that) more)))
;; The type hint here has the downside that for block locations we still get
;; floats, even though in that case they are ints.
(defn x ^double [o]
(cond
(vector? o)
(get o 0)
(map? o)
(:x o 0)
(satisfies? HasXYZ o)
(-x o)
(satisfies? HasLocation o)
(-x (-location o))
(satisfies? HasEntity o)
(-x (-location (-entity o)))))
(defn y ^double [o]
(cond
(vector? o)
(get o 1)
(map? o)
(:y o 0)
(satisfies? HasXYZ o)
(-y o)
(satisfies? HasLocation o)
(-y (-location o))
(satisfies? HasEntity o)
(-y (-location (-entity o)))))
(defn z ^double [o]
(cond
(vector? o)
(get o 2)
(map? o)
(:z o 0)
(satisfies? HasXYZ o)
(-z o)
(satisfies? HasLocation o)
(-z (-location o))
(satisfies? HasEntity o)
(-z (-location (-entity o)))))
(defn pitch ^double [o]
(cond
(vector? o)
(let [n (get o 3)]
(if (number? n)
n
0))
(map? o)
(:pitch o 0)
(satisfies? HasPitchYaw o)
(-pitch o)
(satisfies? HasLocation o)
(-pitch (-location o))
(satisfies? HasEntity o)
(-pitch (-location (-entity o)))))
(defn yaw ^double [o]
(cond
(vector? o)
(let [n (get o 4)]
(if (number? n)
n
0))
(map? o)
(:yaw o 0)
(satisfies? HasPitchYaw o)
(-yaw o)
(satisfies? HasLocation o)
(-yaw (-location o))
(satisfies? HasEntity o)
(-yaw (-location (-entity o)))
))
(defn location
"Get the location of the given object"
^Location [o]
(cond
(vector? o)
(let [[x y z yaw pitch world] o]
(map->Location (into {}
(remove (comp nil? val))
{:x x
:y y
:z z
:yaw (if (number? yaw) yaw 0)
:pitch (if (number? pitch) pitch 0)
:world world})))
(map? o)
(or (:location o)
(map->Location o))
(instance? Location o)
o
(satisfies? HasLocation o)
(-location o)
(satisfies? HasEntity o)
(-location (-entity o))
:else
(map->Location (into {}
(remove (comp nil? val))
{:x (x o)
:y (y o)
:z (z o)
:yaw (yaw o)
:pitch (pitch o)
:world (world o)}))))
(defn world
"Get the world associated with a given object, or look up a world by string or
UUID."
(^World [o]
(cond
(instance? World o)
o
(satisfies? HasWorld o)
(-world o)
(string? o)
(-world-by-name (server) o)
(instance? java.util.UUID o)
(-world-by-uuid (server) o)
:else
(-world (location o))))
(^World [o n]
(cond
(string? n)
(-world-by-name o n)
(instance? java.util.UUID n)
(-world-by-uuid o n))))
(defn worlds
"Get a list of all worlds on the server"
([]
(Bukkit/getWorlds))
([o]
(-worlds o)))
(defn entity
"Get an object's entity, or get entity by UUID."
[o]
(cond
(instance? Entity o)
o
(instance? UUID o)
(.getEntity (server) o)
(satisfies? HasEntity o)
(-entity o)))
(def
^{:doc "Render hiccup-like markup into a string with color and styling codes that Minecraft understand, see the [[lambdaisland.witchcraft.markup]] namespace for details."}
render-markup
markup/render)
(defn item-meta
"Get the ItemMeta for an item or compatible object, this object contains things
like the display name of the item, if it has been renamed."
^ItemMeta [o]
(cond
(instance? ItemMeta o)
o
(satisfies? HasItemMeta o)
(-item-meta o)))
(defn display-name
"Get the display-name for an item, itemstack, itemmeta, or nameable block or blockstate."
^String [o]
(cond
(satisfies? HasDisplayName o)
(-display-name o)
(satisfies? HasCustomName o)
(-get-custom-name o)
(satisfies? HasBlockState o)
(recur (-block-state o))
:else
(when-let [im (item-meta o)]
(-display-name im))))
(defn lore
"Get the lore for an item or compatible object."
[o]
(if (satisfies? HasLore o)
(-lore o)
(lore (item-meta o))))
(defn set-lore
"Set the lore on an item, itemstack, itemmeta. Takes a list (sequence) of
strings, or of markup vectors as per [[lambdaisland.witchcraft.markup/render]]."
[o lore]
(if (satisfies? HasLore o)
(-set-lore o (map #(markup/render [:reset %1]) lore))
(let [m (item-meta o)]
(-set-lore m (map #(markup/render [:reset %1]) lore))
(-set-item-meta o m))))
(defn set-display-name
"Set the display-name on an item, itemstack, itemmeta. Takes a list (sequence)
of strings, or of markup vectors as
per [[lambdaisland.witchcraft.markup/render]]."
[o name]
(cond
(satisfies? CanRenderDisplayName o)
(-render-and-set-display-name o name)
(satisfies? HasDisplayName o)
(-set-display-name o (markup/render name))
(satisfies? HasCustomName o)
(-set-custom-name o (markup/render name))
:else
(let [m (item-meta o)]
(-set-display-name m (markup/render name))
(-set-item-meta o m))))
(defn set-item-meta
"Set the ItemMeta for compatible objects, like an ItemStack. Either takes an
actual ItemMeta object, or a map with `:name` and/or `:lore` keys."
[o im]
(cond
(satisfies? HasItemMeta o)
(-set-item-meta o im)
(map? im)
;; TODO: we only handle a couple of keys here right now, we'd have to go
;; through all classes listed in
;; org.bukkit.craftbukkit.v1_18_R2.inventory.CraftMetaItem$SerializableMeta/deserialize,
;; and see what they do in their map-based constructor, then convert that to
;; individual setters, see repl-sessions.s2022-05-22 in cauldron for an
;; exploration.
(let [my-meta (item-meta o)]
(doseq [[k v] im]
(case k
:name (set-display-name my-meta v)
:lore (set-lore my-meta v)))
(set-item-meta o my-meta))))
(defn get-target-block
"Get the target block in the line of sight of the entity/player, as org.bukkit.block.Block"
(^org.bukkit.block.Block [entity]
(get-target-block entity #{:air}))
(^org.bukkit.block.Block [entity transparent]
(get-target-block entity transparent 20))
(^org.bukkit.block.Block [entity transparent max-distance]
(cond
(satisfies? HasTargetBlock entity)
(-get-target-block entity (into #{} (map material) transparent) max-distance))))
(defn target-block
"Get the target block in the line of sight of the entity/player, as a map"
[& args]
(block (apply get-target-block args)))
(util/if-class-exists org.bukkit.block.data.BlockData
(defn get-block-data
"Get the BlockData object of something"
^org.bukkit.block.data.BlockData
[b]
(cond
(instance? org.bukkit.block.data.BlockData b)
b
(satisfies? HasBlockData b)
(-get-block-data b)
(string? b)
(-parse-block-data (server) b)
:else
(-get-block-data (get-block b))))
(defn get-block-data [b]
(throw (ex-info "BlockData is not implemented on this server" {}))))
(util/if-class-exists org.bukkit.block.data.BlockData
(defn block-data
"Get the block data for the block as a map with `:material`, and other
material-specific key-values. This is kind of hacky in that we essentially
parse this out of the stringified version of the `BlockData`, but given the
immense parochialism in concrete `BlockData` subclasses we have little other
choice, and we can still reconstitute the `BlockData` by parsing it with
`Server/createBlockData`."
[b]
(let [bd (get-block-data b)
[_ _ attrs] (re-find #"^([^\[]*)\[(.*)\]"
(.getAsString bd))
result {:material (material-name bd)}]
(if attrs
(into result
(map (fn [s]
(let [[k v] (str/split s #"=")]
[(keyword k)
(cond
(= "true" v) true
(= "false" v) false
(re-find #"\d+" v) (Long/parseLong v)
(re-find #"\d+\.\d+" v) (Double/parseDouble v)
:else (keyword v))])))
(str/split attrs #","))
result)))
(defn block-data [b]
(throw (ex-info "BlockData is not implemented on this server" {}))))
(defn material
"Get the `org.bukkit.Material` for the given object.
- map: looks for a `:material` key
- vector: will look for a keyword in the fourth position
(so you can use `[x y z material]``)
- keyword: looks up the named material
- Objects that implement `getMaterial()` or `getType()`, use
the object method to get the material
- location-like things: pass on to `get-block` to get the
material at that location
"
^org.bukkit.Material [m]
(cond
(instance? Material m)
m
(satisfies? HasMaterial m)
(-material m)
(keyword? m)
(if-let [xm (xmaterial m)]
(.parseMaterial xm)
(throw (ex-info (str "Material not found: " m) {:material m
:known-materials
(count materials)})))
(map? m)
(material (:material m (location m)))
(vector? m)
(let [[_ _ _ m] m]
(when (keyword? m)
(material m)))
:else
(-material (get-block m))))
(defn mat
"Get the material name of something, as a keyword."
[m]
(cond
(keyword? m)
m
(and (map? m) (keyword? (:material m)))
(:material m)
(vector? m)
(when (and (<= 3 (count m)) (keyword? (get m 3)))
(get m 3))
(instance? XMaterial m)
(get material-names m)
:else
(when-let [xm (xmaterial m)]
(mat xm))))
(defn material-name
"Get the material name of something, as a keyword. Alias for [[mat]]."
[m]
(mat m))
(defn get-inventory
"Get the org.bukkit.inventory.Inventory for the given object/entity. Works for
players, blocks (e.g. chests), itemstacks (e.g. shulker box in inventory),
etc."
^org.bukkit.inventory.Inventory [o]
(cond
(instance? org.bukkit.inventory.Inventory o)
o
(satisfies? HasInventory o)
(-inventory o)
(satisfies? HasBlockState o)
(-inventory (-block-state o))
(satisfies? HasEntity o)
(-inventory (-entity o))
(satisfies? HasItemMeta o)
(-inventory (-block-state (-item-meta o)))))
(defn contents
"Get the contents of the inventory of something as a sequence of maps."
[o]
(let [inv (get-inventory o)]
(->> (for [^ItemStack stack (reverse inv)]
(when stack
(let [im (.getItemMeta stack)
dn (.getDisplayName im)
lore (.getLore im)
itemflags (.getItemFlags im)
localized (.getLocalizedName im)
enchants (.getEnchants im)]
(cond-> (into {:material (mat stack)
:amount (.getAmount stack)}
(map (juxt (comp keyword key) val))
;; Leverage ConfigurationSerializable to get extra
;; keys, but we don't currently deserialize these
(.serialize im))
(not= "" dn) (assoc :display-name dn)
(not= "" localized) (assoc :localized-display-name localized)
(seq lore) (assoc :lore (seq lore))
(seq itemflags) (assoc :item-flags itemflags)
(seq enchants) (assoc :enchants
(into {}
(map (fn [[^Enchantment k v]]
[(enchantment-key k) v]))
enchants))))))
(drop-while nil?)
reverse
vec)))
(defn inventory-type
"Get the type of an inventory object, or of something that has an
inventory (like a player or chest entity) as a keyword."
[i]
(get
(set/map-invert inventory-types)
(.getType (get-inventory i))))
(defn inventory
"Get a Clojure/EDN representation of an inventory (or of something that has an
inventory). Has `:type` and `:contents` keys, and `:size` for chest type
inventories (others have a fixed size)."
[i]
(let [i (get-inventory i)
type (inventory-type i)
#_#_title (.getName i)]
(cond->
{:type type
:contents (contents i)}
(= :chest type)
(assoc :size (.getSize i))
#_#_title
(assoc :title title))))
(defn set-contents
"Set inventory contents on an inventory or something that has an inventory."
[inv items]
(.setContents (get-inventory inv)
(into-array ItemStack (map item-stack items))))
(defn make-inventory
"Make a new Bukkit inventory object, with either `:type` (keyword) or
`:size` (must be multiple of 9), and optional `:owner` and/or `:title`."
[{:keys [^org.bukkit.inventory.InventoryHolder owner type size ^String title contents]
:or {size 27}}]
(let [inv
(cond
(and type title)
(org.bukkit.Bukkit/createInventory owner ^org.bukkit.event.inventory.InventoryType (get inventory-types type) title)
type
(org.bukkit.Bukkit/createInventory owner ^org.bukkit.event.inventory.InventoryType (get inventory-types type))
title
(org.bukkit.Bukkit/createInventory owner ^long size title)
:else
(org.bukkit.Bukkit/createInventory owner ^long size)