├── .gitignore
├── LICENSE
├── README.md
├── art
├── Banner.png
└── Banner.xcf
├── build.gradle
├── example-scripts
├── complex
│ └── libs
│ │ ├── basic-lib.ktskript
│ │ └── script-using-lib.ktskript
└── simple
│ ├── block-break-drop-replacements.ktskript
│ ├── buy-command.ktskript
│ ├── cow-spawner.ktskript
│ ├── damaging-biomes.ktskript
│ ├── deadly-water.ktskript
│ ├── diamond-troll.ktskript
│ ├── empty-server-commands.ktskript
│ ├── gold-money.ktskript
│ ├── join-commands.ktskript
│ ├── messages.ktskript
│ ├── roleplay-chat.ktskript
│ ├── roleplay-chat2.ktskript
│ ├── scheduled-broadcast.ktskript
│ ├── sponge-trampoline.ktskript
│ ├── staff-custom-join-message.ktskript
│ ├── tax.ktskript
│ ├── teleport-to-nether-event.ktskript
│ ├── track-dirt-blocks.ktskript
│ └── website-command.ktskript
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── lib-scripts
├── forge-events
│ ├── lib
│ │ ├── forge-events-lib.imports
│ │ └── forge-events-lib.ktskript
│ └── usage
│ │ ├── forge-events-script.imports
│ │ └── forge-events-script.ktskript
└── pixelmon-events
│ ├── README.md
│ ├── lib
│ ├── pixelmon-events-lib.imports
│ └── pixelmon-events-lib.ktskript
│ └── usage
│ ├── pixelmon-events-script.imports
│ └── pixelmon-events-script.ktskript
├── libs
└── bstats-sponge-1.2.jar
├── settings.gradle
└── src
└── main
├── kotlin
└── de
│ └── randombyte
│ └── ktskript
│ ├── FolderWatcher.kt
│ ├── KtSkriptPlugin.kt
│ ├── Texts.kt
│ ├── config
│ ├── ConfigAccessors.kt
│ ├── GeneralConfig.kt
│ └── kosp
│ │ ├── AbstractConfigAccessors.kt
│ │ ├── ConfigHolder.kt
│ │ └── ConfigManager.kt
│ ├── script
│ ├── Script.kt
│ ├── ScriptEngineFactory.kt
│ ├── ScriptsManager.kt
│ ├── UnloadScriptsEvent.kt
│ └── Utils.kt
│ └── utils
│ ├── BigDecimals.kt
│ ├── BlockSnapshots.kt
│ ├── Carriers.kt
│ ├── Classes.kt
│ ├── Configs.kt
│ ├── Data.kt
│ ├── Dates.kt
│ ├── Durations.kt
│ ├── Economy.kt
│ ├── Equipables.kt
│ ├── Humanoids.kt
│ ├── Locations.kt
│ ├── Logging.kt
│ ├── Managers.kt
│ ├── Optionals.kt
│ ├── Random.kt
│ ├── Scheduler.kt
│ ├── Services.kt
│ ├── Strings.kt
│ ├── Texts.kt
│ ├── Utils.kt
│ ├── Uuids.kt
│ ├── Vectors.kt
│ ├── Viewers.kt
│ ├── commands
│ ├── CommandElements.kt
│ ├── CommandSources.kt
│ └── Commands.kt
│ ├── events
│ ├── AffectedObjectsEvents.kt
│ ├── Events.kt
│ ├── General.kt
│ ├── InteractBlockEvents.kt
│ └── TargetEntityEvents.kt
│ ├── particles
│ └── Builders.kt
│ └── serializers
│ ├── SimpleDateTypeSerializer.kt
│ └── SimpleDurationTypeSerializer.kt
└── resources
└── assets
└── kt-skript
└── default.imports
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | .gradle/
3 | build/
4 | run/
5 | *.iml
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | entity-cash
294 | Copyright (C) 2017 Sven Rahn
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # KtSkript
2 |
3 | ## [Read the wiki](https://github.com/randombyte-developer/kt-skript/wiki)
4 |
--------------------------------------------------------------------------------
/art/Banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/randombyte-developer/kt-skript/671cce2d10114506d772947f3ceb5a2d0bdb88bc/art/Banner.png
--------------------------------------------------------------------------------
/art/Banner.xcf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/randombyte-developer/kt-skript/671cce2d10114506d772947f3ceb5a2d0bdb88bc/art/Banner.xcf
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id "org.jetbrains.kotlin.jvm" version "1.2.50"
3 | id "org.jetbrains.kotlin.kapt" version "1.2.50"
4 | id "com.github.johnrengelman.shadow" version "2.0.4"
5 | }
6 |
7 | group "de.randombyte"
8 | version "1.4.0"
9 |
10 | repositories {
11 | jcenter()
12 | maven { url "https://repo.spongepowered.org/maven/" }
13 | // the repo seems to be offline, instead use a locally compiled build
14 | // maven { url "http://repo.bstats.org/content/repositories/releases" }
15 | flatDir { dirs "libs" }
16 | maven { url "https://jitpack.io" }
17 | }
18 |
19 | configurations {
20 | compile.extendsFrom shadow
21 | compile.extendsFrom kapt
22 | }
23 |
24 | def kotlinVersion = "1.2.50"
25 |
26 | dependencies {
27 | shadow("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion")
28 | shadow("org.jetbrains.kotlin:kotlin-compiler-embeddable:$kotlinVersion")
29 | shadow("org.jetbrains.kotlin:kotlin-script-util:$kotlinVersion") { transitive = false}
30 | shadow("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
31 | shadow("io.github.lukehutch:fast-classpath-scanner:2.9.5")
32 | kapt "org.spongepowered:spongeapi:7.1.0"
33 | compile "com.github.randombyte-developer:PlaceholderAPI:v4.5.1"
34 | compile "com.github.randombyte-developer:byte-items:v2.2.6"
35 | shadow name: "bstats-sponge-1.2"
36 | }
37 |
38 | jar.enabled = false
39 |
40 | shadowJar {
41 | configurations = [project.configurations.shadow]
42 |
43 | def packages = [
44 | "io.github.lukehutch.fastclasspathscanner",
45 | "javaslang",
46 | "net.jpountz", "net.rubygrapefruit",
47 | "one.util",
48 | "org.bstats", "org.intellij", "org.iq80",
49 | "org.jetbrains.ide", "org.jetbrains.org.objectweb.asm"
50 | ]
51 |
52 | packages.forEach {
53 | relocate it, "de.randombyte.ktskript.shaded.$it"
54 | }
55 |
56 | classifier = null // Remove "-all" suffix from output file name
57 | }
58 | build.dependsOn shadowJar
59 |
60 | compileKotlin {
61 | kotlinOptions {
62 | jvmTarget = "1.8"
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/example-scripts/complex/libs/basic-lib.ktskript:
--------------------------------------------------------------------------------
1 | mapOf>(
2 | "kickAllPlayers" to { reason: Text ->
3 | Server.onlinePlayers.forEach { player ->
4 | player.kick(reason)
5 | }
6 | }
7 | )
--------------------------------------------------------------------------------
/example-scripts/complex/libs/script-using-lib.ktskript:
--------------------------------------------------------------------------------
1 | val libPath = script.path.parent.resolve("basic-lib.ktskript")
2 | val scripts = script.compile(libPath)
3 | if ("basic-lib" !in scripts.keys) throw RuntimeException("Lib not found!")
4 |
5 | val lib = scripts["basic-lib"]!!.compiledScript.eval() as Map>
6 | val kickAllPlayers: (reason: Text) -> Unit = lib["kickAllPlayers"]!! as Function1
7 |
8 | // Might sometimes be useful...
9 | registerCommand("clearlag") {
10 | action {
11 | kickAllPlayers("Clearing lag...".t)
12 | }
13 | }
--------------------------------------------------------------------------------
/example-scripts/simple/block-break-drop-replacements.ktskript:
--------------------------------------------------------------------------------
1 | val replacements = mapOf(
2 |
3 | "minecraft:log" to "minecraft:diamond",
4 | "minecraft:stone" to "minecraft:gold_ingot"
5 |
6 | ).mapValues { (_, itemTypeId) ->
7 | ItemStack.of(Sponge.getRegistry().getType(ItemType::class.java, itemTypeId).get(), 1).createSnapshot()
8 | }
9 |
10 | registerListener {
11 | entities
12 | .filter { it is Item }
13 | .forEach { item ->
14 | if (context.get(EventContextKeys.SPAWN_TYPE).orNull() == SpawnTypes.DROPPED_ITEM) {
15 | val brokenBlockSnapshot = context.get(EventContextKeys.BLOCK_HIT).orNull() ?: return@forEach
16 | val replacement = replacements[brokenBlockSnapshot.state.type.id] ?: return@forEach
17 | item.tryOffer(Keys.REPRESENTED_ITEM, replacement)
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/example-scripts/simple/buy-command.ktskript:
--------------------------------------------------------------------------------
1 | val offers: Map = mapOf(
2 | ItemTypes.SADDLE to 30,
3 | ItemTypes.SHIELD to 10,
4 | ItemTypes.TNT to 5
5 | ).mapValues { (_, costs) -> costs.toBigDecimal() }
6 |
7 | registerCommand("buy") {
8 | arguments(
9 | catalogedElement("item"),
10 | integer("amount")
11 | )
12 | action(onlyPlayers = true) {
13 | val itemType = argument("item")
14 | val amount = argument("amount")
15 |
16 | if (amount < 1) {
17 | commandError("Invalid 'amount'!".t)
18 | }
19 |
20 | if (itemType !in offers.keys) {
21 | commandError("Can't buy this item!".t)
22 | }
23 |
24 | val acc = player.economyAccount
25 | val costs = offers[itemType]!! * amount
26 |
27 | if (acc.balance < costs) {
28 | commandError("You don't have enough money to buy that!".t)
29 | }
30 |
31 | acc.balance -= costs
32 |
33 | val itemStack = ItemStack.of(itemType, amount)
34 | player.give(itemStack)
35 | player.sendMessage("You bought $amount x ${itemType.id}!".t.green())
36 | }
37 | }
--------------------------------------------------------------------------------
/example-scripts/simple/cow-spawner.ktskript:
--------------------------------------------------------------------------------
1 | onBlockRightClick {
2 | if (causedByPlayer && causingPlayer.hasPermission("cowspawn") && !clickedInAir && causingPlayer.isSneaking) {
3 | val clickedBlock = targetBlock.blockLocation
4 | val spawnLocation = clickedBlock.add(v3(0, 1, 0))
5 | val cow = spawnLocation.createEntity(EntityTypes.COW)
6 |
7 | spawnLocation.world.spawnEntity(cow)
8 | causingPlayer.sendMessage("&2Cow spawned!".t)
9 | }
10 | }
--------------------------------------------------------------------------------
/example-scripts/simple/damaging-biomes.ktskript:
--------------------------------------------------------------------------------
1 | val damagingBiomes = listOf(BiomeTypes.TAIGA, BiomeTypes.TAIGA_HILLS)
2 |
3 | val damageSource = DamageSource.builder()
4 | .type(DamageTypes.CUSTOM)
5 | .build()
6 |
7 | Task.builder()
8 | .intervalTicks(20 * 10)
9 | .execute { task ->
10 | Server.onlinePlayers
11 | .filter { player ->
12 | player.location.hasBiome() && player.location.biome in damagingBiomes
13 | }
14 | .forEach { player ->
15 | player.damage(1.0, damageSource)
16 | }
17 | }
18 | .submit(KtSkript)
--------------------------------------------------------------------------------
/example-scripts/simple/deadly-water.ktskript:
--------------------------------------------------------------------------------
1 | val damageSource = DamageSource.builder()
2 | .type(DamageTypes.MAGIC)
3 | .build()
4 |
5 | Task.builder()
6 | .intervalTicks(10)
7 | .execute { ->
8 | Server.onlinePlayers
9 | .forEach { player ->
10 | val playerBlockType = player.location.block.type
11 | if (playerBlockType == BlockTypes.FLOWING_WATER || playerBlockType == BlockTypes.WATER) {
12 | player.damage(1, damageSource) // 1 = half a heart
13 | }
14 | }
15 | }
16 | .submit(KtSkript)
--------------------------------------------------------------------------------
/example-scripts/simple/diamond-troll.ktskript:
--------------------------------------------------------------------------------
1 | onBlockBreak {
2 | if (causedByPlayer) {
3 | blockChanges.forEach { blockChange ->
4 | if (blockChange.original.type == BlockTypes.DIAMOND_ORE) {
5 | if (!causingPlayer.isSneaking) {
6 | cancelEvent()
7 | causingPlayer.sendMessage("&cYou can't mine diamonds, hehe".t)
8 | }
9 | }
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/example-scripts/simple/empty-server-commands.ktskript:
--------------------------------------------------------------------------------
1 | var delayTask: Task? = null
2 |
3 | onPlayerLeave {
4 | // the currently leaving player is at the time of this check technically still on the server
5 | if (Server.onlinePlayers.size == 1) {
6 | delayTask = delay("5m") {
7 | Server.console.executeCommand("say Yep, this server is empty!")
8 | }
9 | }
10 | }
11 |
12 | onPlayerJoin {
13 | delayTask?.cancel()
14 | }
--------------------------------------------------------------------------------
/example-scripts/simple/gold-money.ktskript:
--------------------------------------------------------------------------------
1 | onBlockBreak {
2 | if (causedByPlayer) {
3 | blockChanges.forEach { blockChange ->
4 | if (blockChange.original.type == BlockTypes.GOLD_ORE) {
5 | val moneyInBlock = randomBoolean(chance = 0.05)
6 | if (moneyInBlock) {
7 |
8 | val moneyAmount = randomInt(start = 300, end = 500)
9 |
10 | causingPlayer.economyAccount.balance += moneyAmount.toBigDecimal()
11 |
12 | causingPlayer.sendMessage("You found $moneyAmount coins!".green())
13 | }
14 | }
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/example-scripts/simple/join-commands.ktskript:
--------------------------------------------------------------------------------
1 | onPlayerJoin {
2 | val commands = listOf(
3 | "nucleus:warp ${player.name} main-spawn",
4 | "title times 5 30 5", // read the minecraft wiki to learn more about this command
5 | """title ${player.name} title {"text": "Welcome!", "color": "blue"}"""
6 | )
7 |
8 | commands.forEach { command ->
9 | Server.console.executeCommand(command)
10 | }
11 | }
--------------------------------------------------------------------------------
/example-scripts/simple/messages.ktskript:
--------------------------------------------------------------------------------
1 | onPlayerJoin {
2 | setMessage("&2${player.name} &rjust joined the server!".t)
3 | }
4 |
5 | onPlayerLeave {
6 | setMessage(player.name.darkRed() + " left the server!".white())
7 | }
8 |
9 | onPlayerDeath {
10 | setMessage("${player.name} died!".red())
11 | }
12 |
13 | registerListener {
14 | setMessage("${player.name} just got the achievement ".t + advancement.toText() + ".".t)
15 | }
--------------------------------------------------------------------------------
/example-scripts/simple/roleplay-chat.ktskript:
--------------------------------------------------------------------------------
1 | /*
2 | Commands:
3 | - /ch local - Sets your chat to local
4 | - /ch global - Sets your chat to global
5 | - /whisper
6 | - /shout
7 |
8 | By default your channel is local. Every chat message you send is either directed through local or global chat.
9 | The distances for the modes are configurable below.
10 | */
11 |
12 | object Config {
13 | const val LOCAL_CHAT_DISTANCE = 10.0
14 | const val WHISPER_CHAT_DISTANCE = 1.0
15 | const val SHOUT_CHAT_DISTANCE = 20.0
16 | }
17 |
18 | enum class ChatMode {
19 | LOCAL, GLOBAL
20 | }
21 |
22 | val chatModes = mutableMapOf()
23 |
24 | fun Iterable.send(text: Text) = forEach { it.sendMessage(text) }
25 |
26 | fun rangeChat(sender: Player, range: Double, msg: Text) {
27 | val world = sender.location.extent
28 | val playerPos = sender.location.position
29 | val playersInRange = world
30 | .getNearbyEntities(playerPos, range)
31 | .mapNotNull { it as? Player }
32 | playersInRange.send(msg)
33 | }
34 |
35 | registerCommand("ch") {
36 | child("global") {
37 | action(onlyPlayers = true) {
38 | chatModes += player.uniqueId to ChatMode.GLOBAL
39 | player.sendMessage("&2Set chat mode to global!".t)
40 | }
41 | }
42 |
43 | child("local") {
44 | action(onlyPlayers = true) {
45 | chatModes += player.uniqueId to ChatMode.LOCAL
46 | player.sendMessage("&2Set chat mode to local!".t)
47 | }
48 | }
49 | }
50 |
51 | registerCommand("whisper") {
52 | arguments(remainingStrings("msg"))
53 | action(onlyPlayers = true) {
54 | val msg = "&7[&6${player.name} &7whispers] ".t + argument("msg").white()
55 | rangeChat(sender = player, range = Config.WHISPER_CHAT_DISTANCE, msg = msg)
56 | }
57 | }
58 |
59 | registerCommand("shout") {
60 | arguments(remainingStrings("msg"))
61 | action(onlyPlayers = true) {
62 | val msg = "&7[&6${player.name} &7shouts] ".t + argument("msg").white()
63 | rangeChat(sender = player, range = Config.SHOUT_CHAT_DISTANCE, msg = msg)
64 | }
65 | }
66 |
67 | registerListener {
68 | if (causedByPlayer) {
69 | val currentChatMode = chatModes[causingPlayer.uniqueId] ?: ChatMode.LOCAL
70 |
71 | when(currentChatMode) {
72 | ChatMode.GLOBAL -> {
73 | cancelEvent()
74 | val fullMsg = "&7[&6${causingPlayer.name} &7in global chat] ".t + rawMessage.white()
75 | causingPlayer.location.extent.players.send(fullMsg)
76 | }
77 | ChatMode.LOCAL -> {
78 | cancelEvent()
79 | val fullMsg = "&7[&6${causingPlayer.name} &7in local chat] ".t + rawMessage.white()
80 | rangeChat(sender = causingPlayer, range = Config.LOCAL_CHAT_DISTANCE, msg = fullMsg)
81 | }
82 | }
83 | }
84 | }
--------------------------------------------------------------------------------
/example-scripts/simple/roleplay-chat2.ktskript:
--------------------------------------------------------------------------------
1 | val SHOUTING_PREFIX = "!"
2 |
3 | registerListener {
4 |
5 | val isShouting = rawMessage.toPlain().startsWith(SHOUTING_PREFIX)
6 |
7 | val range = if (isShouting) 100 else 50
8 | val playerLoc = causingPlayer.location
9 | val targetedPlayers = playerLoc.extent
10 | .getNearbyEntities(playerLoc.position, range.toDouble())
11 | .mapNotNull { it as? Player }
12 | setChannel(MessageChannel.fixed(targetedPlayers))
13 |
14 | formatter.setBody(rawMessage.toPlain().removePrefix(SHOUTING_PREFIX).toText())
15 |
16 | val prefix = if (isShouting) "&7[&aShout&7] ".t else "&7[&aLocal&7] ".t
17 | formatter.setHeader(prefix + formatter.header.toText())
18 | }
--------------------------------------------------------------------------------
/example-scripts/simple/scheduled-broadcast.ktskript:
--------------------------------------------------------------------------------
1 | onEvery("5m") {
2 | val message = "&4Please vote for this server here: ".t +
3 | "&e[VOTE]".t.action(TextActions.openUrl(URL("https://www.example.com")))
4 | message.broadcast()
5 | }
--------------------------------------------------------------------------------
/example-scripts/simple/sponge-trampoline.ktskript:
--------------------------------------------------------------------------------
1 | onPlayerMove {
2 | val groundBlock = toTransform.location.add(v3(0, -1, 0))
3 | if (groundBlock.block.type == BlockTypes.SPONGE) {
4 | player.velocity = v3(0.0, 0.5, 0.0)
5 | }
6 | }
--------------------------------------------------------------------------------
/example-scripts/simple/staff-custom-join-message.ktskript:
--------------------------------------------------------------------------------
1 | val staffMembers = listOf(
2 | "KitCrafty",
3 | "Notch"
4 | )
5 |
6 | onPlayerJoin {
7 | if (player.name in staffMembers) {
8 | setMessage("&2The legendary ${player.name} has joined the server!".t)
9 | }
10 | }
--------------------------------------------------------------------------------
/example-scripts/simple/tax.ktskript:
--------------------------------------------------------------------------------
1 | val taxPercentage = 0.19
2 |
3 | onEvery("1h") {
4 | val account = EconomyService.getAccount("bank-account")
5 |
6 | // calculate tax
7 | val tax = account.balance * taxPercentage
8 | // withdraw tax
9 | account.balance -= tax
10 | // deposit tax somewhere else
11 | EconomyService.getAccount("some-other-account").balance += tax
12 |
13 | "${tax.toInt()} coins just got moved somewhere else!".t.broadcast()
14 | }
--------------------------------------------------------------------------------
/example-scripts/simple/teleport-to-nether-event.ktskript:
--------------------------------------------------------------------------------
1 | registerListener {
2 | val entity = targetEntity
3 | if (entity is Player) {
4 | val toWorld = toTransform.extent
5 | if (toWorld.dimension.type == DimensionTypes.NETHER) {
6 | entity.sendMessage("You were sent to the Nether!".t)
7 | }
8 | }
9 | }
--------------------------------------------------------------------------------
/example-scripts/simple/track-dirt-blocks.ktskript:
--------------------------------------------------------------------------------
1 | val configLoader = script.path.parent.resolve("tracking-data.conf").toConfigurationLoader()
2 |
3 | val rootNode = configLoader.load()
4 | val dirtBlocksNode = rootNode.getNode("dirt")
5 |
6 | onBlockBreak {
7 | if (causedByPlayer) {
8 | blockChanges.forEach { blockChange ->
9 | if (blockChange.original.type == BlockTypes.DIRT) {
10 | val alreadyMined = dirtBlocksNode.getInt(0) // 0 is the default value if the config was empty before
11 | dirtBlocksNode.setValue(alreadyMined + 1)
12 | }
13 | }
14 | }
15 | }
16 |
17 | onScriptsUnload {
18 | if (script.id in scripts) { // yep, we are being unloaded
19 | configLoader.save(rootNode)
20 | }
21 | }
22 |
23 | registerCommand("dirtblocks") {
24 | action {
25 | val amount = dirtBlocksNode.getInt(0)
26 | commandSource.sendMessage("$amount dirt blocks mined in total on this server!".t)
27 | }
28 | }
--------------------------------------------------------------------------------
/example-scripts/simple/website-command.ktskript:
--------------------------------------------------------------------------------
1 | registerCommand("website") {
2 | action(onlyPlayers = true) {
3 | val text = "&2This is a link to our website: ".t +
4 | "&e[Click here]".t.underline().action(TextActions.openUrl(URL("https://www.example.com")))
5 | text.sendTo(player)
6 | }
7 | }
8 |
9 | registerCommand("vote") {
10 | action(onlyPlayers = true) {
11 | val text = "Vote-Link: ".t +
12 | "&b[Vote]".t.underline().action(TextActions.openUrl(URL("https://www.example.com")))
13 | text.sendTo(player)
14 | }
15 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/randombyte-developer/kt-skript/671cce2d10114506d772947f3ceb5a2d0bdb88bc/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Mar 09 22:15:47 CET 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn ( ) {
37 | echo "$*"
38 | }
39 |
40 | die ( ) {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save ( ) {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/lib-scripts/forge-events/lib/forge-events-lib.imports:
--------------------------------------------------------------------------------
1 | kotlin.reflect
2 |
3 | net.minecraftforge.common
4 | net.minecraftforge.event
5 | net.minecraftforge.fml.common.eventhandler
6 |
--------------------------------------------------------------------------------
/lib-scripts/forge-events/lib/forge-events-lib.ktskript:
--------------------------------------------------------------------------------
1 | typealias ForgeEvent = net.minecraftforge.fml.common.eventhandler.Event
2 |
3 | val eventListeners = ForgeEvent::class.java.getDeclaredField("listeners").apply { isAccessible = true }.get(null) as ListenerList
4 | val busId = EventBus::class.java.getDeclaredField("busID").apply { isAccessible = true }.get(MinecraftForge.EVENT_BUS) as Int
5 |
6 | fun registerForgeListener(
7 | eventClass: Class,
8 | priority: EventPriority = EventPriority.NORMAL,
9 | filterCanceled: Tristate = Tristate.FALSE,
10 | listener: (T) -> Unit
11 | ): IEventListener {
12 | val iEventListener = IEventListener { event ->
13 |
14 | val passedCancellationFilter = when {
15 | !event.isCancelable -> true
16 | filterCanceled == Tristate.UNDEFINED -> true
17 | filterCanceled == Tristate.FALSE && !event.isCanceled -> true
18 | filterCanceled == Tristate.TRUE && event.isCanceled -> true
19 | else -> false
20 | }
21 |
22 | if (passedCancellationFilter) {
23 | val passedEventClassFilter = when {
24 | eventClass.isAssignableFrom(event::class.java) -> true
25 | else -> false
26 | }
27 |
28 | if (passedEventClassFilter) {
29 | listener.invoke(event as T)
30 | }
31 | }
32 | }
33 |
34 | eventListeners.register(busId, priority, iEventListener)
35 | return iEventListener
36 | }
37 |
38 | // without generics, because lambdas don't support them; generic can be "re-enabled" through a function on the library-caller side
39 | val registerForgeListenerLambda = { eventClass: Class, priority: EventPriority, filterCanceled: Tristate, listener: (ForgeEvent) -> Unit ->
40 | registerForgeListener(eventClass, priority, filterCanceled, listener)
41 | }
42 |
43 | val libFunctions = mapOf(
44 | "registerForgeListener" to registerForgeListenerLambda,
45 | "unregisterForgeListener" to { listener: IEventListener ->
46 | eventListeners.unregister(busId, listener)
47 | }
48 | )
49 |
50 | libFunctions
51 |
--------------------------------------------------------------------------------
/lib-scripts/forge-events/usage/forge-events-script.imports:
--------------------------------------------------------------------------------
1 | net.minecraftforge.event
2 | net.minecraftforge.fml.common.eventhandler
3 |
--------------------------------------------------------------------------------
/lib-scripts/forge-events/usage/forge-events-script.ktskript:
--------------------------------------------------------------------------------
1 | // =====================
2 | // ===== lib setup =====
3 | // =====================
4 |
5 | typealias ForgeEvent = net.minecraftforge.fml.common.eventhandler.Event
6 |
7 | // load lib
8 | val forgeEventsLibId = "forge-events-lib"
9 | val forgeEventsLibPath = script.path.parent.resolve(forgeEventsLibId + ".ktskript")
10 | val scripts = script.compile(forgeEventsLibPath)
11 | val forgeEventsLibScript = scripts[forgeEventsLibId] ?: throw RuntimeException("$forgeEventsLibId not found!")
12 |
13 | val forgeEventsLibFunctions = forgeEventsLibScript.compiledScript.eval() as Map>
14 |
15 | // extract the functions into lambdas
16 | val registerForgeListenerLambda: (eventClass: Class, priority: EventPriority, filterCanceled: Tristate, listener: Function1) -> IEventListener =
17 | forgeEventsLibFunctions["registerForgeListener"]!! as Function4, EventPriority, Tristate, Function1, IEventListener>
18 |
19 | val unregisterForgeListener: (listener: IEventListener) -> Unit =
20 | forgeEventsLibFunctions["unregisterForgeListener"]!! as Function1
21 |
22 | // wrap this specific lambda into a function to get generics, this is not needed but nice for compile time type safety
23 | inline fun registerForgeListener(
24 | priority: EventPriority = EventPriority.NORMAL,
25 | isCancelled: Tristate = Tristate.FALSE,
26 | noinline executor: T.() -> Unit
27 | ): IEventListener = registerForgeListenerLambda(T::class.java, priority, isCancelled, executor as Function1)
28 |
29 | // =======================================
30 | // ===== actual script starting here =====
31 | // =======================================
32 |
33 | val listener = registerForgeListener {
34 | println("Event called!")
35 | }
36 |
37 | onScriptsUnload {
38 | if (script.id in scripts) {
39 | unregisterForgeListener(listener)
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/lib-scripts/pixelmon-events/README.md:
--------------------------------------------------------------------------------
1 | # Dependencies
2 | * Pixelmon Reforged - 8.0.3+
3 |
--------------------------------------------------------------------------------
/lib-scripts/pixelmon-events/lib/pixelmon-events-lib.imports:
--------------------------------------------------------------------------------
1 | kotlin.reflect
2 |
3 | net.minecraftforge.common
4 | net.minecraftforge.event
5 | net.minecraftforge.fml.common.eventhandler
6 |
7 | com.pixelmonmod.pixelmon.Pixelmon
--------------------------------------------------------------------------------
/lib-scripts/pixelmon-events/lib/pixelmon-events-lib.ktskript:
--------------------------------------------------------------------------------
1 | typealias ForgeEvent = net.minecraftforge.fml.common.eventhandler.Event
2 |
3 | val eventListeners = ForgeEvent::class.java.getDeclaredField("listeners").apply { isAccessible = true }.get(null) as ListenerList
4 |
5 | val pixelmonBusId = EventBus::class.java.getDeclaredField("busID").apply { isAccessible = true }.get(Pixelmon.EVENT_BUS) as Int
6 |
7 | fun registerPixelmonListener(
8 | eventClass: Class,
9 | priority: EventPriority = EventPriority.NORMAL,
10 | filterCanceled: Tristate = Tristate.FALSE,
11 | listener: (T) -> Unit
12 | ): IEventListener {
13 | val iEventListener = IEventListener { event ->
14 |
15 | val passedCancellationFilter = when {
16 | !event.isCancelable -> true
17 | filterCanceled == Tristate.UNDEFINED -> true
18 | filterCanceled == Tristate.FALSE && !event.isCanceled -> true
19 | filterCanceled == Tristate.TRUE && event.isCanceled -> true
20 | else -> false
21 | }
22 |
23 | if (passedCancellationFilter) {
24 | val passedEventClassFilter = when {
25 | eventClass.isAssignableFrom(event::class.java) -> true
26 | else -> false
27 | }
28 |
29 | if (passedEventClassFilter) {
30 | listener.invoke(event as T)
31 | }
32 | }
33 | }
34 |
35 | eventListeners.register(pixelmonBusId, priority, iEventListener)
36 | return iEventListener
37 | }
38 |
39 | // without generics, because lambdas don't support them; generic can be "re-enabled" through a function on the library-caller side
40 | val registerPixelmonListenerLambda = { eventClass: Class, priority: EventPriority, filterCanceled: Tristate, listener: (ForgeEvent) -> Unit ->
41 | registerPixelmonListener(eventClass, priority, filterCanceled, listener)
42 | }
43 |
44 | val libFunctions = mapOf(
45 | "registerPixelmonListener" to registerPixelmonListenerLambda,
46 | "unregisterPixelmonListener" to { listener: IEventListener ->
47 | eventListeners.unregister(pixelmonBusId, listener)
48 | }
49 | )
50 |
51 | libFunctions
52 |
--------------------------------------------------------------------------------
/lib-scripts/pixelmon-events/usage/pixelmon-events-script.imports:
--------------------------------------------------------------------------------
1 | net.minecraftforge.event
2 | net.minecraftforge.fml.common.eventhandler
3 |
4 | com.pixelmonmod.pixelmon.api.events.spawning.LegendarySpawnEvent
--------------------------------------------------------------------------------
/lib-scripts/pixelmon-events/usage/pixelmon-events-script.ktskript:
--------------------------------------------------------------------------------
1 | /*===============================================*
2 | * *
3 | * Configure Pixelmon Event library *
4 | * *
5 | *===============================================*/
6 |
7 | // Define alias for Forge Event for convinience
8 | typealias ForgeEvent = net.minecraftforge.fml.common.eventhandler.Event
9 |
10 | // load lib
11 | val pixelmonEventsLibId = "pixelmon-events-lib"
12 | val pixelmonEventsLibPath = script.path.parent.resolve(pixelmonEventsLibId + ".ktskript")
13 | val scripts = script.compile(pixelmonEventsLibPath)
14 | val pixelmonEventsLibScript = scripts[pixelmonEventsLibId] ?: throw RuntimeException("$pixelmonEventsLibId not found!")
15 |
16 | val pixelmonEventsLibFunctions = pixelmonEventsLibScript.compiledScript.eval() as Map>
17 |
18 | // extract the functions into lambdas
19 | val registerPixelmonListenerLambda: (eventClass: Class, priority: EventPriority, filterCanceled: Tristate, listener: Function1) -> IEventListener =
20 | pixelmonEventsLibFunctions["registerPixelmonListener"]!! as Function4, EventPriority, Tristate, Function1, IEventListener>
21 |
22 | val unregisterPixelmonEvent: (listener: IEventListener) -> Unit =
23 | pixelmonEventsLibFunctions["unregisterPixelmonListener"]!! as Function1
24 |
25 | // wrap this specific lambda into a function to get generics, this is not needed but nice for compile time type safety
26 | inline fun registerPixelmonEvent(
27 | priority: EventPriority = EventPriority.NORMAL,
28 | isCancelled: Tristate = Tristate.FALSE,
29 | noinline executor: T.() -> Unit
30 | ): IEventListener = registerPixelmonListenerLambda(T::class.java, priority, isCancelled, executor as Function1)
31 |
32 |
33 | // =============== Script starts here =============== //
34 |
35 | var listener = registerPixelmonEvent {
36 | Server.console.executeCommand("say ${this.getLegendary()} has spawned")
37 | }
38 |
39 | onScriptsUnload {
40 | if (script.id in scripts) {
41 | unregisterPixelmonEvent(listener)
42 | }
43 | }
--------------------------------------------------------------------------------
/libs/bstats-sponge-1.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/randombyte-developer/kt-skript/671cce2d10114506d772947f3ceb5a2d0bdb88bc/libs/bstats-sponge-1.2.jar
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'kt-skript'
2 |
3 |
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/FolderWatcher.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript
2 |
3 | import de.randombyte.ktskript.utils.KtSkript
4 | import org.spongepowered.api.scheduler.Task
5 | import java.nio.file.FileSystems
6 | import java.nio.file.Path
7 | import java.nio.file.StandardWatchEventKinds.*
8 | import java.nio.file.WatchService
9 | import java.time.Duration
10 | import java.util.concurrent.TimeUnit
11 |
12 | class FolderWatcher(val path: Path, val interval: Duration, val onChanges: () -> Unit) {
13 |
14 | companion object {
15 | const val SCRIPTS_FOLDER_WATCHER_TASK_NAME = "kt-skript-scripts-folder-watcher-task"
16 | }
17 |
18 | private lateinit var task: Task
19 | private lateinit var watchService: WatchService
20 |
21 | init {
22 | setupTask()
23 | }
24 |
25 | private fun setupTask () {
26 | watchService = FileSystems.getDefault().newWatchService()
27 | path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)
28 |
29 | task = Task.builder()
30 | .name(SCRIPTS_FOLDER_WATCHER_TASK_NAME)
31 | .interval(interval.toMillis(), TimeUnit.MILLISECONDS)
32 | .execute { ->
33 | checkForChanges()
34 | }
35 | .submit(KtSkript)
36 | }
37 |
38 | private fun checkForChanges() {
39 | val watchKey = watchService.poll() ?: return
40 | if (watchKey.pollEvents().isNotEmpty()) {
41 | try {
42 | onChanges()
43 | } catch (throwable: Throwable) {
44 | throwable.printStackTrace()
45 | }
46 | }
47 |
48 | watchKey.reset()
49 | }
50 |
51 | fun stop() {
52 | task.cancel()
53 | }
54 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/KtSkriptPlugin.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript
2 |
3 | import com.google.inject.Inject
4 | import de.randombyte.ktskript.KtSkriptPlugin.Companion.AUTHOR
5 | import de.randombyte.ktskript.KtSkriptPlugin.Companion.ID
6 | import de.randombyte.ktskript.KtSkriptPlugin.Companion.NAME
7 | import de.randombyte.ktskript.KtSkriptPlugin.Companion.VERSION
8 | import de.randombyte.ktskript.config.ConfigAccessors
9 | import de.randombyte.ktskript.script.ScriptsManager
10 | import de.randombyte.ktskript.script.UnloadScriptsEvent
11 | import de.randombyte.ktskript.utils.*
12 | import org.apache.commons.lang3.RandomUtils
13 | import org.bstats.sponge.Metrics
14 | import org.slf4j.Logger
15 | import org.spongepowered.api.Sponge
16 | import org.spongepowered.api.config.ConfigDir
17 | import org.spongepowered.api.entity.living.player.Player
18 | import org.spongepowered.api.event.Listener
19 | import org.spongepowered.api.event.cause.Cause
20 | import org.spongepowered.api.event.cause.EventContext
21 | import org.spongepowered.api.event.game.GameReloadEvent
22 | import org.spongepowered.api.event.game.state.GameInitializationEvent
23 | import org.spongepowered.api.event.game.state.GameStoppingServerEvent
24 | import org.spongepowered.api.event.network.ClientConnectionEvent
25 | import org.spongepowered.api.plugin.Plugin
26 | import org.spongepowered.api.plugin.PluginContainer
27 | import org.spongepowered.api.scheduler.Task
28 | import java.nio.file.Files
29 | import java.nio.file.Path
30 | import java.util.*
31 | import java.util.concurrent.TimeUnit
32 |
33 | @Plugin(
34 | id = ID,
35 | name = NAME,
36 | version = VERSION,
37 | authors = [AUTHOR])
38 | class KtSkriptPlugin @Inject constructor(
39 | val logger: Logger,
40 | @ConfigDir(sharedRoot = false) private val configPath: Path,
41 | private val bStats: Metrics,
42 | private val pluginContainer: PluginContainer
43 | ) {
44 |
45 | companion object {
46 | const val ID = "kt-skript"
47 | const val NAME = "KtSkript"
48 | const val VERSION = "1.4.0"
49 | const val AUTHOR = "RandomByte"
50 |
51 | const val DEFAULT_IMPORTS_FILE_NAME = "default.imports"
52 | }
53 |
54 | val scriptsManager = ScriptsManager()
55 |
56 | val configAccessors = ConfigAccessors(configPath)
57 |
58 | val scriptDir = configPath.resolve("scripts")
59 |
60 | val cause = Cause.builder().append(this).build(EventContext.empty())
61 |
62 | init {
63 | if (Files.notExists(scriptDir)) Files.createDirectory(scriptDir)
64 | }
65 |
66 | private var scriptsWatcher: FolderWatcher? = null
67 |
68 | @Listener
69 | fun onInit(event: GameInitializationEvent) {
70 | System.setProperty("idea.use.native.fs.for.win", "false")
71 |
72 | reload()
73 |
74 | if (needsMotivationalSpeech()) {
75 | Task.builder()
76 | .delay(RandomUtils.nextLong(80, 130), TimeUnit.SECONDS)
77 | .execute { -> Texts.motivationalSpeech.forEach { it.sendTo(Sponge.getServer().console) } }
78 | .submit(this)
79 | }
80 |
81 | logger.info("Loaded $NAME: $VERSION")
82 | }
83 |
84 | @Listener
85 | fun onReload(event: GameReloadEvent) {
86 | reload()
87 | logger.info("Reloaded!")
88 | }
89 |
90 | @Listener
91 | fun onStopping(event: GameStoppingServerEvent) {
92 | postUnloadScriptsEvent()
93 | }
94 |
95 | private fun reload() {
96 | configAccessors.reloadAll()
97 | copyDefaultImportsIfNeeded()
98 | reloadAllScripts()
99 | setupFolderWatchers()
100 | }
101 |
102 | private fun setupFolderWatchers() {
103 | scriptsWatcher?.stop()
104 | scriptsWatcher = FolderWatcher(scriptDir, configAccessors.general.get().updateInterval) {
105 | logger.info("Detected changes in the scripts folder.")
106 | reloadAllScripts()
107 | }
108 | }
109 |
110 | /**
111 | * Unregisters mostly everything which was set up by scripts, and by this plugin as well
112 | */
113 | private fun tidyUp() {
114 | CommandManager.getOwnedBy(this).map(CommandManager::removeMapping)
115 | EventManager.unregisterPluginListeners(this)
116 | Scheduler.getScheduledTasks(this)
117 | .filterNot { it.name == FolderWatcher.SCRIPTS_FOLDER_WATCHER_TASK_NAME }
118 | .forEach { it.cancel() }
119 | }
120 |
121 | private fun reloadAllScripts() {
122 | // Notify scripts of them being about to be unloaded to allow them to save configs
123 | postUnloadScriptsEvent()
124 |
125 | // removes all left over event handlers, commands etc. of scripts
126 | tidyUp()
127 |
128 | try {
129 | with(scriptsManager) {
130 | clear()
131 | loadGlobalImports(configPath, verbose = configAccessors.general.get().verboseClasspathScanner)
132 | loadScripts(scriptDir)
133 | runAllScriptsSafely()
134 | }
135 | } catch (throwable: Throwable) {
136 | throwable.printStackTrace()
137 | }
138 |
139 | // Register our own reload event listener again
140 | EventManager.registerListeners(this, this)
141 |
142 | logger.info("Loaded ${scriptsManager.scripts.size} script(s).")
143 | }
144 |
145 | private fun postUnloadScriptsEvent() {
146 | EventManager.post(UnloadScriptsEvent(scriptsManager.scripts.keys.toList(), cause))
147 | }
148 |
149 | /**
150 | * Rewrites the default.imports file to match the built-in one, only if the config option is
151 | * set accordingly.
152 | */
153 | private fun copyDefaultImportsIfNeeded() {
154 | if (!configAccessors.general.get().allowDefaultImportsModifications) {
155 | pluginContainer.getAsset(DEFAULT_IMPORTS_FILE_NAME).get().copyToDirectory(configPath, true)
156 | }
157 | }
158 |
159 |
160 | val metricsNoteSent = mutableSetOf()
161 |
162 | @Listener
163 | fun onPlayerJoin(event: ClientConnectionEvent.Join) {
164 | val uuid = event.targetEntity.uniqueId
165 | if (needsMotivationalSpeech(event.targetEntity)) {
166 | Task.builder()
167 | .delay(RandomUtils.nextLong(10, 50), TimeUnit.SECONDS)
168 | .execute { ->
169 | val player = uuid.getPlayer() ?: return@execute
170 | metricsNoteSent += uuid
171 | Texts.motivationalSpeech.forEach { it.sendTo(player) }
172 | }
173 | .submit(this)
174 | }
175 | }
176 |
177 | private fun needsMotivationalSpeech(player: Player? = null) = configAccessors.general.get().enableMetricsMessages &&
178 | !Sponge.getMetricsConfigManager().areMetricsEnabled(this) &&
179 | ((player == null) || player.uniqueId !in metricsNoteSent && player.hasPermission("nucleus.mute.base")) // also passes OPs without Nucleus
180 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/Texts.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript
2 |
3 | import de.randombyte.ktskript.utils.*
4 |
5 | object Texts {
6 | val motivationalSpeech = listOf(
7 | "[${KtSkriptPlugin.NAME}] ".yellow() + "Metrics are disabled for this plugin or globally! Please consider enabling metrics.".aqua(),
8 | "Metrics are anonymous usage data (how many players are on the server, which minecraft version the server is on, etc.)".green(),
9 | "With that data the developer can check how many servers use the plugin. Plugins with many users motivate me more to release new updates. :)".gold(),
10 | "To disable this message, go to the Sponge global config, and enable metrics collection for at least this plugin, thanks! ;)".lightPurple())
11 |
12 | const val configComment = "Since you are already editing configs, how about enabling metrics for at least this plugin? ;)\n" +
13 | "Go to the 'config/sponge/global.conf', scroll to the 'metrics' section and enable metrics.\n" +
14 | "Anonymous metrics data collection enables the developer to see how many people and servers are using this plugin.\n" +
15 | "Seeing that my plugin is being used is a big factor in motivating me to provide future support and updates.\n" +
16 | "If you really don't want to enable metrics and don't want to receive any messages anymore, you can disable this config option ;("
17 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/config/ConfigAccessors.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.config
2 |
3 | import de.randombyte.ktskript.config.kosp.AbstractConfigAccessors
4 | import de.randombyte.ktskript.config.kosp.ConfigHolder
5 | import java.nio.file.Path
6 |
7 | class ConfigAccessors(configPath: Path) : AbstractConfigAccessors(configPath) {
8 |
9 | val general: ConfigHolder = getConfigHolder("general.conf")
10 |
11 | override val holders = listOf(general)
12 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/config/GeneralConfig.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.config
2 |
3 | import de.randombyte.ktskript.Texts
4 | import ninja.leaping.configurate.objectmapping.Setting
5 | import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable
6 | import java.time.Duration
7 |
8 | @ConfigSerializable class GeneralConfig(
9 | @Setting("enable-metrics-messages", comment = Texts.configComment) val enableMetricsMessages: Boolean = true,
10 | @Setting("script-update-interval", comment = "How often the script files should be checked for changes.")
11 | val updateInterval: Duration = Duration.ZERO,
12 | @Setting("output-scripts-to-console", comment = "Useful for debugging the imports.")
13 | val outputScripts: Boolean = false,
14 | @Setting("warn-about-multiple-compile-requests", comment = "Read the docs to learn more.")
15 | val warnAboutDuplicates: Boolean = true,
16 | @Setting("verbose-classpath-scanner", comment = "Useful for debugging the classpath. Warning: Very verbose, much console output!")
17 | val verboseClasspathScanner: Boolean = false,
18 | @Setting("allow-default-imports-modifications", comment = "By default the default.imports is completely ignored and just printed for convenience, read the wiki.")
19 | val allowDefaultImportsModifications: Boolean = false
20 | ) {
21 | // default config
22 | constructor() : this(
23 | updateInterval = Duration.ofSeconds(3),
24 | outputScripts = false,
25 | warnAboutDuplicates = true,
26 | verboseClasspathScanner = false,
27 | allowDefaultImportsModifications = false
28 | )
29 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/config/kosp/AbstractConfigAccessors.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.config.kosp
2 |
3 | import de.randombyte.ktskript.utils.toConfigurationLoader
4 | import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection
5 | import java.nio.file.Files
6 | import java.nio.file.Path
7 |
8 | /**
9 | * To be overwritten to have fields for various [ConfigHolder]s.
10 | */
11 | abstract class AbstractConfigAccessors(val configPath: Path) {
12 |
13 | init {
14 | if (Files.notExists(configPath)) {
15 | Files.createDirectories(configPath)
16 | }
17 | }
18 |
19 | abstract val holders: List>
20 |
21 | fun reloadAll() {
22 | holders.forEach(ConfigHolder<*>::reload)
23 | reloadedAll()
24 | }
25 |
26 | /**
27 | * Called when all configs were reloaded.
28 | */
29 | open fun reloadedAll() { }
30 |
31 | protected inline fun getConfigHolder(
32 | configName: String,
33 | noinline additionalSerializers: TypeSerializerCollection.() -> Any = {}
34 | ) = ConfigManager(
35 | configPath.resolve(configName).toConfigurationLoader(),
36 | T::class.java,
37 | additionalSerializers = additionalSerializers
38 | ).toConfigHolder()
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/config/kosp/ConfigHolder.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.config.kosp
2 |
3 | /**
4 | * Caches a config file, backed by a [ConfigManager].
5 | */
6 | open class ConfigHolder(val configManager: ConfigManager) {
7 | private lateinit var config: T
8 |
9 | /**
10 | * Called when the config was reloaded.
11 | */
12 | open fun reloaded() { }
13 |
14 | fun reload() {
15 | save(configManager.load()) // generates the config automatically
16 | reloaded()
17 | }
18 |
19 | fun get() = config
20 |
21 | fun save(config: T) {
22 | this.config = config
23 | configManager.save(config)
24 | }
25 | }
26 |
27 | fun ConfigManager.toConfigHolder(): ConfigHolder = ConfigHolder(this)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/config/kosp/ConfigManager.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.config.kosp
2 |
3 | import com.google.common.reflect.TypeToken
4 | import de.randombyte.ktskript.utils.serializers.SimpleDateTypeSerializer
5 | import de.randombyte.ktskript.utils.serializers.SimpleDurationTypeSerializer
6 | import de.randombyte.ktskript.utils.typeToken
7 | import ninja.leaping.configurate.ConfigurationOptions
8 | import ninja.leaping.configurate.commented.CommentedConfigurationNode
9 | import ninja.leaping.configurate.loader.ConfigurationLoader
10 | import ninja.leaping.configurate.objectmapping.serialize.TypeSerializerCollection
11 | import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers
12 | import java.time.Duration
13 | import java.util.*
14 |
15 | /**
16 | * A class for one specific config file which handles generating configs if it isn't present.
17 | */
18 | class ConfigManager (
19 | val configLoader: ConfigurationLoader,
20 | clazz: Class,
21 | simpleDurationSerialization: Boolean = true,
22 | simpleDateSerialization: Boolean = true,
23 | additionalSerializers: TypeSerializerCollection.() -> Any = { }
24 | ) {
25 |
26 | private val typeToken: TypeToken = clazz.kotlin.typeToken
27 | private val options: ConfigurationOptions = ConfigurationOptions.defaults()
28 | .setShouldCopyDefaults(true)
29 | .setSerializers(TypeSerializers.getDefaultSerializers().newChild().apply {
30 | if (simpleDurationSerialization) registerType(Duration::class.typeToken, SimpleDurationTypeSerializer)
31 | if (simpleDateSerialization) registerType(Date::class.typeToken, SimpleDateTypeSerializer)
32 | additionalSerializers.invoke(this)
33 | })
34 |
35 | /**
36 | * Returns the saved config. If none exists a new one is generated and already saved.
37 | */
38 | @Suppress("UNCHECKED_CAST")
39 | fun load(): T = configLoader.load(options).getValue(typeToken) ?: {
40 | save(typeToken.rawType.newInstance() as T)
41 | load()
42 | }.invoke()
43 |
44 | fun save(config: T) = configLoader.apply { save(load(options).setValue(typeToken, config)) }
45 |
46 | /**
47 | * get() already generates the config when none exists but this method also inserts missing nodes
48 | * and reformats the structure.
49 | */
50 | fun generate() = save(load())
51 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/script/Script.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.script
2 |
3 | import de.randombyte.ktskript.script.ScriptsManager.InternalScript
4 | import de.randombyte.ktskript.utils.KtSkript
5 | import java.nio.file.Path
6 |
7 | class Script(val id: String, val path: Path) {
8 |
9 | companion object {
10 | const val THREE_QUOTES = "\"\"\""
11 | }
12 |
13 | // This could be implemented with bindings but it seems to be more readable for now
14 | fun toCode() = """
15 | KtSkriptScript("$id", Paths.get($THREE_QUOTES${path.toAbsolutePath()}$THREE_QUOTES))
16 | """.trimIndent()
17 |
18 | /**
19 | * Compiles one or more scripts.
20 | * If [path] points to a single file, that one is tried to be compiled.
21 | * If [path] points to a folder, every .ktskript file is tried.
22 | * If a .ktskript file was already compiled (and is now cached), it won't be recompiled.
23 | *
24 | * @return a [Map] which consists of the successfully compiled and/or cached [InternalScript]s mapped to its ID
25 | */
26 | fun compile(path: Path): Map = KtSkript.scriptsManager.loadScripts(path)
27 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/script/ScriptEngineFactory.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.script
2 |
3 | import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBase
4 | import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
5 | import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine
6 | import org.jetbrains.kotlin.script.jsr223.KotlinStandardJsr223ScriptTemplate
7 | import java.io.File
8 | import javax.script.Bindings
9 | import javax.script.ScriptContext
10 |
11 | // Taken from the KotlinJsr223ScriptEngineFactoryExamples.kt
12 |
13 | class MyKotlinJsr223JvmLocalScriptEngineFactory(private val templateClasspath: List) : KotlinJsr223JvmScriptEngineFactoryBase() {
14 | override fun getScriptEngine() = KotlinJsr223JvmLocalScriptEngine(
15 | this,
16 | templateClasspath,
17 | KotlinStandardJsr223ScriptTemplate::class.qualifiedName!!,
18 | { ctx, types -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), types ?: emptyArray()) },
19 | arrayOf(Bindings::class)
20 | )
21 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/script/ScriptsManager.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.script
2 |
3 | import de.randombyte.ktskript.utils.KtSkript
4 | import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner
5 | import java.io.File
6 | import java.nio.file.Path
7 | import javax.script.CompiledScript
8 |
9 | class ScriptsManager {
10 | companion object {
11 | // doing the typealias thing here because 'Script' is apparently already used somewhere in the imported packages
12 | fun generateHelpers(script: Script) =
13 | """
14 | typealias KtSkriptScript = de.randombyte.ktskript.script.Script
15 | val script = ${script.toCode()}
16 | """.trimIndent()
17 | }
18 |
19 | class InternalScript(val path: Path, val compiledScript: CompiledScript)
20 | val scripts: MutableMap = mutableMapOf()
21 |
22 | private val allClasspathFiles = lazy { getAsMuchClasspathAsPossible().map { it.absoluteFile } }
23 |
24 | private fun newEngine(templateClasspath: List) = MyKotlinJsr223JvmLocalScriptEngineFactory(templateClasspath).scriptEngine
25 |
26 | var globalImports = ""
27 |
28 | fun clear() {
29 | scripts.clear()
30 | globalImports = ""
31 | }
32 |
33 | /**
34 | * @return Import statements for all classes from the packages specified in the given [file]
35 | */
36 | fun loadImportsFromFile(file: File, verbose: Boolean): String {
37 | val packagePrefixes = file
38 | .readLines()
39 | .filter { it.isNotBlank() }
40 | .toTypedArray()
41 |
42 | val classPathImportPackages = FastClasspathScanner(*packagePrefixes)
43 | .verbose(verbose)
44 | .overrideClasspath(allClasspathFiles.value)
45 | .alwaysScanClasspathElementRoot(false)
46 | .strictWhitelist()
47 | .scan()
48 | .namesOfAllClasses
49 | .map { it.substringBeforeLast(".") } // snip away class name
50 | .filter { it.isNotEmpty() }
51 | .toSet() // ensure uniqueness
52 |
53 | val newImports = classPathImportPackages
54 | .joinToString(separator = "\n") { "import $it.*;" }
55 |
56 | return newImports
57 | }
58 |
59 | /**
60 | * Loads all classes from the packages specified in the given [path] which should point to the
61 | * "default.imports" file.
62 | *
63 | * @param path [Path] to the root config dir
64 | */
65 | fun loadGlobalImports(path: Path, verbose: Boolean) {
66 | globalImports += loadImportsFromFile(path.resolve("default.imports").toFile(), verbose)
67 | }
68 |
69 | /**
70 | * Loads all classes from the packages specified in the given [file] which should point to the
71 | * script specific ".imports" file.
72 | *
73 | * @param file [Path] to the ".imports" file
74 | *
75 | * @return all import statements from the file
76 | */
77 | fun loadScriptSpecificImports(file: File, verbose: Boolean): String = loadImportsFromFile(file, verbose)
78 |
79 | /**
80 | * @return the successfully read scripts
81 | */
82 | fun loadScripts(path: Path): Map {
83 | val scriptFiles = getFiles(path, extension = "ktskript")
84 | .map { it.nameWithoutExtension to it }
85 | .toList()
86 |
87 | // check duplicate use of IDs
88 | val duplicatedIds = scriptFiles
89 | .groupBy { (id, _) -> id }
90 | .mapValues { (_, occurrences) -> occurrences.count() }
91 | .filter { (_, count) -> count > 1 }
92 |
93 | duplicatedIds.forEach { (id, count) ->
94 | KtSkript.logger.error("Ignoring scripts '$id': Multiple use of script ID '$id'($count times)!")
95 | }
96 | if (duplicatedIds.isNotEmpty()) return emptyMap()
97 |
98 | val alreadyCompiledScripts = mutableMapOf()
99 |
100 | val generalConfig = KtSkript.configAccessors.general.get()
101 |
102 | val compiledScripts = scriptFiles
103 | .toMap() // uniqueness of keys is now guaranteed
104 | // filter already used script IDs
105 | .filter { (id, file) ->
106 | if (id in scripts.keys) {
107 | if (generalConfig.warnAboutDuplicates) {
108 | KtSkript.logger.warn("Ignoring already used script ID '$id' at '${file.absolutePath}'!")
109 | }
110 | alreadyCompiledScripts += id to scripts.getValue(id)
111 | false
112 | } else true
113 | }
114 | // read script file
115 | .map { (id, file) -> Triple(id, file, file.readText()) }
116 | // add imports and the Script helper object
117 | .map { (id, file, scriptContent) ->
118 |
119 | val importsFile = File(file.parent, file.nameWithoutExtension + ".imports")
120 | val scriptSpecificImports: String? = if (importsFile.exists() && importsFile.isFile) {
121 | loadScriptSpecificImports(importsFile, verbose = generalConfig.verboseClasspathScanner)
122 | } else null
123 |
124 | val scriptString = """
125 | $globalImports
126 | ${scriptSpecificImports.orEmpty()}
127 | ${generateHelpers(Script(id, file.toPath()))}
128 | $scriptContent
129 | """.trimIndent()
130 |
131 | if (generalConfig.outputScripts) {
132 | KtSkript.logger.info("Script '$id':\n$scriptString")
133 | }
134 |
135 | Triple(id, file, scriptString)
136 | }
137 | // compile script
138 | .mapNotNull { (id, file, scriptString) ->
139 | val compiledScript = try {
140 | // reset engine because there might be errors from previous scripts
141 | val scriptEngine = newEngine(allClasspathFiles.value)
142 | scriptEngine.compile(scriptString)
143 | } catch (throwable: Throwable) {
144 | KtSkript.logger.error("Ignoring faulty script '$id' at '${file.absolutePath}'!", throwable)
145 | return@mapNotNull null
146 | }
147 | id to InternalScript(file.toPath(), compiledScript)
148 | }
149 | .toMap()
150 |
151 | scripts += compiledScripts
152 |
153 | return compiledScripts + alreadyCompiledScripts
154 | }
155 |
156 | /**
157 | * This tries to run all scripts. If any script fails to execute, it is removed from [scripts].
158 | */
159 | fun runAllScriptsSafely() {
160 | runScriptsSafely(*scripts.keys.toTypedArray())
161 | }
162 |
163 | /**
164 | * @return if the specific scripts were run successfully
165 | */
166 | fun runScriptsSafely(vararg ids: String) = ids.map { id -> id to runScriptSafely(id) }.toMap()
167 |
168 | /**
169 | * Tries to run the script with the given [id]. If the execution fails the script will be removed
170 | * from the [scripts].
171 | *
172 | * @return if the script was run successfully
173 | */
174 | fun runScriptSafely(id: String): Boolean {
175 | val script = scripts[id] ?: throw IllegalArgumentException("No script available with id '$id'!")
176 | try {
177 | script.compiledScript.eval()
178 | } catch (throwable: Throwable) {
179 | KtSkript.logger.error("Can not run script '$id'!", throwable)
180 | scripts.remove(id)
181 | return false
182 | }
183 | return true
184 | }
185 |
186 | private fun getFiles(path: Path, extension: String) = path.toFile().walk().filter { file ->
187 | file.isFile && file.extension == extension
188 | }
189 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/script/UnloadScriptsEvent.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.script
2 |
3 | import org.spongepowered.api.event.Event
4 | import org.spongepowered.api.event.cause.Cause
5 |
6 | /**
7 | * Fired when scripts are about to be unloaded. Useful for config saving.
8 | */
9 | class UnloadScriptsEvent(val scripts: List, private val _cause: Cause) : Event {
10 | override fun getCause() = _cause
11 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/script/Utils.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.script
2 |
3 | import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner
4 | import org.jetbrains.kotlin.script.util.classpathFromClassloader
5 | import org.jetbrains.kotlin.utils.PathUtil
6 |
7 | fun getAsMuchClasspathAsPossible() = FastClasspathScanner().findBestClassLoader()
8 | .flatMap { classpathFromClassloader(it)!! } + PathUtil.getJdkClassesRootsFromCurrentJre()
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/BigDecimals.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import java.math.BigDecimal
4 |
5 | operator fun BigDecimal.plus(other: Int): BigDecimal = this + other.toBigDecimal()
6 | operator fun BigDecimal.plus(other: Double): BigDecimal = this + other.toBigDecimal()
7 |
8 | operator fun BigDecimal.minus(other: Int): BigDecimal = this - other.toBigDecimal()
9 | operator fun BigDecimal.minus(other: Double): BigDecimal = this - other.toBigDecimal()
10 |
11 | operator fun BigDecimal.times(other: Int): BigDecimal = this * other.toBigDecimal()
12 | operator fun BigDecimal.times(other: Double): BigDecimal = this * other.toBigDecimal()
13 |
14 | operator fun BigDecimal.div(other: Int): BigDecimal = this * other.toBigDecimal()
15 | operator fun BigDecimal.div(other: Double): BigDecimal = this * other.toBigDecimal()
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/BlockSnapshots.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.block.BlockSnapshot
4 | import org.spongepowered.api.block.BlockType
5 | import org.spongepowered.api.world.Location
6 | import org.spongepowered.api.world.extent.Extent
7 |
8 | val BlockSnapshot.type: BlockType
9 | get() = state.type
10 |
11 | val BlockSnapshot.blockLocation: Location
12 | get() = location.orElseThrow { RuntimeException("This BlockSnapshot doesn't have a Location!") }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Carriers.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.entity.living.player.Player
4 | import org.spongepowered.api.item.inventory.Carrier
5 | import org.spongepowered.api.item.inventory.Inventory
6 | import org.spongepowered.api.item.inventory.ItemStack
7 | import org.spongepowered.api.item.inventory.entity.MainPlayerInventory
8 | import org.spongepowered.api.item.inventory.query.QueryOperationTypes
9 | import org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult.Type.SUCCESS
10 |
11 | /**
12 | * Tries to offer the given [itemStack] to this [Carrier]. If the carrier is a [Player] the items is
13 | * only tried to be offered to the [MainPlayerInventory].
14 | *
15 | * @return true if the transaction was successful
16 | */
17 | fun Carrier.give(itemStack: ItemStack): Boolean {
18 | val inventory = when(this) {
19 | is Player -> inventory.query(QueryOperationTypes.INVENTORY_TYPE.of(MainPlayerInventory::class.java))
20 | else -> inventory
21 | }
22 |
23 | return inventory.offer(itemStack).type == SUCCESS
24 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Classes.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import com.google.common.reflect.TypeToken
4 | import kotlin.reflect.KClass
5 |
6 | val KClass.typeToken: TypeToken
7 | get() = TypeToken.of(this.java)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Configs.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import ninja.leaping.configurate.ConfigurationNode
4 | import ninja.leaping.configurate.hocon.HoconConfigurationLoader
5 | import java.nio.file.Path
6 |
7 | fun Path.toConfigurationLoader() = HoconConfigurationLoader.builder()
8 | .setPath(this)
9 | .build()
10 |
11 | fun Path.loadConfig(): ConfigurationNode = toConfigurationLoader().load()
12 |
13 | fun Path.saveConfig(configurationNode: ConfigurationNode) {
14 | toConfigurationLoader().save(configurationNode)
15 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Data.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.data.DataHolder
4 | import org.spongepowered.api.data.manipulator.DataManipulator
5 | import org.spongepowered.api.data.manipulator.mutable.RepresentedItemData
6 | import org.spongepowered.api.data.manipulator.mutable.entity.HealthData
7 | import org.spongepowered.api.data.manipulator.mutable.entity.InvisibilityData
8 | import org.spongepowered.api.data.manipulator.mutable.entity.SneakingData
9 | import org.spongepowered.api.item.inventory.ItemStackSnapshot
10 |
11 | private inline fun > DataHolder.getOrThrow() = getOrCreate(T::class.java).orElseThrow {
12 | IllegalArgumentException("'${this::class.java.simpleName}' doesn't support '${T::class.simpleName}'!")
13 | }
14 |
15 | // todo: how to improve the mess? plus the upcoming additions?
16 |
17 | var DataHolder.health: Double
18 | get() = getOrThrow().health().get()
19 | set(value) { offer(getOrThrow().health().set(value)) }
20 |
21 | var DataHolder.invisible: Boolean
22 | get() = getOrThrow().invisible().get()
23 | set(value) { offer(getOrThrow().invisible().set(value)) }
24 |
25 | var DataHolder.vanished: Boolean
26 | get() = getOrThrow().vanish().get()
27 | set(value) { offer(getOrThrow().vanish().set(value)) }
28 |
29 | val DataHolder.isSneaking: Boolean
30 | get() = getOrThrow().sneaking().get()
31 |
32 |
33 | var DataHolder.representedItem: ItemStackSnapshot
34 | get() = getOrThrow().item().get()
35 | set(value) { offer(getOrThrow().item().set(value)) }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Dates.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import ninja.leaping.configurate.objectmapping.ObjectMappingException
4 | import java.text.ParseException
5 | import java.text.SimpleDateFormat
6 | import java.util.*
7 |
8 | object Dates {
9 | private val dateFormat = SimpleDateFormat("HH:mm:ss.SSS-dd.MM.yyyy")
10 |
11 | fun deserialize(string: String): Date {
12 | try {
13 | return dateFormat.parse(string)
14 | } catch (exception: ParseException) {
15 | throw ObjectMappingException("Invalid input value '$string' for a date like this: '21:18:25.300-28.03.2017'", exception)
16 | }
17 | }
18 |
19 | fun serialize(date: Date): String = dateFormat.format(date)
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Durations.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import java.time.Duration
4 |
5 | /**
6 | * A simple format for defining [Duration]s.
7 | *
8 | * 'd' -> days
9 | * 'h' -> hours
10 | * 'm' -> minutes
11 | * 's' -> seconds
12 | * 'ms' -> milliseconds
13 | *
14 | * Examples: '1d4h30m20s90ms', '30s', '2h', '12m3s', '500ms'
15 | */
16 | object Durations {
17 | private const val MINUTE = 60
18 | private const val HOUR = 60 * MINUTE
19 | private const val DAY = 24 * HOUR
20 |
21 | val REGEX = "(?:(\\d+)d)?(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?(?:(\\d+)ms)?".toRegex()
22 |
23 | fun deserialize(string: String): Duration {
24 | val result = REGEX.matchEntire(string) ?: throw RuntimeException("Couldn't parse duration '$string'!")
25 |
26 | val days = result.groupValues[1].toLongOrZero()
27 | val hours = result.groupValues[2].toLongOrZero()
28 | val minutes = result.groupValues[3].toLongOrZero()
29 | val seconds = result.groupValues[4].toLongOrZero()
30 | val milliseconds = result.groupValues[5].toLongOrZero()
31 |
32 | return Duration.ofDays(days).plusHours(hours).plusMinutes(minutes).plusSeconds(seconds).plusMillis(milliseconds)
33 | }
34 |
35 | fun serialize(duration: Duration, outputMilliseconds: Boolean = true): String {
36 | val days = duration.seconds / DAY
37 | val hours = duration.seconds % DAY / HOUR
38 | val minutes = duration.seconds % DAY % HOUR / MINUTE
39 | val seconds = duration.seconds % DAY % HOUR % MINUTE
40 | val milliseconds = duration.nano / 1000000
41 |
42 | val sb = StringBuilder()
43 | days.apply { if (this != 0L) sb.append(this).append("d") }
44 | hours.apply { if (this != 0L) sb.append(this).append("h") }
45 | minutes.apply { if (this != 0L) sb.append(this).append("m") }
46 | seconds.apply { if (this != 0L) sb.append(this).append("s") }
47 | milliseconds.apply { if (outputMilliseconds && this != 0) sb.append(this).append("ms") }
48 |
49 | val string = sb.toString()
50 | return if (string.isNotEmpty()) string else "0s" // prevent "" return values
51 | }
52 |
53 | private fun String.toLongOrZero() = if (isEmpty()) 0 else toLong()
54 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Economy.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.entity.living.player.User
4 | import org.spongepowered.api.service.economy.EconomyService
5 | import org.spongepowered.api.service.economy.account.Account
6 | import org.spongepowered.api.service.economy.account.UniqueAccount
7 | import java.math.BigDecimal
8 | import java.util.*
9 |
10 | fun EconomyService.getAccount(identifier: String): Account = getOrCreateAccount(identifier)
11 | .orElseThrow { IllegalArgumentException("Could not get or create economy account '$identifier'!") }
12 |
13 | fun EconomyService.getAccount(uuid: UUID): UniqueAccount = getOrCreateAccount(uuid)
14 | .orElseThrow { IllegalArgumentException("Could not get or create economy account '$uuid'!") }
15 |
16 | fun EconomyService.getCurrencyById(id: String) = currencies.find { it.id == id }
17 | ?: throw IllegalArgumentException("Could not find currency '$id'!")
18 |
19 | var Account.balance: BigDecimal
20 | get() = getBalance(EconomyService.defaultCurrency)
21 | set(balance) { setBalance(EconomyService.defaultCurrency, balance, KtSkript.cause) }
22 |
23 | val User.economyAccount: UniqueAccount
24 | get() = EconomyService.getAccount(uniqueId)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Equipables.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.data.type.HandType
4 | import org.spongepowered.api.data.type.HandTypes
5 | import org.spongepowered.api.data.type.HandTypes.MAIN_HAND
6 | import org.spongepowered.api.entity.Equipable
7 | import org.spongepowered.api.item.inventory.ItemStack
8 | import org.spongepowered.api.item.inventory.equipment.EquipmentTypes
9 |
10 | fun Equipable.hasItemInHand(handType: HandType = MAIN_HAND) = !getEquipped(handType.equipmentType).orElse(ItemStack.empty()).isEmpty
11 |
12 | @Deprecated("The Sponge native method takes priority over this extension function.")
13 | fun Equipable.getItemInHand(handType: HandType = MAIN_HAND) = getEquipped(handType.equipmentType).orElseThrow {
14 | RuntimeException("Equipable '$bestName' doesn't have anything in the '${handType.name}' hand!")
15 | }
16 |
17 | fun Equipable.itemInHand(handType: HandType = MAIN_HAND) = getEquipped(handType.equipmentType).orElseThrow {
18 | RuntimeException("Equipable '$bestName' doesn't have anything in the '${handType.name}' hand!")
19 | }
20 |
21 | private val HandType.equipmentType get() = when(this) {
22 | HandTypes.MAIN_HAND -> EquipmentTypes.MAIN_HAND
23 | HandTypes.OFF_HAND -> EquipmentTypes.OFF_HAND
24 | else -> throw RuntimeException("Illegal HandType!")
25 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Humanoids.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.command.CommandException
4 | import org.spongepowered.api.data.type.HandTypes
5 | import org.spongepowered.api.entity.EntityTypes
6 | import org.spongepowered.api.entity.living.Humanoid
7 | import org.spongepowered.api.item.inventory.Carrier
8 | import org.spongepowered.api.item.inventory.ItemStack
9 |
10 | /**
11 | * Gives the [Humanoid] the [itemStack] by trying these things:
12 | * 1. putting it in the hand
13 | * 2. putting it somewhere in the inventory
14 | * 3. dropping it onto the ground
15 | */
16 | fun Humanoid.give(itemStack: ItemStack) { // todo more general: Any.give()?
17 | fun ItemStack.singleCopy(): ItemStack = copy().apply { quantity = 1 }
18 |
19 | val itemInHand = getItemInHand(HandTypes.MAIN_HAND).orNull()
20 |
21 | if (itemInHand == null) {
22 | // nothing in hand -> put item in hand
23 | setItemInHand(HandTypes.MAIN_HAND, itemStack)
24 | } else {
25 | if (itemInHand.singleCopy().equalTo(itemStack.singleCopy())) {
26 | val newQuantity = itemInHand.quantity + itemStack.quantity
27 | if (newQuantity <= itemInHand.type.maxStackQuantity) {
28 | itemInHand.quantity = newQuantity
29 | setItemInHand(HandTypes.MAIN_HAND, itemInHand)
30 | return
31 | }
32 | }
33 |
34 | // something in hand or exceeds max quantity -> place item somewhere in inventory
35 | val success = (this as Carrier).give(itemStack)
36 | if (!success) {
37 | // inventory full -> spawn as item
38 | val itemEntity = location.extent.createEntity(EntityTypes.ITEM, location.position)
39 | itemEntity.representedItem = itemStack.createSnapshot()
40 | if (!location.extent.spawnEntity(itemEntity)) {
41 | throw CommandException("Couldn't spawn Item!".t)
42 | }
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Locations.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.entity.Entity
4 | import org.spongepowered.api.world.Locatable
5 | import org.spongepowered.api.world.Location
6 | import org.spongepowered.api.world.World
7 | import org.spongepowered.api.world.extent.Extent
8 |
9 | val Location.world: World
10 | get() = extent as? World ?: throw RuntimeException("The Location isn't in a World!")
11 |
12 | fun Iterable.getNearest(location: Location): T? = filter {
13 | it.location.extent.uniqueId == location.extent.uniqueId
14 | }.minBy {
15 | it.location.position.distance(location.position)
16 | }
17 |
18 | fun Location.getNearbyEntities(distance: Double) = extent.getNearbyEntities(position, distance)
19 |
20 | inline fun Location.getNearbyEntitiesOfType(distance: Double): List {
21 | return extent.getNearbyEntities(position, distance).mapNotNull { it as? T }
22 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Logging.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | fun log(message: String) = KtSkript.logger.info("LOG: $message")
4 |
5 | fun warn(message: String) = KtSkript.logger.warn("WARNING: $message")
6 |
7 | fun error(message: String) = KtSkript.logger.error("ERROR: $message")
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Managers.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.Server
4 | import org.spongepowered.api.Sponge
5 | import org.spongepowered.api.command.CommandManager
6 | import org.spongepowered.api.event.EventManager
7 | import org.spongepowered.api.plugin.PluginManager
8 | import org.spongepowered.api.scheduler.Scheduler
9 | import org.spongepowered.api.service.ServiceManager
10 | import org.spongepowered.api.service.economy.EconomyService as SpongeEconomyService
11 |
12 | inline val Server: Server get() = Sponge.getServer()
13 |
14 | inline val PluginManager: PluginManager get() = Sponge.getPluginManager()
15 | inline val CommandManager: CommandManager get() = Sponge.getCommandManager()
16 | inline val EventManager: EventManager get() = Sponge.getEventManager()
17 | inline val ServiceManager: ServiceManager get() = Sponge.getServiceManager()
18 | inline val Scheduler: Scheduler get() = Sponge.getScheduler()
19 |
20 | inline val EconomyService: SpongeEconomyService get() = SpongeEconomyService::class.service
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Optionals.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import java.util.*
4 |
5 | /**
6 | * Converts the Java [Optional] into the Kotlin equivalent.
7 | */
8 | fun Optional.orNull(): T? = orElse(null)
9 |
10 | /**
11 | * And the other way around.
12 | */
13 | fun T?.toOptional(): Optional = Optional.ofNullable(this)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Random.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.apache.commons.lang3.RandomUtils
4 |
5 | fun randomDouble(start: Double = 0.0, end: Double) = RandomUtils.nextDouble(start, end)
6 |
7 | fun randomInt(start: Int = 0, end: Int) = RandomUtils.nextInt(start, end)
8 |
9 | fun randomBoolean(chance: Double = 0.5) = randomDouble(start = 0.0, end = 1.0) < chance.coerceIn(0.0..1.0)
10 |
11 | val List.randomElement
12 | get() = get(randomInt(start = 0, end = lastIndex))
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Scheduler.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.scheduler.Task
4 | import java.util.concurrent.TimeUnit
5 |
6 | fun delayTicks(ticks: Number, action: () -> Unit): Task = Task.builder()
7 | .delayTicks(ticks.toLong())
8 | .execute { -> action() }
9 | .submit(KtSkript)
10 |
11 | fun delayMillis(millis: Number, action: () -> Unit): Task = Task.builder()
12 | .delay(millis.toLong(), TimeUnit.MILLISECONDS)
13 | .execute { -> action() }
14 | .submit(KtSkript)
15 |
16 | fun delay(duration: String, action: () -> Unit): Task = delayMillis(Durations.deserialize(duration).toMillis(), action)
17 |
18 |
19 | fun onEveryTick(action: () -> Unit) = onEveryTicks(ticks = 0, action = action)
20 |
21 | fun onEveryTicks(ticks: Number, action: () -> Unit): Task = Task.builder()
22 | .intervalTicks(ticks.toLong())
23 | .execute { -> action() }
24 | .submit(KtSkript)
25 |
26 | fun onEvery(interval: String, action: () -> Unit): Task = Task.builder()
27 | .interval(Durations.deserialize(interval).toMillis(), TimeUnit.MILLISECONDS)
28 | .execute { -> action() }
29 | .submit(KtSkript)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Services.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import kotlin.reflect.KClass
4 |
5 | val KClass.available get() = ServiceManager.provide(this.java).isPresent
6 |
7 | val KClass.service get() = ServiceManager.provide(this.java)
8 | .orElseThrow { RuntimeException("Could not load '${this.java.name}'!") }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Strings.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import de.randombyte.byteitems.ByteItemsApi
4 | import me.rojo8399.placeholderapi.PlaceholderService
5 | import org.spongepowered.api.Sponge
6 | import org.spongepowered.api.item.ItemType
7 | import org.spongepowered.api.item.inventory.ItemStack
8 | import org.spongepowered.api.item.inventory.ItemStackSnapshot
9 | import org.spongepowered.api.text.Text
10 | import org.spongepowered.api.text.action.TextAction
11 | import org.spongepowered.api.text.serializer.TextSerializers
12 |
13 | val String.t
14 | get() = TextSerializers.FORMATTING_CODE.deserialize(this)
15 |
16 | fun String.toText(): Text = Text.of(this)
17 |
18 | fun String.aqua(): Text = toText().aqua()
19 | fun String.black(): Text = toText().black()
20 | fun String.blue(): Text = toText().blue()
21 | fun String.darkAqua(): Text = toText().darkAqua()
22 | fun String.darkBlue(): Text = toText().darkBlue()
23 | fun String.darkGray(): Text = toText().darkGray()
24 | fun String.darkGreen(): Text = toText().darkGreen()
25 | fun String.darkPurple(): Text = toText().darkPurple()
26 | fun String.darkRed(): Text = toText().darkRed()
27 | fun String.gold(): Text = toText().gold()
28 | fun String.gray(): Text = toText().gray()
29 | fun String.green(): Text = toText().green()
30 | fun String.lightPurple(): Text = toText().lightPurple()
31 | fun String.red(): Text = toText().red()
32 | fun String.white(): Text = toText().white()
33 | fun String.yellow(): Text = toText().yellow()
34 |
35 | fun String.bold(): Text = toText().bold()
36 | fun String.italic(): Text = toText().italic()
37 | fun String.obfuscated(): Text = toText().obfuscated()
38 | fun String.reset(): Text = toText().reset()
39 | fun String.strikethrough(): Text = toText().strikethrough()
40 | fun String.underline(): Text = toText().underline()
41 |
42 | fun > String.action(action: T): Text = toText().action(action)
43 |
44 | fun String.limit(limit: Int): String {
45 | val safeLimit = limit.coerceIn(0..length)
46 | return if (safeLimit < length) {
47 | substring(0, safeLimit) + "…"
48 | } else this
49 | }
50 |
51 | fun String.replace(vararg args: Pair): String = replace(args.toMap())
52 | fun String.replace(values: Map): String {
53 | var string = this
54 | values.forEach { (argument, value) ->
55 | string = string.replace(argument, value)
56 | }
57 | return string
58 | }
59 |
60 | // API safe wrappers
61 |
62 | object Static {
63 | // fixed the wrong pattern in placeholder api itself...
64 | val PLACEHOLDER_PATTERN = "[%]([^ %]+)[%]".toRegex()
65 | }
66 |
67 | /**
68 | * Tries to process the placeholders if PlaceholderAPI is loaded.
69 | */
70 | fun String.tryReplacePlaceholders(source: Any? = null, observer: Any? = null): String {
71 | if (!PluginManager.getPlugin("placeholderapi").isPresent) return this
72 |
73 | val placeholderService = PlaceholderService::class.service
74 |
75 | val placeholders = Static.PLACEHOLDER_PATTERN
76 | .findAll(this)
77 | .map { matchResult -> matchResult.groupValues[1] }.toList()
78 | val replacements = placeholders.mapNotNull { placeholder ->
79 | val replacement = placeholderService.parse(placeholder, source, observer) ?: return@mapNotNull null
80 | val replacementString = if (replacement is Text) {
81 | TextSerializers.FORMATTING_CODE.serialize(replacement)
82 | } else {
83 | replacement.toString()
84 | }
85 | "%$placeholder%" to replacementString
86 | }.toMap()
87 |
88 | return this.replace(replacements)
89 | }
90 |
91 | fun String.tryAsByteItem(failMessage: String? = null): ItemStackSnapshot {
92 | if (!Sponge.getPluginManager().getPlugin("byte-items").isPresent) {
93 | // fall back to normal minecraft item types
94 | val itemType = Sponge.getRegistry().getType(ItemType::class.java, this)
95 | .orElseThrow { IllegalArgumentException("Couldn't find ItemType '$this'!") }
96 | return ItemStack.of(itemType, 1).createSnapshot()
97 | }
98 |
99 | val byteItemsApi = ByteItemsApi::class.service
100 | return if (failMessage != null) {
101 | byteItemsApi.getItemSafely(id = this, failMessage = failMessage)
102 | } else {
103 | byteItemsApi.getItemSafely(id = this)
104 | }
105 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Texts.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.Sponge
4 | import org.spongepowered.api.text.Text
5 | import org.spongepowered.api.text.action.ClickAction
6 | import org.spongepowered.api.text.action.HoverAction
7 | import org.spongepowered.api.text.action.ShiftClickAction
8 | import org.spongepowered.api.text.action.TextAction
9 | import org.spongepowered.api.text.channel.MessageChannel
10 | import org.spongepowered.api.text.channel.MessageReceiver
11 | import org.spongepowered.api.text.format.*
12 | import org.spongepowered.api.text.serializer.TextSerializers
13 |
14 | fun Text.format(format: TextFormat): Text = toBuilder().format(format).build()
15 |
16 | fun Text.color(color: TextColor): Text = format(format.color(color))
17 |
18 | fun Text.aqua(): Text = color(TextColors.AQUA)
19 | fun Text.black(): Text = color(TextColors.BLACK)
20 | fun Text.blue(): Text = color(TextColors.BLUE)
21 | fun Text.darkAqua(): Text = color(TextColors.DARK_AQUA)
22 | fun Text.darkBlue(): Text = color(TextColors.DARK_BLUE)
23 | fun Text.darkGray(): Text = color(TextColors.DARK_GRAY)
24 | fun Text.darkGreen(): Text = color(TextColors.DARK_GREEN)
25 | fun Text.darkPurple(): Text = color(TextColors.DARK_PURPLE)
26 | fun Text.darkRed(): Text = color(TextColors.DARK_RED)
27 | fun Text.gold(): Text = color(TextColors.GOLD)
28 | fun Text.gray(): Text = color(TextColors.GRAY)
29 | fun Text.green(): Text = color(TextColors.GREEN)
30 | fun Text.lightPurple(): Text = color(TextColors.LIGHT_PURPLE)
31 | fun Text.red(): Text = color(TextColors.RED)
32 | fun Text.white(): Text = color(TextColors.WHITE)
33 | fun Text.yellow(): Text = color(TextColors.YELLOW)
34 |
35 | fun Text.style(style: TextStyle): Text = format(format.style(style))
36 |
37 | fun Text.bold(): Text = style(TextStyles.BOLD)
38 | fun Text.italic(): Text = style(TextStyles.ITALIC)
39 | fun Text.obfuscated(): Text = style(TextStyles.OBFUSCATED)
40 | fun Text.reset(): Text = style(TextStyles.RESET)
41 | fun Text.strikethrough(): Text = style(TextStyles.STRIKETHROUGH)
42 | fun Text.underline(): Text = style(TextStyles.UNDERLINE)
43 |
44 | fun > Text.action(action: T): Text {
45 | return when (action) {
46 | is ClickAction<*> -> toBuilder().onClick(action)
47 | is ShiftClickAction<*> -> toBuilder().onShiftClick(action)
48 | is HoverAction<*> -> toBuilder().onHover(action)
49 | else -> return this
50 | }.build()
51 | }
52 |
53 | operator fun Text.plus(other: Text): Text = Text.of(this, other)
54 | operator fun Text.plus(other: String): Text = this + other.toText()
55 |
56 | fun Text.serialize() = TextSerializers.FORMATTING_CODE.serialize(this)
57 |
58 | // sending texts
59 | fun Text.sendTo(vararg messageChannels: MessageChannel) {
60 | if (!isEmpty) messageChannels.forEach { it.send(this) }
61 | }
62 |
63 | fun Iterable.sendTo(vararg messageChannels: MessageChannel) = forEach { it.sendTo(*messageChannels) }
64 |
65 | fun Text.sendTo(vararg receivers: MessageReceiver) = sendTo(receivers.asIterable())
66 | fun Text.sendTo(receivers: Iterable) {
67 | if (!isEmpty) receivers.forEach { it.sendMessage(this) }
68 | }
69 |
70 | fun Iterable.sendTo(vararg receivers: MessageReceiver) = sendTo(receivers.asIterable())
71 | fun Iterable.sendTo(receivers: Iterable) = forEach { it.sendTo(receivers) }
72 |
73 | fun Text.broadcast() = sendTo(Sponge.getServer().broadcastChannel)
74 | fun Iterable.broadcast() = sendTo(Sponge.getServer().broadcastChannel)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Utils.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import de.randombyte.ktskript.KtSkriptPlugin
4 | import org.spongepowered.api.CatalogType
5 | import org.spongepowered.api.data.DataHolder
6 | import org.spongepowered.api.data.key.Keys
7 | import org.spongepowered.api.entity.living.player.User
8 | import org.spongepowered.api.util.Identifiable
9 |
10 | inline val KtSkript: KtSkriptPlugin get() = PluginManager.getPlugin(KtSkriptPlugin.ID).get().instance.get() as KtSkriptPlugin
11 |
12 | val Any.bestName: String get() = when {
13 | this is User -> name
14 | this is DataHolder && supports(Keys.DISPLAY_NAME) -> get(Keys.DISPLAY_NAME).get().toPlain()
15 | this is CatalogType -> id
16 | this is Identifiable -> uniqueId.toString()
17 | else -> this::class.java.name
18 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Uuids.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import org.spongepowered.api.Sponge
4 | import org.spongepowered.api.entity.living.player.Player
5 | import org.spongepowered.api.entity.living.player.User
6 | import org.spongepowered.api.service.user.UserStorageService
7 | import org.spongepowered.api.world.World
8 | import java.util.*
9 |
10 | fun String.toUUID(): UUID = UUID.fromString(this)
11 |
12 | fun UUID.getPlayer(): Player? = Sponge.getServer().getPlayer(this).orNull()
13 | fun UUID.getUser(): User? = UserStorageService::class.service.get(this).orNull()
14 | fun UUID.getWorld(): World? = Sponge.getServer().getWorld(this).orNull()
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Vectors.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import com.flowpowered.math.vector.Vector3d
4 | import com.flowpowered.math.vector.Vector3i
5 |
6 | fun v3(x: Double, y: Double, z: Double) = Vector3d(x, y, z)
7 | fun v3(x: Int, y: Int, z: Int) = Vector3i(x, y, z)
8 |
9 | fun Vector3i.copy(newX: Int = x, newY: Int = y, newZ: Int = z) = Vector3i(newX, newY, newZ)
10 | fun Vector3d.copy(newX: Double = x, newY: Double = y, newZ: Double = z) = Vector3d(newX, newY, newZ)
11 |
12 | operator fun Vector3i.rangeTo(that: Vector3i) = Vector3iRange(this, that)
13 |
14 | /**
15 | * Iterates over all positions between [start] and [endInclusive].
16 | */
17 | class Vector3iRange(override val start: Vector3i, override val endInclusive: Vector3i) : ClosedRange, Iterable {
18 |
19 | override fun contains(value: Vector3i) =
20 | (start.x..endInclusive.x).contains(value.x) &&
21 | (start.y..endInclusive.y).contains(value.y) &&
22 | (start.z..endInclusive.z).contains(value.z)
23 |
24 | override fun iterator(): Iterator = Vector3iProgressionIterator(start, endInclusive)
25 |
26 | internal class Vector3iProgressionIterator(private val start: Vector3i, private val end: Vector3i): Iterator {
27 | private var next = start
28 |
29 | override fun hasNext() = next.x <= end.x && next.y <= end.y && next.z <= end.z
30 |
31 | override fun next(): Vector3i {
32 | val value = next
33 | if (hasNext()) {
34 | next = next.add(1, 0, 0)
35 | if (next.x > end.x) next = Vector3i(start.x, next.y + 1, next.z)
36 | if (next.y > end.y) next = Vector3i(next.x, start.y, next.z + 1)
37 | }
38 | return value
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/Viewers.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils
2 |
3 | import com.flowpowered.math.vector.Vector3i
4 | import org.spongepowered.api.effect.Viewer
5 | import org.spongepowered.api.effect.particle.ParticleEffect
6 |
7 | // todo remove?
8 | fun Viewer.spawnParticles(particleEffect: ParticleEffect, position: Vector3i) = spawnParticles(particleEffect, position.toDouble())
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/commands/CommandElements.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.commands
2 |
3 | import de.randombyte.ktskript.utils.t
4 | import org.spongepowered.api.CatalogType
5 | import org.spongepowered.api.command.args.GenericArguments.*
6 |
7 | fun boolean(key: String) = bool(key.t)
8 |
9 | fun string(key: String) = string(key.t)
10 |
11 | fun remainingStrings(key: String) = remainingRawJoinedStrings(key.t)
12 |
13 | fun integer(key: String) = integer(key.t)
14 |
15 | fun double(key: String) = doubleNum(key.t)
16 |
17 | fun choice(key: String, vararg choices: String) = choices(key.t, choices.associateBy { it })
18 |
19 | fun choice(key: String, choices: Map) = choices(key.t, choices)
20 |
21 | fun player(key: String) = player(key.t)
22 |
23 | fun user(key: String) = user(key.t)
24 |
25 | inline fun catalogedElement(key: String) = catalogedElement(key.t, T::class.java)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/commands/CommandSources.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.commands
2 |
3 | import de.randombyte.ktskript.utils.CommandManager
4 | import org.spongepowered.api.command.CommandSource
5 |
6 | fun CommandSource.executeCommand(command: String) = CommandManager.process(this, command)
7 | fun Iterable.executeCommand(command: String) = forEach { it.executeCommand(command) }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/commands/Commands.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.commands
2 |
3 | import de.randombyte.ktskript.utils.CommandManager
4 | import de.randombyte.ktskript.utils.KtSkript
5 | import de.randombyte.ktskript.utils.t
6 | import org.spongepowered.api.command.CommandException
7 | import org.spongepowered.api.command.CommandResult
8 | import org.spongepowered.api.command.CommandSource
9 | import org.spongepowered.api.command.args.CommandContext
10 | import org.spongepowered.api.command.spec.CommandSpec
11 | import org.spongepowered.api.entity.living.player.Player
12 | import org.spongepowered.api.text.Text
13 |
14 | fun registerCommand(vararg names: String, commandBuilder: CommandSpec.Builder.() -> Unit) {
15 | CommandManager.register(KtSkript, command(commandBuilder), *names)
16 | }
17 |
18 | fun command(commandBuilder: CommandSpec.Builder.() -> Unit): CommandSpec {
19 | val builder = CommandSpec.builder()
20 | commandBuilder.invoke(builder)
21 | return builder.build()
22 | }
23 |
24 | fun CommandSpec.Builder.child(vararg names: String, commandBuilder: CommandSpec.Builder.() -> Unit) = child(command(commandBuilder), *names)
25 |
26 | fun CommandSpec.Builder.action(onlyPlayers: Boolean = false, executor: CommandExecutorContext.() -> Unit) {
27 | executor { src, args ->
28 | if (onlyPlayers && src !is Player) throw CommandException("Command must be executed by a player!".t)
29 | val result = executor(CommandExecutorContext(src, args))
30 | return@executor result as? CommandResult ?: CommandResult.success()
31 | }
32 | }
33 |
34 | fun commandError(errorText: Text): Nothing = throw CommandException(errorText)
35 |
36 | data class CommandExecutorContext(val commandSource: CommandSource, val arguments: CommandContext) {
37 | val player: Player
38 | get() {
39 | if (commandSource !is Player) {
40 | throw CommandException("The command source is not a player! Use 'action(onlyPlayers = true) { ... }'.".t)
41 | }
42 | return commandSource
43 | }
44 |
45 | fun argument(key: String): T = arguments.getOne(key).orElseThrow {
46 | CommandException("Argument '$key' is not present!".t)
47 | }
48 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/events/AffectedObjectsEvents.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.events
2 |
3 | import org.spongepowered.api.block.BlockSnapshot
4 | import org.spongepowered.api.data.Transaction
5 | import org.spongepowered.api.entity.Entity
6 | import org.spongepowered.api.event.block.ChangeBlockEvent
7 | import org.spongepowered.api.event.entity.AffectEntityEvent
8 |
9 | val ChangeBlockEvent.blockChanges: MutableList>
10 | get() = transactions
11 |
12 | val AffectEntityEvent.affectedEntities: MutableList
13 | get() = entities
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/events/Events.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.events
2 |
3 | import de.randombyte.ktskript.script.UnloadScriptsEvent
4 | import de.randombyte.ktskript.utils.EventManager
5 | import de.randombyte.ktskript.utils.KtSkript
6 | import org.spongepowered.api.entity.EntityTypes
7 | import org.spongepowered.api.entity.living.player.Player
8 | import org.spongepowered.api.event.Event
9 | import org.spongepowered.api.event.block.ChangeBlockEvent
10 | import org.spongepowered.api.event.block.InteractBlockEvent
11 | import org.spongepowered.api.event.entity.*
12 | import org.spongepowered.api.event.game.state.GameStartedServerEvent
13 | import org.spongepowered.api.event.game.state.GameStartingServerEvent
14 | import org.spongepowered.api.event.game.state.GameStoppedServerEvent
15 | import org.spongepowered.api.event.game.state.GameStoppingServerEvent
16 | import org.spongepowered.api.event.network.ClientConnectionEvent
17 |
18 | fun registerListener(eventClass: Class, executor: (T) -> Unit) {
19 | EventManager.registerListener(KtSkript, eventClass, executor::invoke)
20 | }
21 |
22 | inline fun registerListener(noinline executor: T.() -> Unit) = registerListener(T::class.java, executor)
23 |
24 | // === EVENTS ===
25 |
26 | // INTERACTION
27 |
28 | fun onBlockLeftClick(executor: InteractBlockEvent.Primary.MainHand.() -> Unit) = registerListener(executor)
29 |
30 | fun onBlockRightClick(executor: InteractBlockEvent.Secondary.MainHand.() -> Unit) = registerListener(executor)
31 |
32 | fun onEntityLeftClick(executor: InteractEntityEvent.Primary.MainHand.() -> Unit) = registerListener(executor)
33 |
34 | fun onEntityRightClick(executor: InteractEntityEvent.Secondary.MainHand.() -> Unit) = registerListener(executor)
35 |
36 | // MOVE
37 |
38 | fun onEntityMove(executor: MoveEntityEvent.() -> Unit) = registerListener(executor)
39 |
40 | fun onPlayerMove(executor: MoveEntityEvent.() -> Unit) = onEntityMove { if (targetEntity.type == EntityTypes.PLAYER) executor() }
41 |
42 | // BLOCKS
43 |
44 | fun onBlockBreak(executor: ChangeBlockEvent.Break.() -> Unit) = registerListener(executor)
45 |
46 | fun onBlockPlace(executor: ChangeBlockEvent.Place.() -> Unit) = registerListener(executor)
47 |
48 | // ENTITIES
49 |
50 | fun onEntitySpawn(executor: SpawnEntityEvent.() -> Unit) = registerListener(executor)
51 |
52 | fun onEntityDamage(executor: DamageEntityEvent.() -> Unit) = registerListener(executor)
53 |
54 | fun onEntityRemove(executor: DestructEntityEvent.() -> Unit) = registerListener(executor)
55 |
56 | fun onEntityDeath(executor: DestructEntityEvent.Death.() -> Unit) = registerListener(executor)
57 |
58 | // PLAYERS
59 |
60 | fun onPlayerLogin(executor: ClientConnectionEvent.Login.() -> Unit) = registerListener(executor)
61 |
62 | fun onPlayerJoin(executor: ClientConnectionEvent.Join.() -> Unit) = registerListener(executor)
63 |
64 | fun onPlayerLeave(executor: ClientConnectionEvent.Disconnect.() -> Unit) = registerListener(executor)
65 |
66 | fun onPlayerDamage(executor: DamageEntityEvent.() -> Unit) = onEntityDamage { if (targetEntity is Player) executor() }
67 |
68 | fun onPlayerDeath(executor: DestructEntityEvent.Death.() -> Unit) = onEntityDeath { if (targetEntity is Player) executor() }
69 |
70 | // SERVER
71 |
72 | fun onServerStarting(executor: GameStartingServerEvent.() -> Unit) = registerListener(executor)
73 |
74 | fun onServerStarted(executor: GameStartedServerEvent.() -> Unit) = registerListener(executor)
75 |
76 | fun onServerStopping(executor: GameStoppingServerEvent.() -> Unit) = registerListener(executor)
77 |
78 | fun onServerStopped(executor: GameStoppedServerEvent.() -> Unit) = registerListener(executor)
79 |
80 | // OTHERS
81 |
82 | fun onScriptsUnload(executor: UnloadScriptsEvent.() -> Unit) = registerListener(executor)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/events/General.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.events
2 |
3 | import org.spongepowered.api.entity.living.player.Player
4 | import org.spongepowered.api.event.Cancellable
5 | import org.spongepowered.api.event.Event
6 |
7 | val Event.causedByPlayer: Boolean
8 | get() = cause.containsType(Player::class.java)
9 |
10 | val Event.causingPlayer: Player
11 | get() = cause.first(Player::class.java).orElseThrow { RuntimeException("No causing player available!") }
12 |
13 | fun Cancellable.cancelEvent() = setCancelled(true)
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/events/InteractBlockEvents.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.events
2 |
3 | import org.spongepowered.api.block.BlockSnapshot
4 | import org.spongepowered.api.event.block.InteractBlockEvent
5 |
6 | val InteractBlockEvent.clickedInAir: Boolean
7 | get() = targetBlock == BlockSnapshot.NONE
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/events/TargetEntityEvents.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.events
2 |
3 | import org.spongepowered.api.entity.living.player.Player
4 | import org.spongepowered.api.event.entity.TargetEntityEvent
5 |
6 | val TargetEntityEvent.player: Player
7 | get() = (targetEntity as? Player) ?: throw RuntimeException("The 'targetEntity' is not a Player!")
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/particles/Builders.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.particles
2 |
3 | import com.flowpowered.math.vector.Vector3d
4 | import org.spongepowered.api.block.BlockState
5 | import org.spongepowered.api.data.type.NotePitch
6 | import org.spongepowered.api.effect.particle.ParticleEffect
7 | import org.spongepowered.api.effect.particle.ParticleOptions
8 | import org.spongepowered.api.effect.particle.ParticleTypes
9 | import org.spongepowered.api.item.FireworkEffect
10 | import org.spongepowered.api.util.Color
11 |
12 | fun particleEffect(configurator: ParticleEffect.Builder.() -> Unit) = ParticleEffect.builder().apply {
13 | // setting some default values, todo remove?
14 | type(ParticleTypes.REDSTONE_DUST)
15 | velocity(Vector3d(0.5, 0.5, 0.5))
16 | quantity(10)
17 | offset(Vector3d.ZERO)
18 |
19 | configurator.invoke(this)
20 | }.build()
21 |
22 | fun ParticleEffect.Builder.blockState(blockState: BlockState) = option(ParticleOptions.BLOCK_STATE, blockState)
23 | fun ParticleEffect.Builder.color(color: Color) = option(ParticleOptions.COLOR, color)
24 | fun ParticleEffect.Builder.note(notePitch: NotePitch) = option(ParticleOptions.NOTE, notePitch)
25 | fun ParticleEffect.Builder.fireworkEffects(fireworksEffects: List) = option(ParticleOptions.FIREWORK_EFFECTS, fireworksEffects)
26 |
27 | fun fireworkEffect(configurator: FireworkEffect.Builder.() -> Unit) = FireworkEffect.builder().apply {
28 | configurator.invoke(this)
29 | }.build()
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/serializers/SimpleDateTypeSerializer.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.serializers
2 |
3 | import com.google.common.reflect.TypeToken
4 | import de.randombyte.ktskript.utils.Dates
5 | import ninja.leaping.configurate.ConfigurationNode
6 | import ninja.leaping.configurate.objectmapping.ObjectMappingException
7 | import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer
8 | import java.text.ParseException
9 | import java.text.SimpleDateFormat
10 | import java.util.*
11 |
12 | object SimpleDateTypeSerializer : TypeSerializer {
13 | override fun deserialize(type: TypeToken<*>, value: ConfigurationNode): Date = Dates.deserialize(value.string)
14 |
15 | override fun serialize(type: TypeToken<*>, date: Date, value: ConfigurationNode) {
16 | value.value = Dates.serialize(date)
17 | }
18 | }
--------------------------------------------------------------------------------
/src/main/kotlin/de/randombyte/ktskript/utils/serializers/SimpleDurationTypeSerializer.kt:
--------------------------------------------------------------------------------
1 | package de.randombyte.ktskript.utils.serializers
2 |
3 | import com.google.common.reflect.TypeToken
4 | import de.randombyte.ktskript.utils.Durations
5 | import ninja.leaping.configurate.ConfigurationNode
6 | import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer
7 | import java.time.Duration
8 |
9 | /**
10 | * See [Durations] for how the duration is formatted.
11 | */
12 | object SimpleDurationTypeSerializer : TypeSerializer {
13 | override fun deserialize(type: TypeToken<*>, node: ConfigurationNode) = Durations.deserialize(node.string)
14 |
15 | override fun serialize(type: TypeToken<*>, duration: Duration, node: ConfigurationNode) {
16 | node.value = Durations.serialize(duration)
17 | }
18 | }
--------------------------------------------------------------------------------
/src/main/resources/assets/kt-skript/default.imports:
--------------------------------------------------------------------------------
1 | !!
2 |
3 | kotlin
4 | -kotlin.reflect
5 | -kotlin.internal
6 |
7 | java
8 | -java.awt
9 | -java.applet
10 |
11 | de.randombyte.ktskript
12 | -de.randombyte.ktskript.shaded
13 |
14 | org.spongepowered.api
15 | com.flowpowered.math
16 |
--------------------------------------------------------------------------------